@runtypelabs/persona 1.38.1 → 1.38.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +29 -29
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +28 -0
- package/dist/index.d.ts +28 -0
- package/dist/index.global.js +44 -44
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +29 -29
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/session.ts +58 -0
- package/src/types.ts +15 -0
- package/src/ui.ts +60 -10
- package/src/utils/actions.ts +10 -5
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,"\\"),
|
|
1
|
+
"use strict";var Mi=Object.create;var _n=Object.defineProperty;var Ei=Object.getOwnPropertyDescriptor;var Wi=Object.getOwnPropertyNames;var ki=Object.getPrototypeOf,Li=Object.prototype.hasOwnProperty;var Pi=(e,n)=>{for(var o in n)_n(e,o,{get:n[o],enumerable:!0})},Lr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of Wi(n))!Li.call(e,r)&&r!==o&&_n(e,r,{get:()=>n[r],enumerable:!(t=Ei(n,r))||t.enumerable});return e};var Hi=(e,n,o)=>(o=e!=null?Mi(ki(e)):{},Lr(n||!e||!e.__esModule?_n(o,"default",{value:e,enumerable:!0}):o,e)),Bi=e=>Lr(_n({},"__esModule",{value:!0}),e);var ba={};Pi(ba,{AgentWidgetClient:()=>Qt,AgentWidgetSession:()=>an,AttachmentManager:()=>Zt,DEFAULT_DARK_THEME:()=>ks,DEFAULT_LIGHT_THEME:()=>Ws,DEFAULT_WIDGET_CONFIG:()=>Be,VERSION:()=>nn,attachHeaderToContainer:()=>en,buildComposer:()=>dn,buildDefaultHeader:()=>vs,buildExpandedHeader:()=>Cs,buildHeader:()=>Ut,buildHeaderWithLayout:()=>ln,buildMinimalHeader:()=>bs,componentRegistry:()=>gn,createActionManager:()=>Rn,createAgentExperience:()=>ds,createBubbleWithLayout:()=>ii,createCSATFeedback:()=>as,createComponentMiddleware:()=>mi,createComponentStreamParser:()=>ss,createDirectivePostprocessor:()=>Rr,createFlexibleJsonStreamParser:()=>Nr,createImagePart:()=>Yr,createJsonStreamParser:()=>Kn,createLocalStorageAdapter:()=>ns,createMarkdownProcessor:()=>Wn,createMarkdownProcessorFromConfig:()=>kn,createMessageActions:()=>Ss,createNPSFeedback:()=>ls,createPlainTextParser:()=>Jn,createRegexJsonParser:()=>Yn,createStandardBubble:()=>cn,createTextPart:()=>Xn,createTypingIndicator:()=>Hn,createXmlParser:()=>Vn,default:()=>va,defaultActionHandlers:()=>tn,defaultJsonActionParser:()=>In,directivePostprocessor:()=>Fr,escapeHtml:()=>qn,extractComponentDirectiveFromMessage:()=>is,fileToImagePart:()=>Kr,generateAssistantMessageId:()=>rn,generateCodeSnippet:()=>Si,generateMessageId:()=>_r,generateUserMessageId:()=>Ln,getDisplayText:()=>Ur,getHeaderLayout:()=>xs,getImageParts:()=>Jr,hasComponentDirective:()=>rs,hasImages:()=>zr,headerLayouts:()=>es,initAgentWidget:()=>Is,isComponentDirectiveType:()=>gi,markdownPostprocessor:()=>fs,mergeWithDefaults:()=>ts,normalizeContent:()=>qr,pluginRegistry:()=>Bn,renderComponentDirective:()=>os,validateImageFile:()=>Vr});module.exports=Bi(ba);var Hr=require("marked"),Ii=e=>{if(e)return e},Wn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Hr.Marked({gfm:(r=n==null?void 0:n.gfm)!=null?r:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),t=Ii(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},kn=e=>e?Wn({markedOptions:e.options,renderer:e.renderer}):Wn(),Ri=Wn(),fs=e=>Ri(e),qn=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Br=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Pr=e=>`%%FORM_PLACEHOLDER_${e}%%`,Ir=(e,n)=>{let o=e;return o=o.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(t,r)=>{try{let s=JSON.parse(r.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Pr(n.length);return n.push({token:i,type:String(s.type)}),i}}catch{return t}return t}),o=o.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(t,r)=>{let s=Pr(n.length);return n.push({token:s,type:r}),s}),o},Rr=e=>{let n=kn(e);return o=>{let t=[],r=Ir(o,t),s=n(r);return t.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),f=`<div class="tvw-form-directive" data-tv-form="${Br(a)}"></div>`;s=s.replace(d,f)}),s}},Fr=e=>{let n=[],o=Ir(e,n),t=fs(o);return n.forEach(({token:r,type:s})=>{let i=new RegExp(r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Br(s)}"></div>`;t=t.replace(i,d)}),t};var qt=require("partial-json"),Un=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ws=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Fi=e=>{var i,a;let n=(i=e.completedAt)!=null?i:Date.now(),o=(a=e.startedAt)!=null?a:n,r=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-o))/1e3;return r<.1?"Thought for <0.1 seconds":`Thought for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`},$r=e=>e.status==="complete"?Fi(e):e.status==="pending"?"Waiting":"",$i=e=>{var r,s,i;let o=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((i=(s=e.startedAt)!=null?s:e.completedAt)!=null?i:Date.now())))/1e3;return o<.1?"Used tool for <0.1 seconds":`Used tool for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`};var Or=e=>e.status==="complete"?$i(e):"Using tool...",Oi=()=>{let e=null,n=0,o=t=>{let r=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=t.match(r);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
3
3
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=t.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},_n=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},qn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Un=()=>{var n;let e=Ri();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)}},zn=()=>{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,_t.parse)(o,_t.STR|_t.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Dn(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Dn(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Fr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Dn(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Dn(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,_t.parse)(s,_t.STR|_t.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Jn=()=>{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 Fi="https://api.runtype.com/v1/dispatch",$r="https://api.runtype.com",Or=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 $i(e){switch(e){case"json":return zn;case"regex-json":return Un;case"xml":return Jn;case"plain":default:return qn}}var Gt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Fi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:$i(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$/,""))||$r;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(n=this.config).onSessionInit)==null||o.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||$r}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.message_id)throw new Error(`message_id is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:n,type:o})}async submitCSATFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:n,comment:o})}async submitNPSFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="session_id")):void 0,g={session_id:d.sessionId,messages:n.messages.filter(Or).map(w=>{var h,F,T;return{id:w.id,role:w.role,content:(T=(F=(h=w.contentParts)!=null?h:w.llmContent)!=null?F:w.rawContent)!=null?T:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",g);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(g),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 F=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:F}),F}if(m.status===429){let F=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:F}),F}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Or).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,ke,Ke,Wt,ft,rt,H,wt,yt,At,te,we,Fe,vt,et,Bt,It,Ot,nn,Nt,Le,gn,mn,jt,Bn,In,hn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=L=>{let ae=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,xe=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,De=L.tools?L.tools.map(tt=>({...tt,chunks:tt.chunks?[...tt.chunks]:void 0})):void 0;return{...L,reasoning:ae,toolCall:xe,tools:De}},g=L=>{o({type:"message",message:f(L)})},m=null,w={current:null},h=new Map,F=new Map,T={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},S=L=>{if(L==null)return null;try{return String(L)}catch{return null}},R=L=>{var ae,xe,De,tt,Ve;return S((Ve=(tt=(De=(xe=(ae=L.stepId)!=null?ae:L.step_id)!=null?xe:L.step)!=null?De:L.parentId)!=null?tt:L.flowStepId)!=null?Ve:L.flow_step_id)},v=L=>{var ae,xe,De,tt,Ve,Pe,E;return S((E=(Pe=(Ve=(tt=(De=(xe=(ae=L.callId)!=null?ae:L.call_id)!=null?xe:L.requestId)!=null?De:L.request_id)!=null?tt:L.toolCallId)!=null?Ve:L.tool_call_id)!=null?Pe:L.stepId)!=null?E:L.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},g(m),m),C=(L,ae)=>{T.lastId=ae,L&&T.byStep.set(L,ae)},k=(L,ae)=>{var Ve;let xe=(Ve=L.reasoningId)!=null?Ve:L.id,De=R(L);if(xe){let Pe=String(xe);return C(De,Pe),Pe}if(De){let Pe=T.byStep.get(De);if(Pe)return T.lastId=Pe,Pe}if(T.lastId&&!ae)return T.lastId;if(!ae)return null;let tt=`reason-${u()}`;return C(De,tt),tt},K=L=>{let ae=h.get(L);if(ae)return ae;let xe={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:L,status:"streaming",chunks:[]}};return h.set(L,xe),g(xe),xe},J=(L,ae)=>{y.lastId=ae,L&&y.byCall.set(L,ae)},z=(L,ae)=>{var Ve;let xe=(Ve=L.toolId)!=null?Ve:L.id,De=v(L);if(xe){let Pe=String(xe);return J(De,Pe),Pe}if(De){let Pe=y.byCall.get(De);if(Pe)return y.lastId=Pe,Pe}if(y.lastId&&!ae)return y.lastId;if(!ae)return null;let tt=`tool-${u()}`;return J(De,tt),tt},_=L=>{let ae=F.get(L);if(ae)return ae;let xe={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:L,status:"pending"}};return F.set(L,xe),g(xe),xe},j=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ae=Number(L);if(!Number.isNaN(ae)&&Number.isFinite(ae))return ae;let xe=Date.parse(L);if(!Number.isNaN(xe))return xe}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},B=new Map,V=new Map;for(;;){let{done:L,value:ae}=await r.read();if(L)break;i+=s.decode(ae,{stream:!0});let xe=i.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>e,processChunk:async t=>{if(t.length<=n)return e!==null?{text:e,raw:t}:null;let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;let s=o(t);return s!==null&&(e=s),n=t.length,e!==null?{text:e,raw:t}:null},close:async()=>{}}},zn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Jn=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Yn=()=>{var n;let e=Oi();return{processChunk:async o=>{let t=o.trim();return!t.startsWith("{")&&!t.startsWith("[")?null:e.processChunk(o)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Kn=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e!==null||e===""?{text:e||"",raw:o}:null;try{let r=(0,qt.parse)(o,qt.STR|qt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?Un(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=Un(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Nr=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Un(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Un(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=o)return n!==null?{text:n,raw:s}:null;try{let a=(0,qt.parse)(s,qt.STR|qt.OBJ),d=r(a);d!==null&&(n=d)}catch{}return o=s.length,{text:n||"",raw:s}},close:()=>{}}},Vn=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let t=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return t&&t[1]?(e=t[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var Ni="https://api.runtype.com/v1/dispatch",jr="https://api.runtype.com",Dr=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function ji(e){switch(e){case"json":return Kn;case"regex-json":return Yn;case"xml":return Vn;case"plain":default:return Jn}}var Qt=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var o,t,r;this.apiUrl=(o=n.apiUrl)!=null?o:Ni,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:ji(n.parserType),this.contextProviders=(r=n.contextProviders)!=null?r:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}isClientTokenMode(){return!!this.config.clientToken}getClientApiUrl(n){var t;let o=((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr;return n==="init"?`${o}/v1/client/init`:`${o}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,o;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let t=await this.sessionInitPromise;return this.clientSession=t,(o=(n=this.config).onSessionInit)==null||o.call(n,t),t}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,o={token:this.config.clientToken,...this.config.flowId&&{flow_id:this.config.flowId},...n&&{session_id:n}},t=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!t.ok){let a=await t.json().catch(()=>({error:"Session initialization failed"}));throw t.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):t.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let r=await t.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(r.session_id),{sessionId:r.session_id,expiresAt:new Date(r.expires_at),flow:r.flow,config:{welcomeMessage:r.config.welcome_message,placeholder:r.config.placeholder,theme:r.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||jr}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.message_id)throw new Error(`message_id is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let r=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let a=await r.json().catch(()=>({error:"Feedback submission failed"}));throw r.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,message_id:n,type:o})}async submitCSATFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"csat",rating:n,comment:o})}async submitNPSFeedback(n,o){let t=this.getClientSession();if(!t)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({session_id:t.sessionId,type:"nps",rating:n,comment:o})}async dispatch(n,o){return this.isClientTokenMode()?this.dispatchClientToken(n,o):this.dispatchProxy(n,o)}async dispatchClientToken(n,o){var r,s,i,a;let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(r=this.config).onSessionExpired)==null||s.call(r);let w=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:w}),w}let u=await this.buildPayload(n.messages),f=u.metadata?Object.fromEntries(Object.entries(u.metadata).filter(([w])=>w!=="session_id")):void 0,p={session_id:d.sessionId,messages:n.messages.filter(Dr).map(w=>{var h,R,M;return{id:w.id,role:w.role,content:(M=(R=(h=w.contentParts)!=null?h:w.llmContent)!=null?R:w.rawContent)!=null?M:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...u.context&&{context:u.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:t.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let R=new Error("Session expired. Please refresh to continue.");throw o({type:"error",error:R}),R}if(m.status===429){let R=new Error(w.hint||"Message limit reached for this session.");throw o({type:"error",error:R}),R}let h=new Error(w.error||"Failed to send message");throw o({type:"error",error:h}),h}if(!m.body){let w=new Error("No response body received");throw o({type:"error",error:w}),w}o({type:"status",status:"connected"});try{await this.streamResponse(m.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let u=d instanceof Error?d:new Error(String(d));throw!u.message.includes("Session expired")&&!u.message.includes("Message limit")&&o({type:"error",error:u}),u}}async dispatchProxy(n,o){let t=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>t.abort()),o({type:"status",status:"connecting"});let r=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",r);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal},r)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw o({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(r),signal:t.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw o({type:"error",error:a}),a}o({type:"status",status:"connected"});try{await this.streamResponse(i.body,o)}finally{o({type:"status",status:"idle"})}}async buildPayload(n){let t={messages:n.slice().filter(Dr).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i,a;return{role:r.role,content:(a=(i=(s=r.contentParts)!=null?s:r.llmContent)!=null?i:r.rawContent)!=null?a:r.content,createdAt:r.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let r={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(r,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(r).length&&(t.context=r)}if(this.requestMiddleware)try{let r=await this.requestMiddleware({payload:{...t},config:this.config});if(r&&typeof r=="object")return r}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",r)}return t}async handleCustomSSEEvent(n,o,t,r,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let a=()=>{if(t.current)return t.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return t.current=d,r(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,r(d)}return i.done&&(t.current&&(t.current.streaming=!1,r(t.current)),o({type:"status",status:"idle"})),i.error&&o({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(n,o,t){var Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P,te,we,Ge,St,ze,ft,Lt,Ht,fn,Kt,Fn,wn,sn,We,yn,vn,Dt,$n;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,u=()=>a+d++,f=B=>{let le=B.reasoning?{...B.reasoning,chunks:[...B.reasoning.chunks]}:void 0,he=B.toolCall?{...B.toolCall,chunks:B.toolCall.chunks?[...B.toolCall.chunks]:void 0}:void 0,Ee=B.tools?B.tools.map(Ze=>({...Ze,chunks:Ze.chunks?[...Ze.chunks]:void 0})):void 0;return{...B,reasoning:le,toolCall:he,tools:Ee}},p=B=>{o({type:"message",message:f(B)})},m=null,w={current:null},h=new Map,R=new Map,M={lastId:null,byStep:new Map},y={lastId:null,byCall:new Map},A=B=>{if(B==null)return null;try{return String(B)}catch{return null}},I=B=>{var le,he,Ee,Ze,ot;return A((ot=(Ze=(Ee=(he=(le=B.stepId)!=null?le:B.step_id)!=null?he:B.step)!=null?Ee:B.parentId)!=null?Ze:B.flowStepId)!=null?ot:B.flow_step_id)},v=B=>{var le,he,Ee,Ze,ot,$e,O;return A((O=($e=(ot=(Ze=(Ee=(he=(le=B.callId)!=null?le:B.call_id)!=null?he:B.requestId)!=null?Ee:B.request_id)!=null?Ze:B.toolCallId)!=null?ot:B.tool_call_id)!=null?$e:B.stepId)!=null?O:B.step_id)},N=()=>m||(m={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u()},p(m),m),C=(B,le)=>{M.lastId=le,B&&M.byStep.set(B,le)},k=(B,le)=>{var ot;let he=(ot=B.reasoningId)!=null?ot:B.id,Ee=I(B);if(he){let $e=String(he);return C(Ee,$e),$e}if(Ee){let $e=M.byStep.get(Ee);if($e)return M.lastId=$e,$e}if(M.lastId&&!le)return M.lastId;if(!le)return null;let Ze=`reason-${u()}`;return C(Ee,Ze),Ze},z=B=>{let le=h.get(B);if(le)return le;let he={id:`reason-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:B,status:"streaming",chunks:[]}};return h.set(B,he),p(he),he},_=(B,le)=>{y.lastId=le,B&&y.byCall.set(B,le)},ne=(B,le)=>{var ot;let he=(ot=B.toolId)!=null?ot:B.id,Ee=v(B);if(he){let $e=String(he);return _(Ee,$e),$e}if(Ee){let $e=y.byCall.get(Ee);if($e)return y.lastId=$e,$e}if(y.lastId&&!le)return y.lastId;if(!le)return null;let Ze=`tool-${u()}`;return _(Ee,Ze),Ze},re=B=>{let le=R.get(B);if(le)return le;let he={id:`tool-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:B,status:"pending"}};return R.set(B,he),p(he),he},V=B=>{if(typeof B=="number"&&Number.isFinite(B))return B;if(typeof B=="string"){let le=Number(B);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let he=Date.parse(B);if(!Number.isNaN(he))return he}return Date.now()},J=B=>{if(typeof B=="string")return B;if(B==null)return"";try{return JSON.stringify(B)}catch{return String(B)}},L=new Map,q=new Map;for(;;){let{done:B,value:le}=await r.read();if(B)break;i+=s.decode(le,{stream:!0});let he=i.split(`
|
|
5
5
|
|
|
6
|
-
`);i=(
|
|
7
|
-
`),Ve="message",Pe="";for(let se of tt)se.startsWith("event:")?Ve=se.replace("event:","").trim():se.startsWith("data:")&&(Pe+=se.replace("data:","").trim());if(!Pe)continue;let E;try{E=JSON.parse(Pe)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let bt=Ve!=="message"?Ve:(X=E.type)!=null?X:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(E,o,w,g,u);if(w.current&&!m&&(m=w.current),se)continue}if(bt==="reason_start"){let se=(D=k(E,!0))!=null?D:`reason-${u()}`,I=K(se);I.reasoning=(nt=I.reasoning)!=null?nt:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(dt=I.reasoning.startedAt)!=null?dt:j((lt=E.startedAt)!=null?lt:E.timestamp),I.reasoning.completedAt=void 0,I.reasoning.durationMs=void 0,I.streaming=!0,I.reasoning.status="streaming",g(I)}else if(bt==="reason_chunk"){let se=(Ft=(Lt=k(E,!1))!=null?Lt:k(E,!0))!=null?Ft:`reason-${u()}`,I=K(se);I.reasoning=(q=I.reasoning)!=null?q:{id:se,status:"streaming",chunks:[]},I.reasoning.startedAt=(ct=I.reasoning.startedAt)!=null?ct:j((fe=E.startedAt)!=null?fe:E.timestamp);let W=(pt=(Je=(ut=E.reasoningText)!=null?ut:E.text)!=null?Je:E.delta)!=null?pt:"";if(W&&E.hidden!==!0&&I.reasoning.chunks.push(String(W)),I.reasoning.status=E.done?"complete":"streaming",E.done){I.reasoning.completedAt=j(($t=E.completedAt)!=null?$t:E.timestamp);let U=(Pt=I.reasoning.startedAt)!=null?Pt:Date.now();I.reasoning.durationMs=Math.max(0,((Ht=I.reasoning.completedAt)!=null?Ht:Date.now())-U)}I.streaming=I.reasoning.status!=="complete",g(I)}else if(bt==="reason_complete"){let se=(je=($=k(E,!1))!=null?$:k(E,!0))!=null?je:`reason-${u()}`,I=h.get(se);if(I!=null&&I.reasoning){I.reasoning.status="complete",I.reasoning.completedAt=j((pe=E.completedAt)!=null?pe:E.timestamp);let U=(st=I.reasoning.startedAt)!=null?st:Date.now();I.reasoning.durationMs=Math.max(0,((ge=I.reasoning.completedAt)!=null?ge:Date.now())-U),I.streaming=!1,g(I)}let W=R(E);W&&T.byStep.delete(W)}else if(bt==="tool_start"){let se=(ot=z(E,!0))!=null?ot:`tool-${u()}`,I=_(se),W=(Ae=I.toolCall)!=null?Ae:{id:se,status:"pending"};W.name=(xt=E.toolName)!=null?xt:W.name,W.status="running",E.args!==void 0&&(W.args=E.args),W.startedAt=(ie=W.startedAt)!=null?ie:j((St=E.startedAt)!=null?St:E.timestamp),W.completedAt=void 0,W.durationMs=void 0,I.toolCall=W,I.streaming=!0,g(I)}else if(bt==="tool_chunk"){let se=(Ze=(Ye=z(E,!1))!=null?Ye:z(E,!0))!=null?Ze:`tool-${u()}`,I=_(se),W=(ke=I.toolCall)!=null?ke:{id:se,status:"running"};W.startedAt=(Wt=W.startedAt)!=null?Wt:j((Ke=E.startedAt)!=null?Ke:E.timestamp);let U=(H=(rt=(ft=E.text)!=null?ft:E.delta)!=null?rt:E.message)!=null?H:"";U&&(W.chunks=(wt=W.chunks)!=null?wt:[],W.chunks.push(String(U))),W.status="running",I.toolCall=W,I.streaming=!0,g(I)}else if(bt==="tool_complete"){let se=(At=(yt=z(E,!1))!=null?yt:z(E,!0))!=null?At:`tool-${u()}`,I=_(se),W=(te=I.toolCall)!=null?te:{id:se,status:"running"};if(W.status="complete",E.result!==void 0&&(W.result=E.result),typeof E.duration=="number"&&(W.duration=E.duration),W.completedAt=j((we=E.completedAt)!=null?we:E.timestamp),typeof E.duration=="number")W.durationMs=E.duration;else{let me=(Fe=W.startedAt)!=null?Fe:Date.now();W.durationMs=Math.max(0,((vt=W.completedAt)!=null?vt:Date.now())-me)}I.toolCall=W,I.streaming=!1,g(I);let U=v(E);U&&y.byCall.delete(U)}else if(bt==="step_chunk"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let W=N(),U=(Ot=(It=(Bt=(et=E.text)!=null?et:E.delta)!=null?Bt:E.content)!=null?It:E.chunk)!=null?Ot:"";if(U){let Te=((nn=V.get(W.id))!=null?nn:"")+U;W.rawContent=Te,B.has(W.id)||B.set(W.id,this.createStreamParser());let Xe=B.get(W.id),Ie=Te.trim().startsWith("{")||Te.trim().startsWith("[");if(Ie&&V.set(W.id,Te),Xe.__isPlainTextParser===!0){W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W);continue}let We=Xe.processChunk(Te);if(We instanceof Promise)We.then(be=>{var Ge;let Ce=typeof be=="string"?be:(Ge=be==null?void 0:be.text)!=null?Ge:null;if(Ce!==null&&Ce.trim()!==""){let Me=m;Me&&Me.id===W.id&&(Me.content=Ce,g(Me))}else if(!Ie&&!Te.trim().startsWith("<")){let Me=m;Me&&Me.id===W.id&&(Me.content+=U,V.delete(Me.id),B.delete(Me.id),Me.rawContent=void 0,g(Me))}}).catch(()=>{W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W)});else{let be=typeof We=="string"?We:(Nt=We==null?void 0:We.text)!=null?Nt:null;be!==null&&be.trim()!==""?(W.content=be,g(W)):!Ie&&!Te.trim().startsWith("<")&&(W.content+=U,V.delete(W.id),B.delete(W.id),W.rawContent=void 0,g(W))}}if(E.isComplete){let me=(gn=(Le=E.result)==null?void 0:Le.response)!=null?gn:W.content;if(me){let Te=V.get(W.id),Xe=Te!=null?Te:Y(me);W.rawContent=Xe;let Ie=B.get(W.id),_e=null,We=!1;if(Ie&&(_e=Ie.getExtractedText(),_e===null&&(_e=_n(Xe)),_e===null)){let be=Ie.processChunk(Xe);be instanceof Promise?(We=!0,be.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===W.id&&(Re.content=Ge,Re.streaming=!1,B.delete(Re.id),V.delete(Re.id),g(Re))}})):_e=typeof be=="string"?be:(mn=be==null?void 0:be.text)!=null?mn:null}if(!We){_e!==null&&_e.trim()!==""?W.content=_e:V.has(W.id)||(W.content=Y(me));let be=B.get(W.id);if(be){let Ce=(jt=be.close)==null?void 0:jt.call(be);Ce instanceof Promise&&Ce.catch(()=>{}),B.delete(W.id)}V.delete(W.id),W.streaming=!1,g(W)}}}}else if(bt==="step_complete"){let se=E.stepType,I=E.executionType;if(se==="tool"||I==="context")continue;let W=(Bn=E.result)==null?void 0:Bn.response,U=N();if(W!=null){let me=B.get(U.id),Te=!1,Xe=!1;if(me){let Ie=me.getExtractedText(),_e=V.get(U.id),We=_e!=null?_e:Y(W);if(U.rawContent=We,Ie!==null&&Ie.trim()!=="")U.content=Ie,Te=!0;else{let be=_n(We);if(be!==null)U.content=be,Te=!0;else{let Ce=me.processChunk(We);if(Ce instanceof Promise)Xe=!0,Ce.then(Ge=>{var Re;let Me=typeof Ge=="string"?Ge:(Re=Ge==null?void 0:Ge.text)!=null?Re:null;if(Me!==null&&Me.trim()!==""){let le=m;le&&le.id===U.id&&(le.content=Me,le.streaming=!1,B.delete(le.id),V.delete(le.id),g(le))}else{let le=me.getExtractedText(),he=m;he&&he.id===U.id&&(le!==null&&le.trim()!==""?he.content=le:V.has(he.id)||(he.content=Y(W)),he.streaming=!1,B.delete(he.id),V.delete(he.id),g(he))}});else{let Ge=typeof Ce=="string"?Ce:(In=Ce==null?void 0:Ce.text)!=null?In:null;if(Ge!==null&&Ge.trim()!=="")U.content=Ge,Te=!0;else{let Me=me.getExtractedText();Me!==null&&Me.trim()!==""&&(U.content=Me,Te=!0)}}}}}if(!Xe){if(!U.rawContent){let Ie=V.get(U.id);U.rawContent=Ie!=null?Ie:Y(W)}if(!Te&&!V.has(U.id)&&(U.content=Y(W)),me){let Ie=(hn=me.close)==null?void 0:hn.call(me);Ie instanceof Promise&&Ie.catch(()=>{})}B.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}}else B.delete(U.id),V.delete(U.id),U.streaming=!1,g(U)}else if(bt==="flow_complete"){let se=(Yt=E.result)==null?void 0:Yt.response;if(se!=null){let I=N(),W=V.get(I.id),U=W!=null?W:Y(se);I.rawContent=U;let me=Y(se),Te=B.get(I.id);if(Te){let _e=_n(U);if(_e!==null)me=_e;else{let We=Te.processChunk(U);We instanceof Promise&&We.then(Ce=>{var Me;let Ge=typeof Ce=="string"?Ce:(Me=Ce==null?void 0:Ce.text)!=null?Me:null;if(Ge!==null){let Re=m;Re&&Re.id===I.id&&(Re.content=Ge,Re.streaming=!1,g(Re))}});let be=Te.getExtractedText();be!==null&&(me=be)}}B.delete(I.id),V.delete(I.id);let Xe=me!==I.content,Ie=I.streaming!==!1;Xe&&(I.content=me),I.streaming=!1,(Xe||Ie)&&g(I)}else if(m!==null){let I=m;B.delete(I.id),V.delete(I.id),I.streaming!==!1&&(I.streaming=!1,g(I))}o({type:"status",status:"idle"})}else bt==="error"&&E.error&&o({type:"error",error:E.error instanceof Error?E.error:new Error(String(E.error))})}}}};function Nr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Mn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function En(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var sn=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 Gt(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 Gt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,g={id:i!=null?i:o==="user"?Mn():o==="assistant"?En():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(g),g}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,g,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=Mn(),s=En(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(h){let F={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(F),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(g=(f=this.callbacks).onError)==null||g.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var p=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Oi=ki(require("lucide"),1),oe=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Oi[r];return s?Ni(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 Ni(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function jr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dr(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function _r(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function qr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Yn(e){return{type:"text",text:e}}function Ur(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 zr(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 Jr(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 Yr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ji=["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"],Jt=[...Yr,...ji];function Di(e){return Yr.includes(e)||e.startsWith("image/")}function Kn(e){return Di(e.type)}async function Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Kn(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 Vr(e,n=Jt,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 _i(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Xr(e,n){let o=_i(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 Vn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function qi(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ui(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 Qt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Vn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Vn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Vn.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:Vn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let g=Vr(f,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let m=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Kr(f),w=Kn(f)?URL.createObjectURL(f):null,h={id:qi(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Kn(n.file),t=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Ui(n.file.type),d=oe(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=p("span");u.textContent=Xr(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=p("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=oe("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 hs=()=>{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"},zi=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"||hs()==="dark"?t:o},Gr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(hs())});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(hs());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())}},Xn=(e,n)=>{let o=zi(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 Qr=require("idiomorph"),Zr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Qr.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 mt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var kt={"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 Wn=(e,n)=>{let o=p("button");o.type="button",o.innerHTML=`
|
|
6
|
+
`);i=(Z=he.pop())!=null?Z:"";for(let Ee of he){let Ze=Ee.split(`
|
|
7
|
+
`),ot="message",$e="";for(let se of Ze)se.startsWith("event:")?ot=se.replace("event:","").trim():se.startsWith("data:")&&($e+=se.replace("data:","").trim());if(!$e)continue;let O;try{O=JSON.parse($e)}catch(se){o({type:"error",error:se instanceof Error?se:new Error("Failed to parse chat stream payload")});continue}let wt=ot!=="message"?ot:(de=O.type)!=null?de:"message";if(this.parseSSEEvent){w.current=m;let se=await this.handleCustomSSEEvent(O,o,w,p,u);if(w.current&&!m&&(m=w.current),se)continue}if(wt==="reason_start"){let se=(qe=k(O,!0))!=null?qe:`reason-${u()}`,S=z(se);S.reasoning=(Ct=S.reasoning)!=null?Ct:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(j=S.reasoning.startedAt)!=null?j:V((ee=O.startedAt)!=null?ee:O.timestamp),S.reasoning.completedAt=void 0,S.reasoning.durationMs=void 0,S.streaming=!0,S.reasoning.status="streaming",p(S)}else if(wt==="reason_chunk"){let se=(xt=(at=k(O,!1))!=null?at:k(O,!0))!=null?xt:`reason-${u()}`,S=z(se);S.reasoning=(vt=S.reasoning)!=null?vt:{id:se,status:"streaming",chunks:[]},S.reasoning.startedAt=(Ft=S.reasoning.startedAt)!=null?Ft:V((Rt=O.startedAt)!=null?Rt:O.timestamp);let E=(lt=(fe=(D=O.reasoningText)!=null?D:O.text)!=null?fe:O.delta)!=null?lt:"";if(E&&O.hidden!==!0&&S.reasoning.chunks.push(String(E)),S.reasoning.status=O.done?"complete":"streaming",O.done){S.reasoning.completedAt=V((dt=O.completedAt)!=null?dt:O.timestamp);let Y=(Ve=S.reasoning.startedAt)!=null?Ve:Date.now();S.reasoning.durationMs=Math.max(0,((ct=S.reasoning.completedAt)!=null?ct:Date.now())-Y)}S.streaming=S.reasoning.status!=="complete",p(S)}else if(wt==="reason_complete"){let se=($t=(jt=k(O,!1))!=null?jt:k(O,!0))!=null?$t:`reason-${u()}`,S=h.get(se);if(S!=null&&S.reasoning){S.reasoning.status="complete",S.reasoning.completedAt=V((Ot=O.completedAt)!=null?Ot:O.timestamp);let Y=(F=S.reasoning.startedAt)!=null?F:Date.now();S.reasoning.durationMs=Math.max(0,((Ue=S.reasoning.completedAt)!=null?Ue:Date.now())-Y),S.streaming=!1,p(S)}let E=I(O);E&&M.byStep.delete(E)}else if(wt==="tool_start"){let se=(ge=ne(O,!0))!=null?ge:`tool-${u()}`,S=re(se),E=(tt=S.toolCall)!=null?tt:{id:se,status:"pending"};E.name=(me=O.toolName)!=null?me:E.name,E.status="running",O.args!==void 0&&(E.args=O.args),E.startedAt=(U=E.startedAt)!=null?U:V((nt=O.startedAt)!=null?nt:O.timestamp),E.completedAt=void 0,E.durationMs=void 0,S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_chunk"){let se=(Xe=(Re=ne(O,!1))!=null?Re:ne(O,!0))!=null?Xe:`tool-${u()}`,S=re(se),E=(Wt=S.toolCall)!=null?Wt:{id:se,status:"running"};E.startedAt=(Pt=E.startedAt)!=null?Pt:V((gt=O.startedAt)!=null?gt:O.timestamp);let Y=(kt=(st=(Fe=O.text)!=null?Fe:O.delta)!=null?st:O.message)!=null?kt:"";Y&&(E.chunks=(mt=E.chunks)!=null?mt:[],E.chunks.push(String(Y))),E.status="running",S.toolCall=E,S.streaming=!0,p(S)}else if(wt==="tool_complete"){let se=(P=(ht=ne(O,!1))!=null?ht:ne(O,!0))!=null?P:`tool-${u()}`,S=re(se),E=(te=S.toolCall)!=null?te:{id:se,status:"running"};if(E.status="complete",O.result!==void 0&&(E.result=O.result),typeof O.duration=="number"&&(E.duration=O.duration),E.completedAt=V((we=O.completedAt)!=null?we:O.timestamp),typeof O.duration=="number")E.durationMs=O.duration;else{let Pe=(Ge=E.startedAt)!=null?Ge:Date.now();E.durationMs=Math.max(0,((St=E.completedAt)!=null?St:Date.now())-Pe)}S.toolCall=E,S.streaming=!1,p(S);let Y=v(O);Y&&y.byCall.delete(Y)}else if(wt==="step_chunk"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=N(),Y=(Ht=(Lt=(ft=(ze=O.text)!=null?ze:O.delta)!=null?ft:O.content)!=null?Lt:O.chunk)!=null?Ht:"";if(Y){let He=((fn=q.get(E.id))!=null?fn:"")+Y;E.rawContent=He,L.has(E.id)||L.set(E.id,this.createStreamParser());let ke=L.get(E.id),ye=He.trim().startsWith("{")||He.trim().startsWith("[");if(ye&&q.set(E.id,He),ke.__isPlainTextParser===!0){E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E);continue}let Le=ke.processChunk(He);if(Le instanceof Promise)Le.then(ve=>{var Te;let be=typeof ve=="string"?ve:(Te=ve==null?void 0:ve.text)!=null?Te:null;if(be!==null&&be.trim()!==""){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content=be,p(Ae))}else if(!ye&&!He.trim().startsWith("<")){let Ae=m;Ae&&Ae.id===E.id&&(Ae.content+=Y,q.delete(Ae.id),L.delete(Ae.id),Ae.rawContent=void 0,p(Ae))}}).catch(()=>{E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E)});else{let ve=typeof Le=="string"?Le:(Kt=Le==null?void 0:Le.text)!=null?Kt:null;ve!==null&&ve.trim()!==""?(E.content=ve,p(E)):!ye&&!He.trim().startsWith("<")&&(E.content+=Y,q.delete(E.id),L.delete(E.id),E.rawContent=void 0,p(E))}}if(O.isComplete){let Pe=(wn=(Fn=O.result)==null?void 0:Fn.response)!=null?wn:E.content;if(Pe){let He=q.get(E.id),ke=He!=null?He:J(Pe);E.rawContent=ke;let ye=L.get(E.id),Ie=null,Le=!1;if(ye&&(Ie=ye.getExtractedText(),Ie===null&&(Ie=zn(ke)),Ie===null)){let ve=ye.processChunk(ke);ve instanceof Promise?(Le=!0,ve.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===E.id&&(Qe.content=Te,Qe.streaming=!1,L.delete(Qe.id),q.delete(Qe.id),p(Qe))}})):Ie=typeof ve=="string"?ve:(sn=ve==null?void 0:ve.text)!=null?sn:null}if(!Le){Ie!==null&&Ie.trim()!==""?E.content=Ie:q.has(E.id)||(E.content=J(Pe));let ve=L.get(E.id);if(ve){let be=(We=ve.close)==null?void 0:We.call(ve);be instanceof Promise&&be.catch(()=>{}),L.delete(E.id)}q.delete(E.id),E.streaming=!1,p(E)}}}}else if(wt==="step_complete"){let se=O.stepType,S=O.executionType;if(se==="tool"||S==="context")continue;let E=(yn=O.result)==null?void 0:yn.response,Y=N();if(E!=null){let Pe=L.get(Y.id),He=!1,ke=!1;if(Pe){let ye=Pe.getExtractedText(),Ie=q.get(Y.id),Le=Ie!=null?Ie:J(E);if(Y.rawContent=Le,ye!==null&&ye.trim()!=="")Y.content=ye,He=!0;else{let ve=zn(Le);if(ve!==null)Y.content=ve,He=!0;else{let be=Pe.processChunk(Le);if(be instanceof Promise)ke=!0,be.then(Te=>{var Qe;let Ae=typeof Te=="string"?Te:(Qe=Te==null?void 0:Te.text)!=null?Qe:null;if(Ae!==null&&Ae.trim()!==""){let At=m;At&&At.id===Y.id&&(At.content=Ae,At.streaming=!1,L.delete(At.id),q.delete(At.id),p(At))}else{let At=Pe.getExtractedText(),Bt=m;Bt&&Bt.id===Y.id&&(At!==null&&At.trim()!==""?Bt.content=At:q.has(Bt.id)||(Bt.content=J(E)),Bt.streaming=!1,L.delete(Bt.id),q.delete(Bt.id),p(Bt))}});else{let Te=typeof be=="string"?be:(vn=be==null?void 0:be.text)!=null?vn:null;if(Te!==null&&Te.trim()!=="")Y.content=Te,He=!0;else{let Ae=Pe.getExtractedText();Ae!==null&&Ae.trim()!==""&&(Y.content=Ae,He=!0)}}}}}if(!ke){if(!Y.rawContent){let ye=q.get(Y.id);Y.rawContent=ye!=null?ye:J(E)}if(!He&&!q.has(Y.id)&&(Y.content=J(E)),Pe){let ye=(Dt=Pe.close)==null?void 0:Dt.call(Pe);ye instanceof Promise&&ye.catch(()=>{})}L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}}else L.delete(Y.id),q.delete(Y.id),Y.streaming=!1,p(Y)}else if(wt==="flow_complete"){let se=($n=O.result)==null?void 0:$n.response;if(se!=null){let S=N(),E=q.get(S.id),Y=E!=null?E:J(se);S.rawContent=Y;let Pe=J(se),He=L.get(S.id);if(He){let Ie=zn(Y);if(Ie!==null)Pe=Ie;else{let Le=He.processChunk(Y);Le instanceof Promise&&Le.then(be=>{var Ae;let Te=typeof be=="string"?be:(Ae=be==null?void 0:be.text)!=null?Ae:null;if(Te!==null){let Qe=m;Qe&&Qe.id===S.id&&(Qe.content=Te,Qe.streaming=!1,p(Qe))}});let ve=He.getExtractedText();ve!==null&&(Pe=ve)}}L.delete(S.id),q.delete(S.id);let ke=Pe!==S.content,ye=S.streaming!==!1;ke&&(S.content=Pe),S.streaming=!1,(ke||ye)&&p(S)}else if(m!==null){let S=m;L.delete(S.id),q.delete(S.id),S.streaming!==!1&&(S.streaming=!1,p(S))}o({type:"status",status:"idle"})}else wt==="error"&&O.error&&o({type:"error",error:O.error instanceof Error?O.error:new Error(String(O.error))})}}}};function _r(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ln(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function rn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var an=class{constructor(n={},o){this.config=n;this.callbacks=o;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.handleEvent=n=>{var o,t;n.type==="message"?this.upsertMessage(n.message):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null)):n.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(t=(o=this.callbacks).onError)==null||t.call(o,n.error))};var t;this.messages=[...(t=n.initialMessages)!=null?t:[]].map(r=>{var s;return{...r,sequence:(s=r.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Qt(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}isClientTokenMode(){return this.client.isClientTokenMode()}async initClientSession(){var n,o;if(!this.isClientTokenMode())return null;try{let t=await this.client.initSession();return this.setClientSession(t),t}catch(t){return(o=(n=this.callbacks).onError)==null||o.call(n,t instanceof Error?t:new Error(String(t))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let o={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(o)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,o){return this.client.submitMessageFeedback(n,o)}async submitCSATFeedback(n,o){return this.client.submitCSATFeedback(n,o)}async submitNPSFeedback(n,o){return this.client.submitNPSFeedback(n,o)}updateConfig(n){this.config={...this.config,...n},this.client=new Qt(this.config)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:o,content:t,llmContent:r,contentParts:s,id:i,createdAt:a,sequence:d,streaming:u=!1}=n,p={id:i!=null?i:o==="user"?Ln():o==="assistant"?rn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:t,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:u,...r!==void 0&&{llmContent:r},...s!==void 0&&{contentParts:s}};return this.upsertMessage(p),p}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}async sendMessage(n,o){var u,f,p,m,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(u=this.abortController)==null||u.abort();let r=Ln(),s=rn(),i={id:r,role:"user",content:t||"[Image]",createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(o==null?void 0:o.viaVoice)||!1,...(o==null?void 0:o.contentParts)&&o.contentParts.length>0&&{contentParts:o.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(h){let R={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(R),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,h instanceof Error?(p=(f=this.callbacks).onError)==null||p.call(f,h):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(h)))}}async continueConversation(){var r,s,i,a,d;if(this.streaming)return;(r=this.abortController)==null||r.abort();let n=rn();this.setStreaming(!0);let o=new AbortController;this.abortController=o;let t=[...this.messages];try{await this.client.dispatch({messages:t,signal:o.signal,assistantMessageId:n},this.handleEvent)}catch(u){let f={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(f),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,u):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(u)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var o;(o=this.abortController)==null||o.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(t=>{var r;return{...t,streaming:!1,sequence:(r=t.sequence)!=null?r:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let o=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,o]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let o=this.ensureSequence(n),t=this.messages.findIndex(r=>r.id===o.id);if(t===-1){this.appendMessage(o);return}this.messages=this.messages.map((r,s)=>s===t?{...r,...o}:r),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((o,t)=>{var d,u;let r=new Date(o.createdAt).getTime(),s=new Date(t.createdAt).getTime();if(!Number.isNaN(r)&&!Number.isNaN(s)&&r!==s)return r-s;let i=(d=o.sequence)!=null?d:0,a=(u=t.sequence)!=null?u:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var g=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Di=Hi(require("lucide"),1),ie=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Di[r];return s?_i(s,n,o,t):(console.warn(`Lucide icon "${e}" not found (tried "${r}"). Available icons: https://lucide.dev/icons`),null)}catch(r){return console.warn(`Failed to render Lucide icon "${e}":`,r),null}};function _i(e,n,o,t){if(!e||!Array.isArray(e))return null;let r=document.createElementNS("http://www.w3.org/2000/svg","svg");return r.setAttribute("width",String(n)),r.setAttribute("height",String(n)),r.setAttribute("viewBox","0 0 24 24"),r.setAttribute("fill","none"),r.setAttribute("stroke",o),r.setAttribute("stroke-width",String(t)),r.setAttribute("stroke-linecap","round"),r.setAttribute("stroke-linejoin","round"),r.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let d=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([u,f])=>{u!=="stroke"&&d.setAttribute(u,String(f))}),r.appendChild(d)}}}),r}function qr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ur(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function zr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Jr(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Xn(e){return{type:"text",text:e}}function Yr(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Kr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;n({type:"image",image:r,mimeType:e.type,alt:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Vr(e,n=["image/png","image/jpeg","image/gif","image/webp"],o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Xr=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qi=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Yt=[...Xr,...qi];function Ui(e){return Xr.includes(e)||e.startsWith("image/")}function Gn(e){return Ui(e.type)}async function Gr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Gn(e)?n({type:"image",image:r,mimeType:e.type,alt:e.name}):n({type:"file",data:r,mimeType:e.type,filename:e.name})},t.onerror=()=>o(new Error("Failed to read file")),t.readAsDataURL(e)})}function Qr(e,n=Yt,o=10*1024*1024){return n.includes(e.type)?e.size>o?{valid:!1,error:`File too large. Maximum size: ${Math.round(o/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function zi(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Zr(e,n){let o=zi(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||o||"FILE"}var Qn={allowedTypes:Yt,maxFileSize:10*1024*1024,maxFiles:4};function Ji(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Yi(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var Zt=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var o,t,r;this.config={allowedTypes:(o=n.allowedTypes)!=null?o:Qn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Qn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Qn.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Qn.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){var t,r,s,i,a,d,u;if(!n||n.length===0)return;let o=Array.from(n);for(let f of o){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,f,"count");continue}let p=Qr(f,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let m=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,m);continue}try{let m=await Gr(f),w=Gn(f)?URL.createObjectURL(f):null,h={id:Ji(),file:f,previewUrl:w,contentPart:m};this.attachments.push(h),this.renderPreview(h)}catch(m){console.error("[AttachmentManager] Failed to process file:",m)}}this.updatePreviewsVisibility(),(u=(d=this.config).onAttachmentsChange)==null||u.call(d,this.getAttachments())}removeAttachment(n){var s,i,a;let o=this.attachments.findIndex(d=>d.id===n);if(o===-1)return;let t=this.attachments[o];t.previewUrl&&URL.revokeObjectURL(t.previewUrl),this.attachments.splice(o,1);let r=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);r&&r.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,o;for(let t of this.attachments)t.previewUrl&&URL.revokeObjectURL(t.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(o=(n=this.config).onAttachmentsChange)==null||o.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let o=Gn(n.file),t=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(t.setAttribute("data-attachment-id",n.id),t.style.width="48px",t.style.height="48px",o&&n.previewUrl){let i=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",t.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=Yi(n.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let u=g("span");u.textContent=Zr(n.file.type,n.file.name),u.style.fontSize="8px",u.style.fontWeight="600",u.style.color="var(--cw-muted, #6b7280)",u.style.textTransform="uppercase",u.style.lineHeight="1",i.appendChild(u),t.appendChild(i)}let r=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");r.type="button",r.setAttribute("aria-label","Remove attachment"),r.style.position="absolute",r.style.top="-4px",r.style.right="-4px",r.style.width="18px",r.style.height="18px",r.style.borderRadius="50%",r.style.backgroundColor="rgba(0, 0, 0, 0.6)",r.style.border="none",r.style.cursor="pointer",r.style.display="flex",r.style.alignItems="center",r.style.justifyContent="center",r.style.padding="0";let s=ie("x",10,"#ffffff",2);s?r.appendChild(s):(r.textContent="\xD7",r.style.color="#ffffff",r.style.fontSize="14px",r.style.lineHeight="1"),r.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),t.appendChild(r),this.previewsContainer.appendChild(t)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,o){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:o})}};var ys=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ki=e=>{var s,i,a;let n=(s=e==null?void 0:e.colorScheme)!=null?s:"light",o=(i=e==null?void 0:e.theme)!=null?i:{},t=(a=e==null?void 0:e.darkTheme)!=null?a:o;return n==="light"?o:n==="dark"||ys()==="dark"?t:o},ei=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(ys())});o.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>o.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let o=window.matchMedia("(prefers-color-scheme: dark)"),t=()=>e(ys());o.addEventListener?(o.addEventListener("change",t),n.push(()=>o.removeEventListener("change",t))):o.addListener&&(o.addListener(t),n.push(()=>o.removeListener(t)))}return()=>{n.forEach(o=>o())}},Zn=(e,n)=>{let o=Ki(n);Object.entries(o).forEach(([t,r])=>{if(r==null||r==="")return;let s=t.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);e.style.setProperty(`--cw-${s}`,String(r))})};var ti=require("idiomorph"),ni=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;ti.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(r,s){if(r instanceof HTMLElement&&t&&r.classList.contains("tvw-animate-typing"))return!1}}})};var pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var It={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Pn=(e,n)=>{let o=g("button");o.type="button",o.innerHTML=`
|
|
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 y,S,R,v,N,C,k,K,J,z,_,j;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(S=i.title)!=null?S:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(R=i.subtitle)!=null?R:"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 Y=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=Y,f.style.width=Y,f.innerHTML="",i.agentIconName){let B=parseFloat(Y)||24,V=oe(i.agentIconName,B*.6,"#ffffff",2);V?(f.appendChild(V),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let g=o.querySelector("[data-role='launcher-image']");if(g){let Y=(k=i.agentIconSize)!=null?k:"40px";g.style.height=Y,g.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(g.src=i.iconUrl,g.style.display="block"):g.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Y=(K=i.callToActionIconSize)!=null?K:"32px";m.style.height=Y,m.style.width=Y,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 V=parseFloat(Y)||24,He=Math.max(V-B,8),X=oe(i.callToActionIconName,He,"currentColor",2);X?m.appendChild(X):m.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}let w=i.position&&kt[i.position]?kt[i.position]:kt["bottom-right"],h="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${h} ${w}`;let F="1px solid #e5e7eb",T="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(_=i.border)!=null?_:F,o.style.boxShadow=(j=i.shadow)!=null?j:T},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var qt=e=>{var z,_,j,Y,B,V,He,X,D,nt,lt,dt,Lt,Ft,q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St;let{config:n,showClose:o=!0}=e,t=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(z=n==null?void 0:n.launcher)!=null?z:{},s=(_=r.headerIconSize)!=null?_:"48px",i=(j=r.closeButtonSize)!=null?j:"32px",a=(Y=r.closeButtonPlacement)!=null?Y:"inline",d=(B=r.headerIconHidden)!=null?B:!1,u=r.headerIconName,f=p("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 ie=parseFloat(s)||24,Ye=oe(u,ie*.6,"#ffffff",2);Ye?f.replaceChildren(Ye):f.textContent=(He=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?He:"\u{1F4AC}"}else if((X=n==null?void 0:n.launcher)!=null&&X.iconUrl){let ie=p("img");ie.src=n.launcher.iconUrl,ie.alt="",ie.className="tvw-rounded-xl tvw-object-cover",ie.style.height=s,ie.style.width=s,f.replaceChildren(ie)}else f.textContent=(nt=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?nt:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col"),m=p("span","tvw-text-base tvw-font-semibold");m.textContent=(dt=(lt=n==null?void 0:n.launcher)==null?void 0:lt.title)!=null?dt:"Chat Assistant";let w=p("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Ft=(Lt=n==null?void 0:n.launcher)==null?void 0:Lt.subtitle)!=null?Ft:"Here to help you get answers fast",g.append(m,w),d?t.append(g):t.append(f,g);let h=(q=r.clearChat)!=null?q:{},F=(fe=h.enabled)!=null?fe:!0,T=(ct=h.placement)!=null?ct:"inline",y=null,S=null;if(F){let ie=(ut=h.size)!=null?ut:"32px",Ye=(Je=h.iconName)!=null?Je:"refresh-cw",Ze=(pt=h.iconColor)!=null?pt:"",ke=($t=h.backgroundColor)!=null?$t:"",Ke=(Pt=h.borderWidth)!=null?Pt:"",Wt=(Ht=h.borderColor)!=null?Ht:"",ft=($=h.borderRadius)!=null?$:"",rt=(je=h.paddingX)!=null?je:"",H=(pe=h.paddingY)!=null?pe:"",wt=(st=h.tooltipText)!=null?st:"Clear chat",yt=(ge=h.showTooltip)!=null?ge:!0;S=p("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"&&(S.style.right="48px"),y=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=ie,y.style.width=ie,y.type="button",y.setAttribute("aria-label",wt);let At=oe(Ye,"20px",Ze||"",2);if(At&&y.appendChild(At),Ze&&(y.style.color=Ze,y.classList.remove("tvw-text-cw-muted")),ke&&(y.style.backgroundColor=ke,y.classList.remove("hover:tvw-bg-gray-100")),Ke||Wt){let te=Ke||"0px",we=Wt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),rt?(y.style.paddingLeft=rt,y.style.paddingRight=rt):(y.style.paddingLeft="",y.style.paddingRight=""),H?(y.style.paddingTop=H,y.style.paddingBottom=H):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,we=()=>{if(te||!y)return;te=p("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=p("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);let et=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${et.left+et.width/2}px`,te.style.top=`${et.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Fe=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",we),S.addEventListener("mouseleave",Fe),y.addEventListener("focus",we),y.addEventListener("blur",Fe),S._cleanupTooltip=()=>{Fe(),S&&(S.removeEventListener("mouseenter",we),S.removeEventListener("mouseleave",Fe)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Fe))}}T==="inline"&&t.appendChild(S)}let R=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":F&&T==="inline"?"":"tvw-ml-auto"),v=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(ot=r.closeButtonTooltipText)!=null?ot:"Close chat",C=(Ae=r.closeButtonShowTooltip)!=null?Ae:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=oe(k,"20px",r.closeButtonColor||"",2);if(J?v.appendChild(J):v.textContent=K,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let ie=r.closeButtonBorderWidth||"0px",Ye=r.closeButtonBorderColor||"transparent";v.style.border=`${ie} solid ${Ye}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),R.appendChild(v),C&&N){let ie=null,Ye=()=>{if(ie)return;ie=p("div","tvw-clear-chat-tooltip"),ie.textContent=N;let ke=p("div");ke.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(ke);let Ke=v.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Ke.left+Ke.width/2}px`,ie.style.top=`${Ke.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ze=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};R.addEventListener("mouseenter",Ye),R.addEventListener("mouseleave",Ze),v.addEventListener("focus",Ye),v.addEventListener("blur",Ze),R._cleanupTooltip=()=>{Ze(),R.removeEventListener("mouseenter",Ye),R.removeEventListener("mouseleave",Ze),v.removeEventListener("focus",Ye),v.removeEventListener("blur",Ze)}}return a!=="top-right"&&t.appendChild(R),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:R,clearChatButton:y,clearChatButtonWrapper:S}},Zt=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var fs=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),ws=e=>{var h,F,T,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(F=r.title)!=null?F:"Chat Assistant",s.appendChild(i);let a=(T=r.closeButtonSize)!=null?T:"32px",d=p("div",""),u=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",g=oe(f,"20px",r.closeButtonColor||"",2);g?u.appendChild(g):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=p("div");m.style.display="none";let w=p("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},ys=e=>{var v,N,C,k,K,J,z,_;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=p("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 j=parseFloat(d)||24,Y=oe(f,j*.5,"#ffffff",2);Y?u.replaceChildren(Y):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let j=p("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=d,j.style.width=d,u.replaceChildren(j)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let g=p("div","tvw-flex tvw-flex-col tvw-flex-1"),m=p("span","tvw-text-lg tvw-font-semibold");m.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=p("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",g.append(m,w),a.append(u,g);let h=(z=s.closeButtonSize)!=null?z:"32px",F=p("div",""),T=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");T.style.height=h,T.style.width=h,T.type="button",T.setAttribute("aria-label","Close chat"),T.style.display=o?"":"none";let y=(_=s.closeButtonIconName)!=null?_:"x",S=oe(y,"20px",s.closeButtonColor||"",2);S?T.appendChild(S):T.textContent="\xD7",t&&T.addEventListener("click",t),F.appendChild(T),a.appendChild(F),i.appendChild(a);let R=p("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return R.textContent="Online and ready to help",i.appendChild(R),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:T,closeButtonWrapper:F,clearChatButton:null,clearChatButtonWrapper:null}},Gn={default:fs,minimal:ws,expanded:ys},vs=e=>{var n;return(n=Gn[e])!=null?n:Gn.default},on=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=p("div");f.style.display="none";let g=p("span"),m=p("span"),w=p("button");w.style.display="none";let h=p("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:g,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=vs(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ji=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},rn=e=>{var q,fe,ct,ut,Je,pt,$t,Pt,Ht,$,je,pe,st,ge,ot,Ae,xt,St,ie,Ye,Ze,ke,Ke,Wt,ft,rt,H,wt,yt,At;let{config:n}=e,o=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");r.style.outline="none";let s=p("textarea");s.placeholder=(fe=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?fe:"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=(ut=(ct=n==null?void 0:n.theme)==null?void 0:ct.inputFontFamily)!=null?ut:"sans-serif",a=(pt=(Je=n==null?void 0:n.theme)==null?void 0:Je.inputFontWeight)!=null?pt:"400";s.style.fontFamily=Ji(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let g=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",g),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=($t=n==null?void 0:n.sendButton)!=null?$t:{},w=(Pt=m.useIcon)!=null?Pt:!1,h=(Ht=m.iconText)!=null?Ht:"\u2191",F=m.iconName,T=($=m.tooltipText)!=null?$:"Send message",y=(je=m.showTooltip)!=null?je:!1,S=(pe=m.size)!=null?pe:"40px",R=m.backgroundColor,v=m.textColor,N=p("div","tvw-send-button-wrapper"),C=p("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(C.type="submit",w){if(C.style.width=S,C.style.height=S,C.style.minWidth=S,C.style.minHeight=S,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",F){let te=parseFloat(S)||24,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Fe=oe(F,te,we,2);Fe?(C.appendChild(Fe),C.style.color=we):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");R?C.style.backgroundColor=R:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(ge=(st=n==null?void 0:n.copy)==null?void 0:st.sendButtonLabel)!=null?ge:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&T){let te=p("div","tvw-send-button-tooltip");te.textContent=T,N.appendChild(te)}N.appendChild(C);let k=(ot=n==null?void 0:n.voiceRecognition)!=null?ot:{},K=k.enabled===!0,J=null,z=null,_=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&_){z=p("div","tvw-send-button-wrapper"),J=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),J.type="button",J.setAttribute("aria-label","Start voice recognition");let te=(Ae=k.iconName)!=null?Ae:"mic",we=(xt=k.iconSize)!=null?xt:S,Fe=parseFloat(we)||24,vt=(St=k.backgroundColor)!=null?St:R,et=(ie=k.iconColor)!=null?ie:v;J.style.width=we,J.style.height=we,J.style.minWidth=we,J.style.minHeight=we,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=et||"currentColor",It=oe(te,Fe,Bt,1.5);It?(J.appendChild(It),J.style.color=Bt):(J.textContent="\u{1F3A4}",J.style.color=Bt),vt?J.style.backgroundColor=vt:J.classList.add("tvw-bg-cw-primary"),et?J.style.color=et:!et&&!v&&J.classList.add("tvw-text-white"),k.borderWidth&&(J.style.borderWidth=k.borderWidth,J.style.borderStyle="solid"),k.borderColor&&(J.style.borderColor=k.borderColor),k.paddingX&&(J.style.paddingLeft=k.paddingX,J.style.paddingRight=k.paddingX),k.paddingY&&(J.style.paddingTop=k.paddingY,J.style.paddingBottom=k.paddingY),z.appendChild(J);let Ot=(Ye=k.tooltipText)!=null?Ye:"Start voice recognition";if(((Ze=k.showTooltip)!=null?Ze:!1)&&Ot){let Nt=p("div","tvw-send-button-tooltip");Nt.textContent=Ot,z.appendChild(Nt)}}let j=(ke=n==null?void 0:n.attachments)!=null?ke:{},Y=j.enabled===!0,B=null,V=null,He=null,X=null;if(Y){X=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),X.style.display="none",He=p("input"),He.type="file",He.accept=((Ke=j.allowedTypes)!=null?Ke:Jt).join(","),He.multiple=((Wt=j.maxFiles)!=null?Wt:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),V=p("div","tvw-send-button-wrapper"),B=p("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",(ft=j.buttonTooltipText)!=null?ft:"Attach file");let te=(rt=j.buttonIconName)!=null?rt:"paperclip",we=S,Fe=parseFloat(we)||40,vt=Math.round(Fe*.6);B.style.width=we,B.style.height=we,B.style.minWidth=we,B.style.minHeight=we,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 et=oe(te,vt,"currentColor",1.5);et?B.appendChild(et):B.textContent="\u{1F4CE}",B.addEventListener("click",Ot=>{Ot.preventDefault(),He==null||He.click()}),V.appendChild(B);let Bt=(H=j.buttonTooltipText)!=null?H:"Attach file",It=p("div","tvw-send-button-tooltip");It.textContent=Bt,V.appendChild(It)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==J&&te.target!==z&&te.target!==B&&te.target!==V&&s.focus()}),X&&(X.style.gap="8px",r.append(X)),He&&r.append(He),r.append(s);let D=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),nt=p("div","tvw-flex tvw-items-center tvw-gap-2");V&&nt.append(V);let lt=p("div","tvw-flex tvw-items-center tvw-gap-1");z&<.append(z),lt.append(N),D.append(nt,lt),r.append(D);let dt=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Lt=(wt=n==null?void 0:n.statusIndicator)!=null?wt:{},Ft=(yt=Lt.visible)!=null?yt:!0;return dt.style.display=Ft?"":"none",dt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,dt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:J,micButtonWrapper:z,statusText:dt,attachmentButton:B,attachmentButtonWrapper:V,attachmentInput:He,attachmentPreviewsContainer:X,actionsRow:D,leftActions:nt,rightActions:lt}};var ei=e=>{var d,u,f,g,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let F=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),T=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?g:"100%";return F.style.width=y,T.style.width="100%",F.appendChild(T),{wrapper:F,panel:T}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&kt[o.position]?kt[o.position]:kt["bottom-right"],r=p("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},ti=(e,n=!0)=>{var w,h,F,T,y,S,R;let o=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?on(e,t,{showClose:n}):qt({config:e,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(T=(F=e==null?void 0:e.copy)==null?void 0:F.welcomeTitle)!=null?T:"Hello \u{1F44B}";let u=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products.",a.append(d,u);let f=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let g=rn({config:e}),m=((R=e==null?void 0:e.layout)==null?void 0:R.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),m||(g.footer.style.display="none"),o.append(g.footer),{container:o,body:i,messagesWrapper:f,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions}};var kn=()=>{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},Yi=(e,n)=>{let o=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=p("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},ni=(e,n)=>{let o=p("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},Ki=(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},bs=(e,n,o)=>{var h,F,T,y,S,R;let t=(h=n.showCopy)!=null?h:!0,r=(F=n.showUpvote)!=null?F:!0,s=(T=n.showDownvote)!=null?T:!0,i=(y=n.visibility)!=null?y:"hover",a=(S=n.align)!=null?S:"right",d=(R=n.layout)!=null?R:"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],g=p("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",N),K.setAttribute("title",N),k&&K.setAttribute("data-action",k);let J=oe(v,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",z=>{z.preventDefault(),z.stopPropagation(),C()}),K};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=oe("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=oe("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");g.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");g.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=g.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");g.appendChild(v)}return g},an=(e,n,o,t,r)=>{var R,v,N,C,k;let s=o!=null?o:{},i=(R=s.layout)!=null?R:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,g=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=Ki(e.role,i),h=p("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let F=document.createElement("div");if(F.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let K=ni(e,d);K.classList.add("tvw-ml-2","tvw-inline"),F.appendChild(K)}if(h.appendChild(F),f&&m==="below"&&e.createdAt){let K=ni(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=kn();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=bs(e,t,r);h.appendChild(K)}if(!u||e.role==="system")return h;let y=p("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=Yi(a,e.role);return g==="right"||g==="left"&&e.role==="user"?y.append(h,S):y.append(S,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},si=(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}):an(e,n,o,t,r)};var ln=new Set,oi=(e,n)=>{let o=ln.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=oe(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},Cs=e=>{let n=e.reasoning,o=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=ln.has(e.id),r=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Ir(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=p("div","tvw-flex tvw-items-center"),f=oe(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let g=p("div","tvw-flex tvw-items-center tvw-ml-auto");g.append(d),r.append(s,g);let m=p("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=oe(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var dn=new Set,ri=(e,n,o)=>{var u;let t=dn.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",g=oe(t?"chevron-up":"chevron-down",16,f,2);g?d.appendChild(g):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},xs=(e,n)=>{var F;let o=e.toolCall,t=(F=n==null?void 0:n.toolCall)!=null?F:{},r=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(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=dn.has(e.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=p("div","tvw-flex tvw-flex-col tvw-text-left"),d=p("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Rr(o),a.appendChild(d);let u=p("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",g=oe(s?"chevron-up":"chevron-down",16,f,2);g?u.appendChild(g):u.textContent=s?"Hide":"Show";let m=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=p("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 T=p("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=o.name,w.appendChild(T)}if(o.args!==void 0){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=ms(o.args),T.append(y,S),w.appendChild(T)}if(o.chunks&&o.chunks.length){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=o.chunks.join(`
|
|
16
|
-
`),T.append(y,S),w.appendChild(T)}if(o.status==="complete"&&o.result!==void 0){let T=p("div","tvw-space-y-1"),y=p("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=p("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(S.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(S.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(S.style.color=t.codeBlockTextColor),S.textContent=ms(o.result),T.append(y,S),w.appendChild(T)}if(o.status==="complete"&&typeof o.duration=="number"){let T=p("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(T.style.color=t.contentTextColor),T.textContent=`Duration: ${o.duration}ms`,w.appendChild(T)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let T=t.toggleTextColor||t.headerTextColor||"currentColor",y=oe(s?"chevron-up":"chevron-down",16,T,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var ii=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(),g=r?r.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let h=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");h.type="button",h.textContent=w,h.disabled=g,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ai={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"}},Ss=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,F,T;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(F=ai[i])!=null?F:ai.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=p("div","tvw-space-y-1"),u=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=p("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let S=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let R=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");R.textContent=y.label,S.appendChild(R);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),S.appendChild(N),f.appendChild(S)});let g=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(T=a.submitLabel)!=null?T:"Submit",g.appendChild(m),g.appendChild(w),f.appendChild(g),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let S=(N=o.formEndpoint)!=null?N:"/form",R=new FormData(f),v={};R.forEach((k,K)=>{v[K]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let K=await k.json();m.textContent=(C=K.message)!=null?C:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await t.sendMessage(String(K.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var As=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},Ln=new As;var Ts={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"},Ms={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ts,darkTheme:Ms,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 Qn(e){var n,o,t,r,s,i,a,d,u,f,g,m,w,h,F,T,y,S,R;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Be.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(w=(m=Be.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(F=(h=e.layout)==null?void 0:h.messages)==null?void 0:F.timestamp}},slots:{...(T=Be.layout)==null?void 0:T.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(S=Be.markdown)==null?void 0:S.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var li=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Vi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Xi=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},Pn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Vi(e),o=Xi(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Es(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:Es(o.text)}}},di=e=>Array.isArray(e)?e.map(n=>String(n)):[],Hn=e=>{let n=new Set(di(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(di(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=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!f)continue;if(f.handled){let g=f.persistMessage!==!1,m=f.displayText!==void 0?f.displayText:"";return f.resubmit&&e.emit("action:resubmit",d),{text:m,persist:g,resubmit:f.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Gi=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}},Qi=e=>e.map(n=>({...n,streaming:!1})),Zn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Gi(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Qi(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 Ws=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)})}},cn=new Ws;var un=require("partial-json");function Zi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function ea(e,n){if(!Zi(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 es(){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,un.parse)(o,un.STR|un.OBJ),s=ea(r,o);s&&(e=s)}catch{}return n=o.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 ts(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=cn.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 ui(){let e=es();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ns(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 ss(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 ta=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function os(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=ta}=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 g=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let F=document.createElement("p");F.className="tvw-feedback-subtitle",F.textContent=r,w.appendChild(F),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 C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.innerHTML=`
|
|
15
|
+
`,o.addEventListener("click",n);let t=s=>{var y,A,I,v,N,C,k,z,_,ne,re,V;let i=(y=s.launcher)!=null?y:{},a=o.querySelector("[data-role='launcher-title']");a&&(a.textContent=(A=i.title)!=null?A:"Chat Assistant");let d=o.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(I=i.subtitle)!=null?I:"Get answers fast");let u=o.querySelector(".tvw-flex-col");u&&(i.textHidden?u.style.display="none":u.style.display="");let f=o.querySelector("[data-role='launcher-icon']");if(f)if(i.agentIconHidden)f.style.display="none";else{let J=(v=i.agentIconSize)!=null?v:"40px";if(f.style.height=J,f.style.width=J,f.innerHTML="",i.agentIconName){let L=parseFloat(J)||24,q=ie(i.agentIconName,L*.6,"#ffffff",2);q?(f.appendChild(q),f.style.display=""):(f.textContent=(N=i.agentIconText)!=null?N:"\u{1F4AC}",f.style.display="")}else i.iconUrl?f.style.display="none":(f.textContent=(C=i.agentIconText)!=null?C:"\u{1F4AC}",f.style.display="")}let p=o.querySelector("[data-role='launcher-image']");if(p){let J=(k=i.agentIconSize)!=null?k:"40px";p.style.height=J,p.style.width=J,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=o.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let J=(z=i.callToActionIconSize)!=null?z:"32px";m.style.height=J,m.style.width=J,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let L=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,L=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let q=parseFloat(J)||24,Z=Math.max(q-L,8),de=ie(i.callToActionIconName,Z,"currentColor",2);de?m.appendChild(de):m.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=i.callToActionIconText)!=null?ne:"\u2197"}let w=i.position&&It[i.position]?It[i.position]:It["bottom-right"],h="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";o.className=`${h} ${w}`;let R="1px solid #e5e7eb",M="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";o.style.border=(re=i.border)!=null?re:R,o.style.boxShadow=(V=i.shadow)!=null?V:M},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var Ut=e=>{var ne,re,V,J,L,q,Z,de,qe,Ct,ee,j,at,xt,vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt;let{config:n,showClose:o=!0}=e,t=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),r=(ne=n==null?void 0:n.launcher)!=null?ne:{},s=(re=r.headerIconSize)!=null?re:"48px",i=(V=r.closeButtonSize)!=null?V:"32px",a=(J=r.closeButtonPlacement)!=null?J:"inline",d=(L=r.headerIconHidden)!=null?L:!1,u=r.headerIconName,f=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(f.style.height=s,f.style.width=s,!d)if(u){let U=parseFloat(s)||24,Re=ie(u,U*.6,"#ffffff",2);Re?f.replaceChildren(Re):f.textContent=(Z=(q=n==null?void 0:n.launcher)==null?void 0:q.agentIconText)!=null?Z:"\u{1F4AC}"}else if((de=n==null?void 0:n.launcher)!=null&&de.iconUrl){let U=g("img");U.src=n.launcher.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=s,U.style.width=s,f.replaceChildren(U)}else f.textContent=(Ct=(qe=n==null?void 0:n.launcher)==null?void 0:qe.agentIconText)!=null?Ct:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(j=(ee=n==null?void 0:n.launcher)==null?void 0:ee.title)!=null?j:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(xt=(at=n==null?void 0:n.launcher)==null?void 0:at.subtitle)!=null?xt:"Here to help you get answers fast",p.append(m,w),d?t.append(p):t.append(f,p);let h=(vt=r.clearChat)!=null?vt:{},R=(Rt=h.enabled)!=null?Rt:!0,M=(Ft=h.placement)!=null?Ft:"inline",y=null,A=null;if(R){let U=(D=h.size)!=null?D:"32px",Re=(fe=h.iconName)!=null?fe:"refresh-cw",Xe=(lt=h.iconColor)!=null?lt:"",Wt=(dt=h.backgroundColor)!=null?dt:"",gt=(Ve=h.borderWidth)!=null?Ve:"",Pt=(ct=h.borderColor)!=null?ct:"",Fe=(jt=h.borderRadius)!=null?jt:"",st=($t=h.paddingX)!=null?$t:"",kt=(Ot=h.paddingY)!=null?Ot:"",mt=(F=h.tooltipText)!=null?F:"Clear chat",ht=(Ue=h.showTooltip)!=null?Ue:!0;A=g("div",M==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),M==="top-right"&&(A.style.right="48px"),y=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),y.style.height=U,y.style.width=U,y.type="button",y.setAttribute("aria-label",mt);let P=ie(Re,"20px",Xe||"",2);if(P&&y.appendChild(P),Xe&&(y.style.color=Xe,y.classList.remove("tvw-text-cw-muted")),Wt&&(y.style.backgroundColor=Wt,y.classList.remove("hover:tvw-bg-gray-100")),gt||Pt){let te=gt||"0px",we=Pt||"transparent";y.style.border=`${te} solid ${we}`,y.classList.remove("tvw-border-none")}if(Fe&&(y.style.borderRadius=Fe,y.classList.remove("tvw-rounded-full")),st?(y.style.paddingLeft=st,y.style.paddingRight=st):(y.style.paddingLeft="",y.style.paddingRight=""),kt?(y.style.paddingTop=kt,y.style.paddingBottom=kt):(y.style.paddingTop="",y.style.paddingBottom=""),A.appendChild(y),ht&&mt&&y&&A){let te=null,we=()=>{if(te||!y)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=mt;let St=g("div");St.className="tvw-clear-chat-tooltip-arrow",te.appendChild(St);let ze=y.getBoundingClientRect();te.style.position="fixed",te.style.left=`${ze.left+ze.width/2}px`,te.style.top=`${ze.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ge=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};A.addEventListener("mouseenter",we),A.addEventListener("mouseleave",Ge),y.addEventListener("focus",we),y.addEventListener("blur",Ge),A._cleanupTooltip=()=>{Ge(),A&&(A.removeEventListener("mouseenter",we),A.removeEventListener("mouseleave",Ge)),y&&(y.removeEventListener("focus",we),y.removeEventListener("blur",Ge))}}M==="inline"&&t.appendChild(A)}let I=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":R&&M==="inline"?"":"tvw-ml-auto"),v=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");v.style.height=i,v.style.width=i,v.type="button";let N=(ge=r.closeButtonTooltipText)!=null?ge:"Close chat",C=(tt=r.closeButtonShowTooltip)!=null?tt:!0;v.setAttribute("aria-label",N),v.style.display=o?"":"none";let k=(me=r.closeButtonIconName)!=null?me:"x",z=(nt=r.closeButtonIconText)!=null?nt:"\xD7",_=ie(k,"20px",r.closeButtonColor||"",2);if(_?v.appendChild(_):v.textContent=z,r.closeButtonColor?(v.style.color=r.closeButtonColor,v.classList.remove("tvw-text-cw-muted")):(v.style.color="",v.classList.add("tvw-text-cw-muted")),r.closeButtonBackgroundColor?(v.style.backgroundColor=r.closeButtonBackgroundColor,v.classList.remove("hover:tvw-bg-gray-100")):(v.style.backgroundColor="",v.classList.add("hover:tvw-bg-gray-100")),r.closeButtonBorderWidth||r.closeButtonBorderColor){let U=r.closeButtonBorderWidth||"0px",Re=r.closeButtonBorderColor||"transparent";v.style.border=`${U} solid ${Re}`,v.classList.remove("tvw-border-none")}else v.style.border="",v.classList.add("tvw-border-none");if(r.closeButtonBorderRadius?(v.style.borderRadius=r.closeButtonBorderRadius,v.classList.remove("tvw-rounded-full")):(v.style.borderRadius="",v.classList.add("tvw-rounded-full")),r.closeButtonPaddingX?(v.style.paddingLeft=r.closeButtonPaddingX,v.style.paddingRight=r.closeButtonPaddingX):(v.style.paddingLeft="",v.style.paddingRight=""),r.closeButtonPaddingY?(v.style.paddingTop=r.closeButtonPaddingY,v.style.paddingBottom=r.closeButtonPaddingY):(v.style.paddingTop="",v.style.paddingBottom=""),I.appendChild(v),C&&N){let U=null,Re=()=>{if(U)return;U=g("div","tvw-clear-chat-tooltip"),U.textContent=N;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",U.appendChild(Wt);let gt=v.getBoundingClientRect();U.style.position="fixed",U.style.left=`${gt.left+gt.width/2}px`,U.style.top=`${gt.top-8}px`,U.style.transform="translate(-50%, -100%)",document.body.appendChild(U)},Xe=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};I.addEventListener("mouseenter",Re),I.addEventListener("mouseleave",Xe),v.addEventListener("focus",Re),v.addEventListener("blur",Xe),I._cleanupTooltip=()=>{Xe(),I.removeEventListener("mouseenter",Re),I.removeEventListener("mouseleave",Xe),v.removeEventListener("focus",Re),v.removeEventListener("blur",Xe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:m,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:A}},en=(e,n,o)=>{var i,a,d,u;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(u=(d=t.clearChat)==null?void 0:d.placement)!=null?u:"inline";e.appendChild(n.header),r==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var vs=e=>Ut({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),bs=e=>{var h,R,M,y;let{config:n,showClose:o=!0,onClose:t}=e,r=(h=n==null?void 0:n.launcher)!=null?h:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(R=r.title)!=null?R:"Chat Assistant",s.appendChild(i);let a=(M=r.closeButtonSize)!=null?M:"32px",d=g("div",""),u=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");u.style.height=a,u.style.width=a,u.type="button",u.setAttribute("aria-label","Close chat"),u.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",p=ie(f,"20px",r.closeButtonColor||"",2);p?u.appendChild(p):u.textContent="\xD7",t&&u.addEventListener("click",t),d.appendChild(u),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:u,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},Cs=e=>{var v,N,C,k,z,_,ne,re;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(N=s.headerIconSize)!=null?N:"56px",u=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");u.style.height=d,u.style.width=d;let f=s.headerIconName;if(f){let V=parseFloat(d)||24,J=ie(f,V*.5,"#ffffff",2);J?u.replaceChildren(J):u.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let V=g("img");V.src=s.iconUrl,V.alt="",V.className="tvw-rounded-xl tvw-object-cover",V.style.height=d,V.style.width=d,u.replaceChildren(V)}else u.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(z=s.title)!=null?z:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(_=s.subtitle)!=null?_:"Here to help you get answers fast",p.append(m,w),a.append(u,p);let h=(ne=s.closeButtonSize)!=null?ne:"32px",R=g("div",""),M=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");M.style.height=h,M.style.width=h,M.type="button",M.setAttribute("aria-label","Close chat"),M.style.display=o?"":"none";let y=(re=s.closeButtonIconName)!=null?re:"x",A=ie(y,"20px",s.closeButtonColor||"",2);A?M.appendChild(A):M.textContent="\xD7",t&&M.addEventListener("click",t),R.appendChild(M),a.appendChild(R),i.appendChild(a);let I=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return I.textContent="Online and ready to help",i.appendChild(I),{header:i,iconHolder:u,headerTitle:m,headerSubtitle:w,closeButton:M,closeButtonWrapper:R,clearChatButton:null,clearChatButtonWrapper:null}},es={default:vs,minimal:bs,expanded:Cs},xs=e=>{var n;return(n=es[e])!=null?n:es.default},ln=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let u=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=g("div");f.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let h=g("div");return h.style.display="none",{header:u,iconHolder:f,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=xs(t)({config:e,showClose:(d=(a=n==null?void 0:n.showCloseButton)!=null?a:o==null?void 0:o.showClose)!=null?d:!0,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat});return n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Vi=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},dn=e=>{var vt,Rt,Ft,D,fe,lt,dt,Ve,ct,jt,$t,Ot,F,Ue,ge,tt,me,nt,U,Re,Xe,Wt,gt,Pt,Fe,st,kt,mt,ht,P;let{config:n}=e,o=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");r.style.outline="none";let s=g("textarea");s.placeholder=(Rt=(vt=n==null?void 0:n.copy)==null?void 0:vt.inputPlaceholder)!=null?Rt:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none",s.rows=1;let i=(D=(Ft=n==null?void 0:n.theme)==null?void 0:Ft.inputFontFamily)!=null?D:"sans-serif",a=(lt=(fe=n==null?void 0:n.theme)==null?void 0:fe.inputFontWeight)!=null?lt:"400";s.style.fontFamily=Vi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(dt=n==null?void 0:n.sendButton)!=null?dt:{},w=(Ve=m.useIcon)!=null?Ve:!1,h=(ct=m.iconText)!=null?ct:"\u2191",R=m.iconName,M=(jt=m.tooltipText)!=null?jt:"Send message",y=($t=m.showTooltip)!=null?$t:!1,A=(Ot=m.size)!=null?Ot:"40px",I=m.backgroundColor,v=m.textColor,N=g("div","tvw-send-button-wrapper"),C=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(C.type="submit",w){if(C.style.width=A,C.style.height=A,C.style.minWidth=A,C.style.minHeight=A,C.style.fontSize="18px",C.style.lineHeight="1",C.innerHTML="",R){let te=parseFloat(A)||24,we=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Ge=ie(R,te,we,2);Ge?(C.appendChild(Ge),C.style.color=we):(C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white"))}else C.textContent=h,v?C.style.color=v:C.classList.add("tvw-text-white");I?C.style.backgroundColor=I:C.classList.add("tvw-bg-cw-primary")}else C.textContent=(Ue=(F=n==null?void 0:n.copy)==null?void 0:F.sendButtonLabel)!=null?Ue:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(m.borderWidth&&(C.style.borderWidth=m.borderWidth,C.style.borderStyle="solid"),m.borderColor&&(C.style.borderColor=m.borderColor),m.paddingX?(C.style.paddingLeft=m.paddingX,C.style.paddingRight=m.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),m.paddingY?(C.style.paddingTop=m.paddingY,C.style.paddingBottom=m.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&M){let te=g("div","tvw-send-button-tooltip");te.textContent=M,N.appendChild(te)}N.appendChild(C);let k=(ge=n==null?void 0:n.voiceRecognition)!=null?ge:{},z=k.enabled===!0,_=null,ne=null,re=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(z&&re){ne=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),_.type="button",_.setAttribute("aria-label","Start voice recognition");let te=(tt=k.iconName)!=null?tt:"mic",we=(me=k.iconSize)!=null?me:A,Ge=parseFloat(we)||24,St=(nt=k.backgroundColor)!=null?nt:I,ze=(U=k.iconColor)!=null?U:v;_.style.width=we,_.style.height=we,_.style.minWidth=we,_.style.minHeight=we,_.style.fontSize="18px",_.style.lineHeight="1";let ft=ze||"currentColor",Lt=ie(te,Ge,ft,1.5);Lt?(_.appendChild(Lt),_.style.color=ft):(_.textContent="\u{1F3A4}",_.style.color=ft),St?_.style.backgroundColor=St:_.classList.add("tvw-bg-cw-primary"),ze?_.style.color=ze:!ze&&!v&&_.classList.add("tvw-text-white"),k.borderWidth&&(_.style.borderWidth=k.borderWidth,_.style.borderStyle="solid"),k.borderColor&&(_.style.borderColor=k.borderColor),k.paddingX&&(_.style.paddingLeft=k.paddingX,_.style.paddingRight=k.paddingX),k.paddingY&&(_.style.paddingTop=k.paddingY,_.style.paddingBottom=k.paddingY),ne.appendChild(_);let Ht=(Re=k.tooltipText)!=null?Re:"Start voice recognition";if(((Xe=k.showTooltip)!=null?Xe:!1)&&Ht){let Kt=g("div","tvw-send-button-tooltip");Kt.textContent=Ht,ne.appendChild(Kt)}}let V=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},J=V.enabled===!0,L=null,q=null,Z=null,de=null;if(J){de=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),de.style.display="none",Z=g("input"),Z.type="file",Z.accept=((gt=V.allowedTypes)!=null?gt:Yt).join(","),Z.multiple=((Pt=V.maxFiles)!=null?Pt:4)>1,Z.style.display="none",Z.setAttribute("aria-label","Attach files"),q=g("div","tvw-send-button-wrapper"),L=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),L.type="button",L.setAttribute("aria-label",(Fe=V.buttonTooltipText)!=null?Fe:"Attach file");let te=(st=V.buttonIconName)!=null?st:"paperclip",we=A,Ge=parseFloat(we)||40,St=Math.round(Ge*.6);L.style.width=we,L.style.height=we,L.style.minWidth=we,L.style.minHeight=we,L.style.fontSize="18px",L.style.lineHeight="1",L.style.backgroundColor="transparent",L.style.color="var(--cw-primary, #111827)",L.style.border="none",L.style.borderRadius="6px",L.style.transition="background-color 0.15s ease",L.addEventListener("mouseenter",()=>{L.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),L.addEventListener("mouseleave",()=>{L.style.backgroundColor="transparent"});let ze=ie(te,St,"currentColor",1.5);ze?L.appendChild(ze):L.textContent="\u{1F4CE}",L.addEventListener("click",Ht=>{Ht.preventDefault(),Z==null||Z.click()}),q.appendChild(L);let ft=(kt=V.buttonTooltipText)!=null?kt:"Attach file",Lt=g("div","tvw-send-button-tooltip");Lt.textContent=ft,q.appendChild(Lt)}r.addEventListener("click",te=>{te.target!==C&&te.target!==N&&te.target!==_&&te.target!==ne&&te.target!==L&&te.target!==q&&s.focus()}),de&&(de.style.gap="8px",r.append(de)),Z&&r.append(Z),r.append(s);let qe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Ct=g("div","tvw-flex tvw-items-center tvw-gap-2");q&&Ct.append(q);let ee=g("div","tvw-flex tvw-items-center tvw-gap-1");ne&&ee.append(ne),ee.append(N),qe.append(Ct,ee),r.append(qe);let j=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),at=(mt=n==null?void 0:n.statusIndicator)!=null?mt:{},xt=(ht=at.visible)!=null?ht:!0;return j.style.display=xt?"":"none",j.textContent=(P=at.idleText)!=null?P:"Online",o.append(t,r,j),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:N,micButton:_,micButtonWrapper:ne,statusText:j,attachmentButton:L,attachmentButtonWrapper:q,attachmentInput:Z,attachmentPreviewsContainer:de,actionsRow:qe,leftActions:Ct,rightActions:ee}};var si=e=>{var d,u,f,p,m,w,h;if(!((u=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?u:!0)){let R=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(p=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?p:"100%";return R.style.width=y,M.style.width="100%",R.appendChild(M),{wrapper:R,panel:M}}let o=(m=e==null?void 0:e.launcher)!=null?m:{},t=o.position&&It[o.position]?It[o.position]:It["bottom-right"],r=g("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(h=(w=e==null?void 0:e.launcher)==null?void 0:w.width)!=null?h:e==null?void 0:e.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,r.appendChild(s),{wrapper:r,panel:s}},oi=(e,n=!0)=>{var w,h,R,M,y,A,I;let o=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),t=(w=e==null?void 0:e.layout)==null?void 0:w.header,r=((h=e==null?void 0:e.layout)==null?void 0:h.showHeader)!==!1,s=t?ln(e,t,{showClose:n}):Ut({config:e,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(M=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?M:"Hello \u{1F44B}";let u=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");u.textContent=(A=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?A:"Ask anything about your account or products.",a.append(d,u);let f=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let p=dn({config:e}),m=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?en(o,s,e):(s.header.style.display="none",en(o,s,e)),o.append(i),m||(p.footer.style.display="none"),o.append(p.footer),{container:o,body:i,messagesWrapper:f,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:u,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var Hn=()=>{let e=document.createElement("div");e.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let o=document.createElement("div");o.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",o.style.animationDelay="250ms";let t=document.createElement("div");t.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",t.style.animationDelay="500ms";let r=document.createElement("span");return r.className="tvw-sr-only",r.textContent="Loading",e.appendChild(n),e.appendChild(o),e.appendChild(t),e.appendChild(r),e},Xi=(e,n)=>{let o=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),t=n==="user"?e.userAvatar:e.assistantAvatar;if(t)if(t.startsWith("http")||t.startsWith("/")||t.startsWith("data:")){let r=g("img");r.src=t,r.alt=n==="user"?"User":"Assistant",r.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",o.appendChild(r)}else o.textContent=t,o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else o.textContent=n==="user"?"U":"A",o.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return o},ri=(e,n)=>{let o=g("div","tvw-text-xs tvw-text-cw-muted"),t=new Date(e.createdAt);return n.format?o.textContent=n.format(t):o.textContent=t.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},Gi=(e,n="bubble")=>{let o=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):o.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":o.push("tvw-text-sm","tvw-leading-relaxed"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:o.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),e==="user"?o.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):o.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return o},Ss=(e,n,o)=>{var h,R,M,y,A,I;let t=(h=n.showCopy)!=null?h:!0,r=(R=n.showUpvote)!=null?R:!0,s=(M=n.showDownvote)!=null?M:!0,i=(y=n.visibility)!=null?y:"hover",a=(A=n.align)!=null?A:"right",d=(I=n.layout)!=null?I:"pill-inside",u={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],f={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${u} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let m=null,w=(v,N,C,k)=>{let z=document.createElement("button");z.className="tvw-message-action-btn",z.setAttribute("aria-label",N),z.setAttribute("title",N),k&&z.setAttribute("data-action",k);let _=ie(v,14,"currentColor",2);return _&&z.appendChild(_),z.addEventListener("click",ne=>{ne.preventDefault(),ne.stopPropagation(),C()}),z};if(t){let v=w("copy","Copy message",()=>{let N=e.content||"";navigator.clipboard.writeText(N).then(()=>{v.classList.add("tvw-message-action-success");let C=ie("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=ie("copy",14,"currentColor",2);k&&(v.innerHTML="",v.appendChild(k))},2e3)}).catch(C=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",C)}),o!=null&&o.onCopy&&o.onCopy(e),n.onCopy&&n.onCopy(e)},"copy");p.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(m==="upvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),m="upvote",v.classList.add("tvw-message-action-active");let k={type:"upvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"upvote");p.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(m==="downvote")m=null,v.classList.remove("tvw-message-action-active");else{let C=p.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),m="downvote",v.classList.add("tvw-message-action-active");let k={type:"downvote",messageId:e.id,message:e};o!=null&&o.onFeedback&&o.onFeedback(k),n.onFeedback&&n.onFeedback(k)}},"downvote");p.appendChild(v)}return p},cn=(e,n,o,t,r)=>{var I,v,N,C,k;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,u=(v=a==null?void 0:a.show)!=null?v:!1,f=(N=d==null?void 0:d.show)!=null?N:!1,p=(C=a==null?void 0:a.position)!=null?C:"left",m=(k=d==null?void 0:d.position)!=null?k:"below",w=Gi(e.role,i),h=g("div",w.join(" "));h.id=`bubble-${e.id}`,h.setAttribute("data-message-id",e.id);let R=document.createElement("div");if(R.innerHTML=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),f&&m==="inline"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-ml-2","tvw-inline"),R.appendChild(z)}if(h.appendChild(R),f&&m==="below"&&e.createdAt){let z=ri(e,d);z.classList.add("tvw-mt-1"),h.appendChild(z)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let z=Hn();h.appendChild(z)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let z=Ss(e,t,r);h.appendChild(z)}if(!u||e.role==="system")return h;let y=g("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),A=Xi(a,e.role);return p==="right"||p==="left"&&e.role==="user"?y.append(h,A):y.append(A,h),h.classList.remove("tvw-max-w-[85%]"),h.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),y},ii=(e,n,o,t,r)=>{let s=o!=null?o:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):cn(e,n,o,t,r)};var un=new Set,ai=(e,n)=>{let o=un.has(e),t=n.querySelector('button[data-expand-header="true"]'),r=n.querySelector(".tvw-border-t");if(!t||!r)return;t.setAttribute("aria-expanded",o?"true":"false");let s=t.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},As=e=>{let n=e.reasoning,o=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!n)return o;let t=un.has(e.id),r=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");r.type="button",r.setAttribute("aria-expanded",t?"true":"false"),r.setAttribute("data-expand-header","true"),r.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=$r(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),f=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),r.append(s,p);let m=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");m.style.display=t?"":"none";let w=n.chunks.join(""),h=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return h.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=ie(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",m.style.display=t?"":"none"})(),o.append(r,m),o};var pn=new Set,li=(e,n,o)=>{var u;let t=pn.has(e),r=(u=o==null?void 0:o.toolCall)!=null?u:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",t?"true":"false");let a=s.querySelector(".tvw-ml-auto"),d=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(d){d.innerHTML="";let f=r.toggleTextColor||r.headerTextColor||"currentColor",p=ie(t?"chevron-up":"chevron-down",16,f,2);p?d.appendChild(p):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},Ts=(e,n)=>{var R;let o=e.toolCall,t=(R=n==null?void 0:n.toolCall)!=null?R:{},r=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),t.backgroundColor&&(r.style.backgroundColor=t.backgroundColor),t.borderColor&&(r.style.borderColor=t.borderColor),t.borderWidth&&(r.style.borderWidth=t.borderWidth),t.borderRadius&&(r.style.borderRadius=t.borderRadius),!o)return r;let s=pn.has(e.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),t.headerBackgroundColor&&(i.style.backgroundColor=t.headerBackgroundColor),t.headerPaddingX&&(i.style.paddingLeft=t.headerPaddingX,i.style.paddingRight=t.headerPaddingX),t.headerPaddingY&&(i.style.paddingTop=t.headerPaddingY,i.style.paddingBottom=t.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Or(o),a.appendChild(d);let u=g("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,f,2);p?u.appendChild(p):u.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(u),i.append(a,m);let w=g("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",t.contentBackgroundColor&&(w.style.backgroundColor=t.contentBackgroundColor),t.contentTextColor&&(w.style.color=t.contentTextColor),t.contentPaddingX&&(w.style.paddingLeft=t.contentPaddingX,w.style.paddingRight=t.contentPaddingX),t.contentPaddingY&&(w.style.paddingTop=t.contentPaddingY,w.style.paddingBottom=t.contentPaddingY),o.name){let M=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");t.contentTextColor?M.style.color=t.contentTextColor:t.headerTextColor&&(M.style.color=t.headerTextColor),M.textContent=o.name,w.appendChild(M)}if(o.args!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.args),M.append(y,A),w.appendChild(M)}if(o.chunks&&o.chunks.length){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=o.chunks.join(`
|
|
16
|
+
`),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=g("div","tvw-space-y-1"),y=g("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let A=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-border-gray-100 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");A.style.fontSize="0.75rem",A.style.lineHeight="1rem",t.codeBlockBackgroundColor&&(A.style.backgroundColor=t.codeBlockBackgroundColor),t.codeBlockBorderColor&&(A.style.borderColor=t.codeBlockBorderColor),t.codeBlockTextColor&&(A.style.color=t.codeBlockTextColor),A.textContent=ws(o.result),M.append(y,A),w.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=g("div","tvw-text-xs tvw-text-cw-muted");t.contentTextColor&&(M.style.color=t.contentTextColor),M.textContent=`Duration: ${o.duration}ms`,w.appendChild(M)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),u.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=ie(s?"chevron-up":"chevron-down",16,M,2);y?u.appendChild(y):u.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var di=e=>{let n=[];return{buttons:n,render:(t,r,s,i,a)=>{if(e.innerHTML="",n.length=0,!t||!t.length||(i!=null?i:r?r.getMessages():[]).some(w=>w.role==="user"))return;let f=document.createDocumentFragment(),p=r?r.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};t.forEach(w=>{let h=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");h.type="button",h.textContent=w,h.disabled=p,a!=null&&a.fontFamily&&(h.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(h.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(h.style.paddingLeft=a.paddingX,h.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(h.style.paddingTop=a.paddingY,h.style.paddingBottom=a.paddingY),h.addEventListener("click",()=>{!r||r.isStreaming()||(s.value="",r.sendMessage(w))}),f.appendChild(h),n.push(h)}),e.appendChild(f)}}};var ci={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},Ms=(e,n,o,t)=>{let r=e.querySelectorAll("[data-tv-form]");r.length&&r.forEach(s=>{var h,R,M;if(s.dataset.enhanced==="true")return;let i=(h=s.dataset.tvForm)!=null?h:"init";s.dataset.enhanced="true";let a=(R=ci[i])!=null?R:ci.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),u=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(u.textContent=a.title,d.appendChild(u),a.description){let y=g("p","tvw-text-sm tvw-text-cw-muted");y.textContent=a.description,d.appendChild(y)}let f=document.createElement("form");f.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(y=>{var C,k;let A=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");A.htmlFor=`${n.id}-${i}-${y.name}`;let I=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,A.appendChild(I);let v=(C=y.type)!=null?C:"text",N;v==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=v),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${y.name}`,N.name=y.name,N.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(N.required=!0),A.appendChild(N),f.appendChild(A)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(M=a.submitLabel)!=null?M:"Submit",p.appendChild(m),p.appendChild(w),f.appendChild(p),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var N,C;y.preventDefault();let A=(N=o.formEndpoint)!=null?N:"/form",I=new FormData(f),v={};I.forEach((k,z)=>{v[z]=k}),v.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let k=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(v)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let z=await k.json();m.textContent=(C=z.message)!=null?C:"Thanks! We'll be in touch soon.",z.success&&z.nextPrompt&&await t.sendMessage(String(z.nextPrompt))}catch(k){m.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Es=class{constructor(){this.plugins=new Map}register(n){var o;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(o=n.onRegister)==null||o.call(n)}unregister(n){var t;let o=this.plugins.get(n);o&&((t=o.onUnregister)==null||t.call(o),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,o)=>{var t,r;return((t=o.priority)!=null?t:0)-((r=n.priority)!=null?r:0)})}getForInstance(n){let o=this.getAll();if(!n||n.length===0)return o;let t=new Set(n.map(s=>s.id));return[...o.filter(s=>!t.has(s.id)),...n].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var o;return(o=n.onUnregister)==null?void 0:o.call(n)}),this.plugins.clear()}},Bn=new Es;var Ws={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},ks={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},Be={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ws,darkTheme:ks,colorScheme:"light",launcher:{enabled:!0,title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ts(e){var n,o,t,r,s,i,a,d,u,f,p,m,w,h,R,M,y,A,I;return e?{...Be,...e,theme:{...Be.theme,...e.theme},darkTheme:{...Be.darkTheme,...e.darkTheme},launcher:{...Be.launcher,...e.launcher,clearChat:{...(n=Be.launcher)==null?void 0:n.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Be.copy,...e.copy},sendButton:{...Be.sendButton,...e.sendButton},statusIndicator:{...Be.statusIndicator,...e.statusIndicator},voiceRecognition:{...Be.voiceRecognition,...e.voiceRecognition},features:{...Be.features,...e.features},suggestionChips:(t=e.suggestionChips)!=null?t:Be.suggestionChips,suggestionChipsConfig:{...Be.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Be.layout,...e.layout,header:{...(r=Be.layout)==null?void 0:r.header,...(s=e.layout)==null?void 0:s.header},messages:{...(i=Be.layout)==null?void 0:i.messages,...(a=e.layout)==null?void 0:a.messages,avatar:{...(u=(d=Be.layout)==null?void 0:d.messages)==null?void 0:u.avatar,...(p=(f=e.layout)==null?void 0:f.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=Be.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(R=(h=e.layout)==null?void 0:h.messages)==null?void 0:R.timestamp}},slots:{...(M=Be.layout)==null?void 0:M.slots,...(y=e.layout)==null?void 0:y.slots}},markdown:{...Be.markdown,...e.markdown,options:{...(A=Be.markdown)==null?void 0:A.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ui=()=>{let e=new Map,n=(r,s)=>(e.has(r)||e.set(r,new Set),e.get(r).add(s),()=>o(r,s)),o=(r,s)=>{var i;(i=e.get(r))==null||i.delete(s)};return{on:n,off:o,emit:(r,s)=>{var i;(i=e.get(r))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Qi=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Zi=e=>{let n=e.trim(),o=n.indexOf("{");if(o===-1)return null;let t=0;for(let r=o;r<n.length;r+=1){let s=n[r];if(s==="{"&&(t+=1),s==="}"&&(t-=1,t===0))return n.slice(o,r+1)}return null},In=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Qi(e),o=Zi(n);if(!o)return null;let t=JSON.parse(o);if(!t||typeof t!="object"||!t.action)return null;let{action:r,...s}=t;return{type:String(r),payload:s,raw:t}}catch{return null}},Ls=e=>typeof e=="string"?e:e==null?"":String(e),tn={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ls(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ls(o.element);if(t&&((r=n.document)!=null&&r.querySelector)){let s=n.document.querySelector(t);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",t)}return{handled:!0,displayText:Ls(o.text)}}},pi=e=>Array.isArray(e)?e.map(n=>String(n)):[],Rn=e=>{let n=new Set(pi(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(pi(e.getSessionMetadata().processedActionMessageIds))},t=()=>{let s=Array.from(n);e.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?e.parsers.reduce((u,f)=>u||(f==null?void 0:f({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),t();let d={action:a,message:s.message};e.emit("action:detected",d);for(let u of e.handlers)if(u)try{let f=()=>{e.emit("action:resubmit",d)},p=u(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:f});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var ea=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},ta=e=>e.map(n=>({...n,streaming:!1})),ns=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?ea(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?ta(o.messages):void 0};t.setItem(e,JSON.stringify(r))}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",r)}},clear:()=>{let o=n();if(o)try{o.removeItem(e)}catch(t){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",t)}}}};var Ps=class{constructor(){this.components=new Map}register(n,o){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,o)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([o,t])=>{this.register(o,t)})}},gn=new Ps;var mn=require("partial-json");function na(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function sa(e,n){if(!na(e))return null;let o=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:o,raw:n}}function ss(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:o=>{let t=o.trim();if(!t.startsWith("{")&&!t.startsWith("["))return null;if(o.length<=n)return e;try{let r=(0,mn.parse)(o,mn.STR|mn.OBJ),s=sa(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function gi(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function os(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=gn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config:o,updateProps:a=>{r&&r(a)}};try{return s(e.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,a),null}}function mi(){let e=ss();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function rs(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function is(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var oa=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function as(e){let{onSubmit:n,onDismiss:o,title:t="How satisfied are you?",subtitle:r="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:u=oa}=e,f=document.createElement("div");f.className="tvw-feedback-container tvw-feedback-csat",f.setAttribute("role","dialog"),f.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let h=document.createElement("h3");h.className="tvw-feedback-title",h.textContent=t,w.appendChild(h);let R=document.createElement("p");R.className="tvw-feedback-subtitle",R.textContent=r,w.appendChild(R),m.appendChild(w);let M=document.createElement("div");M.className="tvw-feedback-rating tvw-feedback-rating-csat",M.setAttribute("role","radiogroup"),M.setAttribute("aria-label","Satisfaction rating from 1 to 5");let y=[];for(let C=1;C<=5;C++){let k=document.createElement("button");k.type="button",k.className="tvw-feedback-rating-btn tvw-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${u[C-1]}`),k.title=u[C-1],k.dataset.rating=String(C),k.innerHTML=`
|
|
17
17
|
<svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
18
|
<polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
|
|
19
19
|
</svg>
|
|
20
|
-
`,k.addEventListener("click",()=>{g=C,y.forEach((K,J)=>{let z=J<C;K.classList.toggle("selected",z),K.setAttribute("aria-checked",J===C-1?"true":"false")})}),y.push(k),T.appendChild(k)}m.appendChild(T);let S=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",S=document.createElement("textarea"),S.className="tvw-feedback-comment",S.placeholder=s,S.rows=3,S.setAttribute("aria-label","Additional comments"),C.appendChild(S),m.appendChild(C)}let R=document.createElement("div");R.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(g===null){T.classList.add("tvw-feedback-shake"),setTimeout(()=>T.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await n(g,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),R.appendChild(v),R.appendChild(N),m.appendChild(R),f.appendChild(m),f}function rs(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:f="Very likely"}=e,g=document.createElement("div");g.className="tvw-feedback-container tvw-feedback-nps",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let F=document.createElement("h3");F.className="tvw-feedback-title",F.textContent=t,h.appendChild(F);let T=document.createElement("p");T.className="tvw-feedback-subtitle",T.textContent=r,h.appendChild(T),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let S=document.createElement("div");S.className="tvw-feedback-labels";let R=document.createElement("span");R.className="tvw-feedback-label-low",R.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(R),S.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let _=0;_<=10;_++){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 ${_} out of 10`),j.textContent=String(_),j.dataset.rating=String(_),_<=6?j.classList.add("tvw-feedback-detractor"):_<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=_,C.forEach((Y,B)=>{Y.classList.toggle("selected",B===_),Y.setAttribute("aria-checked",B===_?"true":"false")})}),C.push(j),N.appendChild(j)}y.appendChild(S),y.appendChild(N),w.appendChild(y);let k=null;if(d){let _=document.createElement("div");_.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),_.appendChild(k),w.appendChild(_)}let K=document.createElement("div");K.className="tvw-feedback-actions";let J=document.createElement("button");J.type="button",J.className="tvw-feedback-btn tvw-feedback-btn-skip",J.textContent=a,J.addEventListener("click",()=>{o==null||o(),g.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){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}z.disabled=!0,z.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await n(m,_),g.remove()}catch(_){z.disabled=!1,z.textContent=i,console.error("[NPS Feedback] Failed to submit:",_)}}),K.appendChild(J),K.appendChild(z),w.appendChild(K),g.appendChild(w),g}var pn="persona-chat-history",na=30*1e3,ks=e=>!e||typeof e!="object"?{}:{...e},pi=e=>e.map(n=>({...n,streaming:!1})),gi=(e,n)=>{let o=e!=null&&e.markdown?Tn(e.markdown):null;return t=>{var i,a,d;let r=(i=t.text)!=null?i:"",s=(a=t.message.rawContent)!=null?a:null;if(n){let u=n.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});u!==null&&(r=u.text,u.persist||(t.message.__skipPersist=!0))}return e!=null&&e.postprocessMessage?e.postprocessMessage({...t,text:r,raw:(d=s!=null?s:t.text)!=null?d:""}):o?o(r):jn(r)}},is=(e,n,o)=>{var Rs,Fs,$s,Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Qn(n),r=Ln.getForInstance(t.plugins);t.components&&cn.registerAll(t.components);let s=li(),i=(Rs=t.storageAdapter)!=null?Rs:Zn(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=ks(c.metadata)),(Fs=c.messages)!=null&&Fs.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var A;a=(A=l({...a}))!=null?A:{},hn()},g=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Pn],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=Hn({parsers:g,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Os=($s=t.launcher)==null?void 0:$s.enabled)!=null?Os:!0,F=(js=(Ns=t.launcher)==null?void 0:Ns.autoExpand)!=null?js:!1,T=F,y=h,S=(_s=(Ds=t.layout)==null?void 0:Ds.header)==null?void 0:_s.layout,R=h?F:!0,v=gi(t,w),N=(Us=(qs=t.features)==null?void 0:qs.showReasoning)!=null?Us:!0,C=(Js=(zs=t.features)==null?void 0:zs.showToolCalls)!=null?Js:!0,k={onCopy:l=>{var c,A;s.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onCopy)==null||A.call(c,l)},onFeedback:l=>{var c,A;s.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(P=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",P)}),(A=(c=t.messageActions)==null?void 0:c.onFeedback)==null||A.call(c,l)}},K=(Ys=t.statusIndicator)!=null?Ys:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:mt.idle:l==="connecting"?(A=K.connectingText)!=null?A:mt.connecting:l==="connected"?(P=K.connectedText)!=null?P:mt.connected:l==="error"?(b=K.errorText)!=null?b:mt.error:mt[l]},{wrapper:z,panel:_}=ei(t),j=ti(t,h),{container:Y,body:B,messagesWrapper:V,suggestions:He,textarea:X,sendButton:D,sendButtonWrapper:nt,composerForm:lt,statusText:dt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:fe,headerTitle:ct,headerSubtitle:ut,header:Je,footer:pt,actionsRow:$t,leftActions:Pt,rightActions:Ht}=j,$=j.micButton,je=j.micButtonWrapper,pe=j.attachmentButton,st=j.attachmentButtonWrapper,ge=j.attachmentInput,ot=j.attachmentPreviewsContainer,Ae=null;(Ks=t.attachments)!=null&&Ks.enabled&&ge&&ot&&(Ae=Qt.fromConfig(t.attachments),Ae.setPreviewsContainer(ot),ge.addEventListener("change",l=>{let c=l.target;Ae==null||Ae.handleFileSelect(c.files),c.value=""}));let xt=r.find(l=>l.renderHeader);if(xt!=null&&xt.renderHeader){let l=xt.renderHeader({config:t,defaultRenderer:()=>{let c=qt({config:t,showClose:h});return Zt(Y,c,t),c.header},onClose:()=>E(!1,"user")});if(l){let c=Y.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Je=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>rn({config:t}).footer,onSubmit:c=>{H&&!H.isStreaming()&&H.sendMessage(c)},disabled:!1});l&&(pt.replaceWith(l),pt=l)}(()=>{var P,b;let l=(b=(P=t.layout)==null?void 0:P.slots)!=null?b:{},c=Q=>{switch(Q){case"body-top":return Y.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return V;case"footer-top":return He;case"composer":return lt;case"footer-bottom":return dt;default:return null}},A=(Q,de)=>{var M;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")Je.insertBefore(de,Je.firstChild);else if(Q==="header-right")Je.appendChild(de);else{let G=Je.querySelector(".tvw-flex-col");G?(M=G.parentNode)==null||M.insertBefore(de,G.nextSibling):Je.appendChild(de)}break;case"body-top":{let G=B.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");G?G.replaceWith(de):B.insertBefore(de,B.firstChild);break}case"body-bottom":B.appendChild(de);break;case"footer-top":He.replaceWith(de);break;case"footer-bottom":dt.replaceWith(de);break;default:break}};for(let[Q,de]of Object.entries(l))if(de)try{let M=de({config:t,defaultContent:()=>c(Q)});M&&A(Q,M)}catch(M){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,M)}})();let Ye=l=>{let A=l.target.closest('button[data-expand-header="true"]');if(!A)return;let P=A.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!P)return;let b=P.getAttribute("data-message-id");if(!b)return;let Q=A.getAttribute("data-bubble-type");Q==="reasoning"?(ln.has(b)?ln.delete(b):ln.add(b),oi(b,P)):Q==="tool"&&(dn.has(b)?dn.delete(b):dn.add(b),ri(b,P,t))};V.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),V.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ye(l))}),_.appendChild(Y),e.appendChild(z);let Ze=()=>{var ce,qe,Ue,it,Tt,ee,Ee,Kt,Vt,Rn,Fn,ps,ze,$n,wn,yn;let l=(qe=(ce=t.launcher)==null?void 0:ce.sidebarMode)!=null?qe:!1,c=l||((it=(Ue=t.launcher)==null?void 0:Ue.fullHeight)!=null?it:!1),A=(Tt=t.theme)!=null?Tt:{},P=(Ee=(ee=t.launcher)==null?void 0:ee.position)!=null?Ee:"bottom-left",b=P==="bottom-left"||P==="top-left",Q=l?"none":"1px solid var(--tvw-cw-border)",de=l?b?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",M=l?"0":"16px",G=(Kt=A.panelBorder)!=null?Kt:Q,Z=(Vt=A.panelShadow)!=null?Vt:de,ye=(Rn=A.panelBorderRadius)!=null?Rn:M;e.style.cssText="",z.style.cssText="",_.style.cssText="",Y.style.cssText="",B.style.cssText="",pt.style.cssText="";let O=(ps=(Fn=t==null?void 0:t.launcher)==null?void 0:Fn.width)!=null?ps:t==null?void 0:t.launcherWidth,$e=O!=null?O:"min(400px, calc(100vw - 24px))";l||(_.style.width=$e,_.style.maxWidth=$e),_.style.boxShadow=Z,_.style.borderRadius=ye,Y.style.border=G,Y.style.borderRadius=ye;let Se=((ze=t.launcher)==null?void 0:ze.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.height="100%",Se&&(z.style.overflow="hidden"),_.style.display="flex",_.style.flexDirection="column",_.style.flex="1 1 0%",_.style.minHeight="0",_.style.maxHeight="100%",_.style.height="100%",_.style.overflow="hidden",Y.style.display="flex",Y.style.flexDirection="column",Y.style.flex="1 1 0%",Y.style.minHeight="0",Y.style.maxHeight="100%",Y.style.overflow="hidden",B.style.flex="1 1 0%",B.style.minHeight="0",B.style.overflowY="auto",pt.style.flexShrink="0"),z.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!Se&&(($n=kt[P])!=null?$n:kt["bottom-right"]).split(" ").forEach(vn=>z.classList.add(vn)),l){let zt=(yn=(wn=t.launcher)==null?void 0:wn.sidebarWidth)!=null?yn:"420px";z.style.cssText=`
|
|
20
|
+
`,k.addEventListener("click",()=>{p=C,y.forEach((z,_)=>{let ne=_<C;z.classList.toggle("selected",ne),z.setAttribute("aria-checked",_===C-1?"true":"false")})}),y.push(k),M.appendChild(k)}m.appendChild(M);let A=null;if(d){let C=document.createElement("div");C.className="tvw-feedback-comment-container",A=document.createElement("textarea"),A.className="tvw-feedback-comment",A.placeholder=s,A.rows=3,A.setAttribute("aria-label","Additional comments"),C.appendChild(A),m.appendChild(C)}let I=document.createElement("div");I.className="tvw-feedback-actions";let v=document.createElement("button");v.type="button",v.className="tvw-feedback-btn tvw-feedback-btn-skip",v.textContent=a,v.addEventListener("click",()=>{o==null||o(),f.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(p===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let C=(A==null?void 0:A.value.trim())||void 0;await n(p,C),f.remove()}catch(C){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(N),m.appendChild(I),f.appendChild(m),f}function ls(e){let{onSubmit:n,onDismiss:o,title:t="How likely are you to recommend us?",subtitle:r="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:u="Not likely",highLabel:f="Very likely"}=e,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let R=document.createElement("h3");R.className="tvw-feedback-title",R.textContent=t,h.appendChild(R);let M=document.createElement("p");M.className="tvw-feedback-subtitle",M.textContent=r,h.appendChild(M),w.appendChild(h);let y=document.createElement("div");y.className="tvw-feedback-rating tvw-feedback-rating-nps",y.setAttribute("role","radiogroup"),y.setAttribute("aria-label","Likelihood rating from 0 to 10");let A=document.createElement("div");A.className="tvw-feedback-labels";let I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=u;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,A.appendChild(I),A.appendChild(v);let N=document.createElement("div");N.className="tvw-feedback-numbers";let C=[];for(let re=0;re<=10;re++){let V=document.createElement("button");V.type="button",V.className="tvw-feedback-rating-btn tvw-feedback-number-btn",V.setAttribute("role","radio"),V.setAttribute("aria-checked","false"),V.setAttribute("aria-label",`Rating ${re} out of 10`),V.textContent=String(re),V.dataset.rating=String(re),re<=6?V.classList.add("tvw-feedback-detractor"):re<=8?V.classList.add("tvw-feedback-passive"):V.classList.add("tvw-feedback-promoter"),V.addEventListener("click",()=>{m=re,C.forEach((J,L)=>{J.classList.toggle("selected",L===re),J.setAttribute("aria-checked",L===re?"true":"false")})}),C.push(V),N.appendChild(V)}y.appendChild(A),y.appendChild(N),w.appendChild(y);let k=null;if(d){let re=document.createElement("div");re.className="tvw-feedback-comment-container",k=document.createElement("textarea"),k.className="tvw-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),re.appendChild(k),w.appendChild(re)}let z=document.createElement("div");z.className="tvw-feedback-actions";let _=document.createElement("button");_.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-skip",_.textContent=a,_.addEventListener("click",()=>{o==null||o(),p.remove()});let ne=document.createElement("button");return ne.type="button",ne.className="tvw-feedback-btn tvw-feedback-btn-submit",ne.textContent=i,ne.addEventListener("click",async()=>{if(m===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}ne.disabled=!0,ne.textContent="Submitting...";try{let re=(k==null?void 0:k.value.trim())||void 0;await n(m,re),p.remove()}catch(re){ne.disabled=!1,ne.textContent=i,console.error("[NPS Feedback] Failed to submit:",re)}}),z.appendChild(_),z.appendChild(ne),w.appendChild(z),p.appendChild(w),p}var hn="persona-chat-history",ra=30*1e3,Hs=e=>!e||typeof e!="object"?{}:{...e},hi=e=>e.map(n=>({...n,streaming:!1})),fi=(e,n,o)=>{let t=e!=null&&e.markdown?kn(e.markdown):null;return r=>{var a,d,u;let s=(a=r.text)!=null?a:"",i=(d=r.message.rawContent)!=null?d:null;if(n){let f=n.process({text:s,raw:i!=null?i:s,message:r.message,streaming:r.streaming});f!==null&&(s=f.text,f.persist||(r.message.__skipPersist=!0),f.resubmit&&!r.streaming&&o&&o())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...r,text:s,raw:(u=i!=null?i:r.text)!=null?u:""}):t?t(s):qn(s)}},ds=(e,n,o)=>{var Os,Ns,js,Ds,_s,qs,Us,zs,Js,Ys,Ks,Vs,Xs,Gs,Qs,Zs,eo;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=ts(n),r=Bn.getForInstance(t.plugins);t.components&&gn.registerAll(t.components);let s=ui(),i=(Os=t.storageAdapter)!=null?Os:ns(),a={},d=null;if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l;else if(l){let c=l;c.metadata&&(a=Hs(c.metadata)),(Ns=c.messages)!=null&&Ns.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let u=()=>a,f=l=>{var T;a=(T=l({...a}))!=null?T:{},le()},p=t.actionParsers&&t.actionParsers.length?t.actionParsers:[In],m=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick],w=Rn({parsers:p,handlers:m,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Ds=(js=t.launcher)==null?void 0:js.enabled)!=null?Ds:!0,R=(qs=(_s=t.launcher)==null?void 0:_s.autoExpand)!=null?qs:!1,M=R,y=h,A=(zs=(Us=t.layout)==null?void 0:Us.header)==null?void 0:zs.layout,I=h?R:!0,v=!1,N=null,C=()=>{v=!0,N&&clearTimeout(N),N=setTimeout(()=>{v&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),v=!1)},1e4)},k=fi(t,w,C),z=(Ys=(Js=t.features)==null?void 0:Js.showReasoning)!=null?Ys:!0,_=(Vs=(Ks=t.features)==null?void 0:Ks.showToolCalls)!=null?Vs:!0,ne={onCopy:l=>{var c,T;s.emit("message:copy",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.id,"copy").catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onCopy)==null||T.call(c,l)},onFeedback:l=>{var c,T;s.emit("message:feedback",l),P!=null&&P.isClientTokenMode()&&P.submitMessageFeedback(l.messageId,l.type).catch(H=>{t.debug&&console.error("[AgentWidget] Failed to submit feedback:",H)}),(T=(c=t.messageActions)==null?void 0:c.onFeedback)==null||T.call(c,l)}},re=(Xs=t.statusIndicator)!=null?Xs:{},V=l=>{var c,T,H,b;return l==="idle"?(c=re.idleText)!=null?c:pt.idle:l==="connecting"?(T=re.connectingText)!=null?T:pt.connecting:l==="connected"?(H=re.connectedText)!=null?H:pt.connected:l==="error"?(b=re.errorText)!=null?b:pt.error:pt[l]},{wrapper:J,panel:L}=si(t),q=oi(t,h),{container:Z,body:de,messagesWrapper:qe,suggestions:Ct,textarea:ee,sendButton:j,sendButtonWrapper:at,composerForm:xt,statusText:vt,introTitle:Rt,introSubtitle:Ft,closeButton:D,iconHolder:fe,headerTitle:lt,headerSubtitle:dt,header:Ve,footer:ct,actionsRow:jt,leftActions:$t,rightActions:Ot}=q,F=q.micButton,Ue=q.micButtonWrapper,ge=q.attachmentButton,tt=q.attachmentButtonWrapper,me=q.attachmentInput,nt=q.attachmentPreviewsContainer,U=null;(Gs=t.attachments)!=null&&Gs.enabled&&me&&nt&&(U=Zt.fromConfig(t.attachments),U.setPreviewsContainer(nt),me.addEventListener("change",l=>{let c=l.target;U==null||U.handleFileSelect(c.files),c.value=""}));let Re=r.find(l=>l.renderHeader);if(Re!=null&&Re.renderHeader){let l=Re.renderHeader({config:t,defaultRenderer:()=>{let c=Ut({config:t,showClose:h});return en(Z,c,t),c.header},onClose:()=>S(!1,"user")});if(l){let c=Z.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Ve=l)}}let Xe=r.find(l=>l.renderComposer);if(Xe!=null&&Xe.renderComposer){let l=Xe.renderComposer({config:t,defaultRenderer:()=>dn({config:t}).footer,onSubmit:c=>{P&&!P.isStreaming()&&P.sendMessage(c)},disabled:!1});l&&(ct.replaceWith(l),ct=l)}(()=>{var H,b;let l=(b=(H=t.layout)==null?void 0:H.slots)!=null?b:{},c=X=>{switch(X){case"body-top":return Z.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return qe;case"footer-top":return Ct;case"composer":return xt;case"footer-bottom":return vt;default:return null}},T=(X,ce)=>{var W;switch(X){case"header-left":case"header-center":case"header-right":if(X==="header-left")Ve.insertBefore(ce,Ve.firstChild);else if(X==="header-right")Ve.appendChild(ce);else{let K=Ve.querySelector(".tvw-flex-col");K?(W=K.parentNode)==null||W.insertBefore(ce,K.nextSibling):Ve.appendChild(ce)}break;case"body-top":{let K=de.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");K?K.replaceWith(ce):de.insertBefore(ce,de.firstChild);break}case"body-bottom":de.appendChild(ce);break;case"footer-top":Ct.replaceWith(ce);break;case"footer-bottom":vt.replaceWith(ce);break;default:break}};for(let[X,ce]of Object.entries(l))if(ce)try{let W=ce({config:t,defaultContent:()=>c(X)});W&&T(X,W)}catch(W){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${X}":`,W)}})();let gt=l=>{let T=l.target.closest('button[data-expand-header="true"]');if(!T)return;let H=T.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!H)return;let b=H.getAttribute("data-message-id");if(!b)return;let X=T.getAttribute("data-bubble-type");X==="reasoning"?(un.has(b)?un.delete(b):un.add(b),ai(b,H)):X==="tool"&&(pn.has(b)?pn.delete(b):pn.add(b),li(b,H,t))};qe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),qe.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),gt(l))}),L.appendChild(Z),e.appendChild(J);let Pt=()=>{var ue,Je,Ye,rt,Tt,Q,Me,Vt,Xt,On,Nn,hs,Ke,jn,Cn,xn;let l=(Je=(ue=t.launcher)==null?void 0:ue.sidebarMode)!=null?Je:!1,c=l||((rt=(Ye=t.launcher)==null?void 0:Ye.fullHeight)!=null?rt:!1),T=(Tt=t.theme)!=null?Tt:{},H=(Me=(Q=t.launcher)==null?void 0:Q.position)!=null?Me:"bottom-left",b=H==="bottom-left"||H==="top-left",X=l?"none":"1px solid var(--tvw-cw-border)",ce=l?b?"2px 0 12px rgba(0, 0, 0, 0.08)":"-2px 0 12px rgba(0, 0, 0, 0.08)":"0 25px 50px -12px rgba(0, 0, 0, 0.25)",W=l?"0":"16px",K=(Vt=T.panelBorder)!=null?Vt:X,G=(Xt=T.panelShadow)!=null?Xt:ce,Ce=(On=T.panelBorderRadius)!=null?On:W;e.style.cssText="",J.style.cssText="",L.style.cssText="",Z.style.cssText="",de.style.cssText="",ct.style.cssText="";let $=(hs=(Nn=t==null?void 0:t.launcher)==null?void 0:Nn.width)!=null?hs:t==null?void 0:t.launcherWidth,je=$!=null?$:"min(400px, calc(100vw - 24px))";l||(L.style.width=je,L.style.maxWidth=je),L.style.boxShadow=G,L.style.borderRadius=Ce,Z.style.border=K,Z.style.borderRadius=Ce;let Se=((Ke=t.launcher)==null?void 0:Ke.enabled)===!1;if(c&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",J.style.display="flex",J.style.flexDirection="column",J.style.flex="1 1 0%",J.style.minHeight="0",J.style.maxHeight="100%",J.style.height="100%",Se&&(J.style.overflow="hidden"),L.style.display="flex",L.style.flexDirection="column",L.style.flex="1 1 0%",L.style.minHeight="0",L.style.maxHeight="100%",L.style.height="100%",L.style.overflow="hidden",Z.style.display="flex",Z.style.flexDirection="column",Z.style.flex="1 1 0%",Z.style.minHeight="0",Z.style.maxHeight="100%",Z.style.overflow="hidden",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.overflowY="auto",ct.style.flexShrink="0"),J.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!Se&&((jn=It[H])!=null?jn:It["bottom-right"]).split(" ").forEach(Sn=>J.classList.add(Sn)),l){let Jt=(xn=(Cn=t.launcher)==null?void 0:Cn.sidebarWidth)!=null?xn:"420px";J.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
24
|
-
width: ${
|
|
24
|
+
width: ${Jt} !important;
|
|
25
25
|
height: 100vh !important;
|
|
26
26
|
max-height: 100vh !important;
|
|
27
27
|
margin: 0 !important;
|
|
@@ -29,7 +29,7 @@
|
|
|
29
29
|
display: flex !important;
|
|
30
30
|
flex-direction: column !important;
|
|
31
31
|
${b?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
32
|
-
`,
|
|
32
|
+
`,L.style.cssText=`
|
|
33
33
|
position: relative !important;
|
|
34
34
|
display: flex !important;
|
|
35
35
|
flex-direction: column !important;
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
min-height: 0 !important;
|
|
41
41
|
margin: 0 !important;
|
|
42
42
|
padding: 0 !important;
|
|
43
|
-
box-shadow: ${
|
|
44
|
-
border-radius: ${
|
|
45
|
-
`,
|
|
43
|
+
box-shadow: ${G} !important;
|
|
44
|
+
border-radius: ${Ce} !important;
|
|
45
|
+
`,L.style.setProperty("width","100%","important"),L.style.setProperty("max-width","100%","important"),Z.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: ${K} !important;
|
|
56
|
+
`,ct.style.cssText=`
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!Se){let zt="max-height: -moz-available !important; max-height: stretch !important;",vn=l?"":"padding-top: 1.25em !important;";z.style.cssText+=zt+vn}};Ze(),Xn(e,t);let ke=[],Ke=null,Wt=()=>{Ke&&(Ke(),Ke=null),t.colorScheme==="auto"&&(Ke=Gr(()=>{Xn(e,t)}))};Wt(),ke.push(()=>{Ke&&(Ke(),Ke=null)});let ft=ii(He),rt=null,H,wt=!1,yt=!0,At=0,te=0,we=null,Fe=!1,vt=0,et=!1,Bt=125,It=2e3,Ot=5,nn=50,Nt=new Map,Le={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},gn=(Xs=(Vs=t.voiceRecognition)==null?void 0:Vs.autoResume)!=null?Xs:!1,mn=l=>{s.emit("voice:state",{active:Le.active,source:l,timestamp:Date.now()})},jt=()=>{f(l=>({...l,voiceState:{active:Le.active,timestamp:Date.now(),manuallyDeactivated:Le.manuallyDeactivated}}))},Bn=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=ks(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);Le.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<na&&setTimeout(()=>{Le.active||(Le.manuallyDeactivated=!1,_e("restore"))},1e3)},In=()=>H?pi(H.getMessages()).filter(l=>!l.__skipPersist):[];function hn(l){if(!(i!=null&&i.save))return;let A={messages:l?pi(l):H?In():[],metadata:a};try{let P=i.save(A);P instanceof Promise&&P.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(P){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",P)}}let Yt=(l=!1)=>{if(!yt)return;let c=Date.now();Fe&&c<vt&&!l||(Fe&&c>=vt&&(Fe=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,we&&cancelAnimationFrame(we),we=requestAnimationFrame(()=>{Fe||!yt||(et=!0,B.scrollTop=B.scrollHeight,At=B.scrollTop,requestAnimationFrame(()=>{et=!1}),we=null)}))))},L=null,ae=()=>z.querySelector("#persona-scroll-container")||B,xe=(l,c=500)=>{let A=l.scrollTop,P=l.clientHeight,b=l.scrollHeight,Q=b-A;if(A+P>=b-2||Math.abs(Q)<5)return;L!==null&&(cancelAnimationFrame(L),L=null);let M=performance.now(),G=ye=>1-Math.pow(1-ye,3),Z=ye=>{let O=l.scrollHeight;O!==b&&(b=O,Q=b-A);let $e=ye-M,Se=Math.min($e/c,1),ce=G(Se),qe=A+Q*ce;l.scrollTop=qe,Se<1?L=requestAnimationFrame(Z):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(Z)},De=l=>{let c=new Map;l.forEach(A=>{let P=Nt.get(A.id);c.set(A.id,{streaming:A.streaming,role:A.role}),!P&&A.role==="assistant"&&s.emit("assistant:message",A),A.role==="assistant"&&(P!=null&&P.streaming)&&A.streaming===!1&&s.emit("assistant:complete",A)}),Nt.clear(),c.forEach((A,P)=>{Nt.set(P,A)})},Ve=(l,c,A)=>{let P=document.createElement("div");c.forEach(M=>{var $e,Se;let G=null,Z=r.find(ce=>!!(M.variant==="reasoning"&&ce.renderReasoning||M.variant==="tool"&&ce.renderToolCall||!M.variant&&ce.renderMessage)),ye=($e=t.layout)==null?void 0:$e.messages;if(Z)if(M.variant==="reasoning"&&M.reasoning&&Z.renderReasoning){if(!N)return;G=Z.renderReasoning({message:M,defaultRenderer:()=>Cs(M),config:t})}else if(M.variant==="tool"&&M.toolCall&&Z.renderToolCall){if(!C)return;G=Z.renderToolCall({message:M,defaultRenderer:()=>xs(M,t),config:t})}else Z.renderMessage&&(G=Z.renderMessage({message:M,defaultRenderer:()=>{let ce=an(M,A,ye,t.messageActions,k);return M.role!=="user"&&Ss(ce,M,t,H),ce},config:t}));if(!G&&M.role==="assistant"&&!M.variant&&t.enableComponentStreaming!==!1&&ns(M)){let qe=ss(M);if(qe){let Ue=ts(qe,{config:t,message:M,transform:A});if(Ue){let it=document.createElement("div");if(it.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(" "),it.id=`bubble-${M.id}`,it.setAttribute("data-message-id",M.id),M.content&&M.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=A({text:M.content,message:M,streaming:!!M.streaming,raw:M.rawContent}),it.appendChild(Tt)}it.appendChild(Ue),G=it}}}if(!G)if(M.variant==="reasoning"&&M.reasoning){if(!N)return;G=Cs(M)}else if(M.variant==="tool"&&M.toolCall){if(!C)return;G=xs(M,t)}else{let ce=(Se=t.layout)==null?void 0:Se.messages;ce!=null&&ce.renderUserMessage&&M.role==="user"?G=ce.renderUserMessage({message:M,config:t,streaming:!!M.streaming}):ce!=null&&ce.renderAssistantMessage&&M.role==="assistant"?G=ce.renderAssistantMessage({message:M,config:t,streaming:!!M.streaming}):G=an(M,A,ce,t.messageActions,k),M.role!=="user"&&G&&Ss(G,M,t,H)}let O=document.createElement("div");O.className="tvw-flex",O.id=`wrapper-${M.id}`,O.setAttribute("data-wrapper-id",M.id),M.role==="user"&&O.classList.add("tvw-justify-end"),O.appendChild(G),P.appendChild(O)});let b=c.some(M=>M.role==="assistant"&&M.streaming),Q=c[c.length-1],de=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(M=>M.role==="user")&&!b&&!de){let M=kn(),G=document.createElement("div");G.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(" "),G.setAttribute("data-typing-indicator","true"),G.appendChild(M);let Z=document.createElement("div");Z.className="tvw-flex",Z.id="wrapper-typing-indicator",Z.setAttribute("data-wrapper-id","typing-indicator"),Z.appendChild(G),P.appendChild(Z)}Zr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let M=ae();xe(M)})})},Pe=()=>{h&&(R?(z.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-95","tvw-opacity-0"),_.classList.add("tvw-scale-100","tvw-opacity-100"),le?le.element.style.display="none":he&&(he.style.display="none")):(z.classList.add("tvw-pointer-events-none","tvw-opacity-0"),_.classList.remove("tvw-scale-100","tvw-opacity-100"),_.classList.add("tvw-scale-95","tvw-opacity-0"),le?le.element.style.display="":he&&(he.style.display="")))},E=(l,c="user")=>{if(!h||R===l)return;let A=R;R=l,Pe(),R&&(fn(),Yt(!0));let P={open:R,source:c,timestamp:Date.now()};R&&!A?s.emit("widget:opened",P):!R&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()})},bt=l=>{D.disabled=l,$&&($.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},se=()=>{var b,Q,de,M,G,Z,ye,O,$e,Se,ce,qe,Ue,it;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(M=(de=t.copy)==null?void 0:de.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",X.placeholder=(Z=(G=t.copy)==null?void 0:G.inputPlaceholder)!=null?Z:"How can I help...",((O=(ye=t.sendButton)==null?void 0:ye.useIcon)!=null?O:!1)||(D.textContent=(Se=($e=t.copy)==null?void 0:$e.sendButtonLabel)!=null?Se:"Send");let c=(qe=(ce=t.theme)==null?void 0:ce.inputFontFamily)!=null?qe:"sans-serif",A=(it=(Ue=t.theme)==null?void 0:Ue.inputFontWeight)!=null?it:"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'}};X.style.fontFamily=P(c),X.style.fontWeight=A};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),H=new sn(t,{onMessagesChanged(l){Ve(V,l,v),H&&(l.some(P=>P.role==="user")?ft.render([],H,X,l):ft.render(t.suggestionChips,H,X,l,t.suggestionChipsConfig)),Yt(!wt),De(l);let c=[...l].reverse().find(A=>A.role==="user");Le.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),hn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,de,M,G;return b==="idle"?(Q=c.idleText)!=null?Q:mt.idle:b==="connecting"?(de=c.connectingText)!=null?de:mt.connecting:b==="connected"?(M=c.connectedText)!=null?M:mt.connected:b==="error"?(G=c.errorText)!=null?G:mt.error:mt[b]};dt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),H&&Ve(V,H.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=ks(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let I=l=>{var b;l.preventDefault();let c=X.value.trim(),A=(b=Ae==null?void 0:Ae.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Ae.getContentParts()),c&&P.push(Yn(c))),X.value="",X.style.height="auto",H.sendMessage(c,{contentParts:P}),A&&Ae.clearAttachments()},W=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),D.click())},U=null,me=!1,Te=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_e=(l="user")=>{var Q,de,M,G;if(me||H.isStreaming())return;let c=Ie();if(!c)return;U=new c;let P=(de=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?de:2e3;U.continuous=!0,U.interimResults=!0,U.lang="en-US";let b=X.value;U.onresult=Z=>{let ye="",O="";for(let Se=0;Se<Z.results.length;Se++){let ce=Z.results[Se],qe=ce[0].transcript;ce.isFinal?ye+=qe+" ":O=qe}let $e=b+ye+O;X.value=$e,Te&&clearTimeout(Te),(ye||O)&&(Te=window.setTimeout(()=>{let Se=X.value.trim();Se&&U&&me&&(We(),X.value="",X.style.height="auto",H.sendMessage(Se,{viaVoice:!0}))},P))},U.onerror=Z=>{Z.error!=="no-speech"&&We()},U.onend=()=>{if(me){let Z=X.value.trim();Z&&Z!==b.trim()&&(X.value="",X.style.height="auto",H.sendMessage(Z,{viaVoice:!0})),We()}};try{if(U.start(),me=!0,Le.active=!0,l!=="system"&&(Le.manuallyDeactivated=!1),mn(l),jt(),$){Xe={backgroundColor:$.style.backgroundColor,color:$.style.color,borderColor:$.style.borderColor};let Z=(M=t.voiceRecognition)!=null?M:{},ye=(G=Z.recordingBackgroundColor)!=null?G:"#ef4444",O=Z.recordingIconColor,$e=Z.recordingBorderColor;if($.classList.add("tvw-voice-recording"),$.style.backgroundColor=ye,O){$.style.color=O;let Se=$.querySelector("svg");Se&&Se.setAttribute("stroke",O)}$e&&($.style.borderColor=$e),$.setAttribute("aria-label","Stop voice recognition")}}catch{We("system")}},We=(l="user")=>{if(me){if(me=!1,Te&&(clearTimeout(Te),Te=null),U){try{U.stop()}catch{}U=null}if(Le.active=!1,mn(l),jt(),$){if($.classList.remove("tvw-voice-recording"),Xe){$.style.backgroundColor=Xe.backgroundColor,$.style.color=Xe.color,$.style.borderColor=Xe.borderColor;let c=$.querySelector("svg");c&&c.setAttribute("stroke",Xe.color||"currentColor"),Xe=null}$.setAttribute("aria-label","Start voice recognition")}}},be=(l,c)=>{var qe,Ue,it,Tt,ee,Ee,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=p("div","tvw-send-button-wrapper"),b=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");b.type="button",b.setAttribute("aria-label","Start voice recognition");let Q=(qe=l==null?void 0:l.iconName)!=null?qe:"mic",de=(Ue=c==null?void 0:c.size)!=null?Ue:"40px",M=(it=l==null?void 0:l.iconSize)!=null?it:de,G=parseFloat(M)||24,Z=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ye=(ee=l==null?void 0:l.iconColor)!=null?ee:c==null?void 0:c.textColor;b.style.width=M,b.style.height=M,b.style.minWidth=M,b.style.minHeight=M,b.style.fontSize="18px",b.style.lineHeight="1";let O=ye||"currentColor",$e=oe(Q,G,O,1.5);$e?(b.appendChild($e),b.style.color=O):(b.textContent="\u{1F3A4}",b.style.color=O),Z?b.style.backgroundColor=Z:b.classList.add("tvw-bg-cw-primary"),ye?b.style.color=ye:!ye&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),P.appendChild(b);let Se=(Ee=l==null?void 0:l.tooltipText)!=null?Ee:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Se){let Vt=p("div","tvw-send-button-tooltip");Vt.textContent=Se,P.appendChild(Vt)}return{micButton:b,micButtonWrapper:P}},Ce=()=>{if(me){let l=X.value.trim();Le.manuallyDeactivated=!0,jt(),We("user"),l&&(X.value="",X.style.height="auto",H.sendMessage(l))}else Le.manuallyDeactivated=!1,jt(),_e("user")};$&&($.addEventListener("click",Ce),ke.push(()=>{We("system"),$&&$.removeEventListener("click",Ce)}));let Ge=s.on("assistant:complete",()=>{gn&&(Le.active||Le.manuallyDeactivated||gn==="assistant"&&!Le.lastUserMessageWasVoice||setTimeout(()=>{!Le.active&&!Le.manuallyDeactivated&&_e("auto")},600))});ke.push(Ge);let Me=s.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.sendMessage("[continue]")},500)});ke.push(Me);let Re=()=>{E(!R,"user")},le=null,he=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Wn(t,Re).element,onToggle:Re});c&&(he=c)}he||(le=Wn(t,Re))}le?e.appendChild(le.element):he&&e.appendChild(he),Pe(),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming()),Yt(!0),Bn();let fn=()=>{var A,P,b,Q,de,M,G,Z;let l=(P=(A=t.launcher)==null?void 0:A.sidebarMode)!=null?P:!1,c=l||((Q=(b=t.launcher)==null?void 0:b.fullHeight)!=null?Q:!1);if(!h){_.style.height="",_.style.width="";return}if(!l){let ye=(M=(de=t==null?void 0:t.launcher)==null?void 0:de.width)!=null?M:t==null?void 0:t.launcherWidth,O=ye!=null?ye:"min(400px, calc(100vw - 24px))";_.style.width=O,_.style.maxWidth=O}if(!c){let ye=window.innerHeight,O=64,$e=(Z=(G=t.launcher)==null?void 0:G.heightOffset)!=null?Z:0,Se=Math.max(200,ye-O),ce=Math.min(640,Se),qe=Math.max(200,ce-$e);_.style.height=`${qe}px`}};fn(),window.addEventListener("resize",fn),ke.push(()=>window.removeEventListener("resize",fn)),At=B.scrollTop;let Bs=()=>{let l=B.scrollTop,c=B.scrollHeight,A=B.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!et&&!(b<=Ot)){if(!yt&&P<nn){Fe=!1,yt=!0;return}yt&&P>nn&&(Fe=!0,vt=Date.now()+It,yt=!1)}};B.addEventListener("scroll",Bs,{passive:!0}),ke.push(()=>B.removeEventListener("scroll",Bs)),ke.push(()=>{we&&cancelAnimationFrame(we)});let Is=()=>{q&&(rt&&(q.removeEventListener("click",rt),rt=null),h?(q.style.display="",rt=()=>{R=!1,Pe()},q.addEventListener("click",rt)):q.style.display="none")};Is(),(()=>{let{clearChatButton:l}=j;l&&l.addEventListener("click",()=>{H.clearMessages();try{localStorage.removeItem(pn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pn}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==pn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(A){console.error("[AgentWidget] Failed to clear custom localStorage:",A)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let A=i.clear();A instanceof Promise&&A.catch(P=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",P)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)}a={},w.syncFromMetadata()})})(),lt.addEventListener("submit",I),X.addEventListener("keydown",W),ke.push(()=>{lt.removeEventListener("submit",I),X.removeEventListener("keydown",W)}),ke.push(()=>{H.cancel()}),le?ke.push(()=>{le==null||le.destroy()}):he&&ke.push(()=>{he==null||he.remove()});let Dt={update(l){var Qs,Zs,eo,to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Vo,Xo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Ze(),Xn(e,t),t.colorScheme!==A&&Wt();let P=Ln.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Zs=(Qs=t.launcher)==null?void 0:Qs.enabled)!=null?Zs:!0,F=(to=(eo=t.launcher)==null?void 0:eo.autoExpand)!=null?to:!1,N=(so=(no=t.features)==null?void 0:no.showReasoning)!=null?so:!0,C=(ro=(oo=t.features)==null?void 0:oo.showToolCalls)!=null?ro:!0,((io=t.launcher)==null?void 0:io.enabled)===!1&&le&&(le.destroy(),le=null),((ao=t.launcher)==null?void 0:ao.enabled)===!1&&he&&(he.remove(),he=null),((lo=t.launcher)==null?void 0:lo.enabled)!==!1&&!le&&!he){let x=r.find(ue=>ue.renderLauncher);if(x!=null&&x.renderLauncher){let ue=x.renderLauncher({config:t,defaultRenderer:()=>Wn(t,Re).element,onToggle:Re});ue&&(he=ue,e.appendChild(he))}he||(le=Wn(t,Re),e.appendChild(le.element))}le&&le.update(t),ct&&((co=t.launcher)==null?void 0:co.title)!==void 0&&(ct.textContent=t.launcher.title),ut&&((uo=t.launcher)==null?void 0:uo.subtitle)!==void 0&&(ut.textContent=t.launcher.subtitle);let b=(po=t.layout)==null?void 0:po.header;if((b==null?void 0:b.layout)!==S&&Je){let x=b?on(t,b,{showClose:h,onClose:()=>E(!1,"user")}):qt({config:t,showClose:h,onClose:()=>E(!1,"user")});Je.replaceWith(x.header),Je=x.header,fe=x.iconHolder,ct=x.headerTitle,ut=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),ct&&(ct.style.display=b.showTitle===!1?"none":""),ut&&(ut.style.display=b.showSubtitle===!1?"none":""),q&&(q.style.display=b.showCloseButton===!1?"none":""),j.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){j.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:ue}=j;ue&&!ue.classList.contains("tvw-absolute")&&(x?ue.classList.remove("tvw-ml-auto"):ue.classList.add("tvw-ml-auto"))}}let de=((go=t.layout)==null?void 0:go.showHeader)!==!1;Je&&(Je.style.display=de?"":"none");let M=((mo=t.layout)==null?void 0:mo.showFooter)!==!1;pt&&(pt.style.display=M?"":"none"),h!==y?h?E(F,"auto"):(R=!0,Pe()):F!==T&&E(F,"auto"),T=F,y=h,fn(),Is(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&H&&Ve(V,H.getMessages(),v);let O=(ho=t.launcher)!=null?ho:{},$e=(fo=O.headerIconHidden)!=null?fo:!1,Se=(yo=(wo=t.layout)==null?void 0:wo.header)==null?void 0:yo.showIcon,ce=$e||Se===!1,qe=O.headerIconName,Ue=(vo=O.headerIconSize)!=null?vo:"48px";if(fe){let x=Y.querySelector(".tvw-border-b-cw-divider"),ue=x==null?void 0:x.querySelector(".tvw-flex-col");if(ce)fe.style.display="none",x&&ue&&!x.contains(ue)&&x.insertBefore(ue,x.firstChild);else{if(fe.style.display="",fe.style.height=Ue,fe.style.width=Ue,x&&ue&&(x.contains(fe)?fe.nextSibling!==ue&&(fe.remove(),x.insertBefore(fe,ue)):x.insertBefore(fe,ue)),qe){let ne=parseFloat(Ue)||24,ve=oe(qe,ne*.6,"#ffffff",2);ve?fe.replaceChildren(ve):fe.textContent=(bo=O.agentIconText)!=null?bo:"\u{1F4AC}"}else if(O.iconUrl){let ne=fe.querySelector("img");if(ne)ne.src=O.iconUrl,ne.style.height=Ue,ne.style.width=Ue;else{let ve=document.createElement("img");ve.src=O.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=Ue,ve.style.width=Ue,fe.replaceChildren(ve)}}else{let ne=fe.querySelector("svg"),ve=fe.querySelector("img");(ne||ve)&&fe.replaceChildren(),fe.textContent=(Co=O.agentIconText)!=null?Co:"\u{1F4AC}"}let Oe=fe.querySelector("img");Oe&&(Oe.style.height=Ue,Oe.style.width=Ue)}}let it=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showTitle,Tt=(To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showSubtitle;if(ct&&(ct.style.display=it===!1?"none":""),ut&&(ut.style.display=Tt===!1?"none":""),q){((Eo=(Mo=t.layout)==null?void 0:Mo.header)==null?void 0:Eo.showCloseButton)===!1?q.style.display="none":q.style.display="";let ue=(Wo=O.closeButtonSize)!=null?Wo:"32px",Oe=(ko=O.closeButtonPlacement)!=null?ko:"inline";q.style.height=ue,q.style.width=ue;let{closeButtonWrapper:ne}=j,ve=Oe==="top-right",gt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&ve!==gt)if(ne.remove(),ve)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let re=(Po=(Lo=O.clearChat)==null?void 0:Lo.placement)!=null?Po:"inline",Qe=(Bo=(Ho=O.clearChat)==null?void 0:Ho.enabled)!=null?Bo:!0;ne.className=Qe&&re==="inline"?"":"tvw-ml-auto";let Ct=Y.querySelector(".tvw-border-b-cw-divider");Ct&&Ct.appendChild(ne)}if(O.closeButtonColor?(q.style.color=O.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),O.closeButtonBackgroundColor?(q.style.backgroundColor=O.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),O.closeButtonBorderWidth||O.closeButtonBorderColor){let re=O.closeButtonBorderWidth||"0px",Qe=O.closeButtonBorderColor||"transparent";q.style.border=`${re} solid ${Qe}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");O.closeButtonBorderRadius?(q.style.borderRadius=O.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),O.closeButtonPaddingX?(q.style.paddingLeft=O.closeButtonPaddingX,q.style.paddingRight=O.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),O.closeButtonPaddingY?(q.style.paddingTop=O.closeButtonPaddingY,q.style.paddingBottom=O.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let at=(Io=O.closeButtonIconName)!=null?Io:"x",Mt=(Ro=O.closeButtonIconText)!=null?Ro:"\xD7";q.innerHTML="";let ht=oe(at,"20px",O.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Mt;let Ne=(Fo=O.closeButtonTooltipText)!=null?Fo:"Close chat",Et=($o=O.closeButtonShowTooltip)!=null?$o:!0;if(q.setAttribute("aria-label",Ne),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!q)return;re=p("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let Sn=p("div");Sn.className="tvw-clear-chat-tooltip-arrow",re.appendChild(Sn);let Xt=q.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};ne.addEventListener("mouseenter",Qe),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Qe),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Qe),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Qe),q.removeEventListener("blur",Ct))}}}let{clearChatButton:ee,clearChatButtonWrapper:Ee}=j;if(ee){let x=(Oo=O.clearChat)!=null?Oo:{},ue=(No=x.enabled)!=null?No:!0,Oe=(Do=(jo=t.layout)==null?void 0:jo.header)==null?void 0:Do.showClearChat,ne=Oe!==void 0?Oe:ue,ve=(_o=x.placement)!=null?_o:"inline";if(Ee){Ee.style.display=ne?"":"none";let{closeButtonWrapper:gt}=j;gt&&!gt.classList.contains("tvw-absolute")&&(ne?gt.classList.remove("tvw-ml-auto"):gt.classList.add("tvw-ml-auto"));let at=ve==="top-right",Mt=Ee.classList.contains("tvw-absolute");if(at!==Mt&&ne){if(Ee.remove(),at)Ee.className="tvw-absolute tvw-top-4 tvw-z-50",Ee.style.right="48px",Y.style.position="relative",Y.appendChild(Ee);else{Ee.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ee.style.right="";let Ne=Y.querySelector(".tvw-border-b-cw-divider"),Et=j.closeButtonWrapper;Ne&&Et&&Et.parentElement===Ne?Ne.insertBefore(Ee,Et):Ne&&Ne.appendChild(Ee)}let ht=j.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(at?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let gt=(qo=x.size)!=null?qo:"32px";ee.style.height=gt,ee.style.width=gt;let at=(Uo=x.iconName)!=null?Uo:"refresh-cw",Mt=(zo=x.iconColor)!=null?zo:"";ee.innerHTML="";let ht=oe(at,"20px",Mt||"",2);if(ht&&ee.appendChild(ht),Mt?(ee.style.color=Mt,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),x.backgroundColor?(ee.style.backgroundColor=x.backgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let re=x.borderWidth||"0px",Qe=x.borderColor||"transparent";ee.style.border=`${re} solid ${Qe}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");x.borderRadius?(ee.style.borderRadius=x.borderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),x.paddingX?(ee.style.paddingLeft=x.paddingX,ee.style.paddingRight=x.paddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),x.paddingY?(ee.style.paddingTop=x.paddingY,ee.style.paddingBottom=x.paddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Ne=(Jo=x.tooltipText)!=null?Jo:"Clear chat",Et=(Yo=x.showTooltip)!=null?Yo:!0;if(ee.setAttribute("aria-label",Ne),Ee&&(Ee._cleanupTooltip&&(Ee._cleanupTooltip(),delete Ee._cleanupTooltip),Et&&Ne)){let re=null,Qe=()=>{if(re||!ee)return;re=p("div","tvw-clear-chat-tooltip"),re.textContent=Ne;let Sn=p("div");Sn.className="tvw-clear-chat-tooltip-arrow",re.appendChild(Sn);let Xt=ee.getBoundingClientRect();re.style.position="fixed",re.style.left=`${Xt.left+Xt.width/2}px`,re.style.top=`${Xt.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ct=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};Ee.addEventListener("mouseenter",Qe),Ee.addEventListener("mouseleave",Ct),ee.addEventListener("focus",Qe),ee.addEventListener("blur",Ct),Ee._cleanupTooltip=()=>{Ct(),Ee&&(Ee.removeEventListener("mouseenter",Qe),Ee.removeEventListener("mouseleave",Ct)),ee&&(ee.removeEventListener("focus",Qe),ee.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Pn],Vt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=Hn({parsers:Kt,handlers:Vt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=gi(t,w),H.updateConfig(t),Ve(V,H.getMessages(),v),ft.render(t.suggestionChips,H,X,void 0,t.suggestionChipsConfig),se(),bt(H.isStreaming());let Rn=((Ko=t.voiceRecognition)==null?void 0:Ko.enabled)===!0,Fn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Rn&&Fn)if(!$||!je){let x=be(t.voiceRecognition,t.sendButton);x&&($=x.micButton,je=x.micButtonWrapper,Ht.insertBefore(je,nt),$.addEventListener("click",Ce),$.disabled=H.isStreaming())}else{let x=(Vo=t.voiceRecognition)!=null?Vo:{},ue=(Xo=t.sendButton)!=null?Xo:{},Oe=(Go=x.iconName)!=null?Go:"mic",ne=(Qo=ue.size)!=null?Qo:"40px",ve=(Zo=x.iconSize)!=null?Zo:ne,gt=parseFloat(ve)||24;$.style.width=ve,$.style.height=ve,$.style.minWidth=ve,$.style.minHeight=ve;let at=(tr=(er=x.iconColor)!=null?er:ue.textColor)!=null?tr:"currentColor";$.innerHTML="";let Mt=oe(Oe,gt,at,2);Mt?$.appendChild(Mt):$.textContent="\u{1F3A4}";let ht=(nr=x.backgroundColor)!=null?nr:ue.backgroundColor;ht?($.style.backgroundColor=ht,$.classList.remove("tvw-bg-cw-primary")):($.style.backgroundColor="",$.classList.add("tvw-bg-cw-primary")),at?($.style.color=at,$.classList.remove("tvw-text-white")):!at&&!ue.textColor&&($.style.color="",$.classList.add("tvw-text-white")),x.borderWidth?($.style.borderWidth=x.borderWidth,$.style.borderStyle="solid"):($.style.borderWidth="",$.style.borderStyle=""),x.borderColor?$.style.borderColor=x.borderColor:$.style.borderColor="",x.paddingX?($.style.paddingLeft=x.paddingX,$.style.paddingRight=x.paddingX):($.style.paddingLeft="",$.style.paddingRight=""),x.paddingY?($.style.paddingTop=x.paddingY,$.style.paddingBottom=x.paddingY):($.style.paddingTop="",$.style.paddingBottom="");let Ne=je==null?void 0:je.querySelector(".tvw-send-button-tooltip"),Et=(sr=x.tooltipText)!=null?sr:"Start voice recognition";if(((or=x.showTooltip)!=null?or:!1)&&Et)if(Ne)Ne.textContent=Et,Ne.style.display="";else{let Qe=document.createElement("div");Qe.className="tvw-send-button-tooltip",Qe.textContent=Et,je==null||je.insertBefore(Qe,$)}else Ne&&(Ne.style.display="none");je.style.display="",$.disabled=H.isStreaming()}else $&&je&&(je.style.display="none",me&&We());if(((rr=t.attachments)==null?void 0:rr.enabled)===!0)if(!st||!pe){let x=(ir=t.attachments)!=null?ir:{},Oe=(lr=((ar=t.sendButton)!=null?ar:{}).size)!=null?lr:"40px";ot||(ot=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ot.style.display="none",lt.insertBefore(ot,X)),ge||(ge=document.createElement("input"),ge.type="file",ge.accept=((dr=x.allowedTypes)!=null?dr:Jt).join(","),ge.multiple=((cr=x.maxFiles)!=null?cr:4)>1,ge.style.display="none",ge.setAttribute("aria-label","Attach files"),lt.insertBefore(ge,X)),st=p("div","tvw-send-button-wrapper"),pe=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),pe.type="button",pe.setAttribute("aria-label",(ur=x.buttonTooltipText)!=null?ur:"Attach file");let ne=(pr=x.buttonIconName)!=null?pr:"paperclip",ve=Oe,gt=parseFloat(ve)||40,at=Math.round(gt*.6);pe.style.width=ve,pe.style.height=ve,pe.style.minWidth=ve,pe.style.minHeight=ve,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.style.backgroundColor="transparent",pe.style.color="var(--cw-primary, #111827)",pe.style.border="none",pe.style.borderRadius="6px",pe.style.transition="background-color 0.15s ease",pe.addEventListener("mouseenter",()=>{pe.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),pe.addEventListener("mouseleave",()=>{pe.style.backgroundColor="transparent"});let Mt=oe(ne,at,"currentColor",1.5);Mt?pe.appendChild(Mt):pe.textContent="\u{1F4CE}",pe.addEventListener("click",Et=>{Et.preventDefault(),ge==null||ge.click()}),st.appendChild(pe);let ht=(gr=x.buttonTooltipText)!=null?gr:"Attach file",Ne=p("div","tvw-send-button-tooltip");Ne.textContent=ht,st.appendChild(Ne),Pt.append(st),!Ae&&ge&&ot&&(Ae=Qt.fromConfig(x),Ae.setPreviewsContainer(ot),ge.addEventListener("change",async()=>{Ae&&(ge!=null&&ge.files)&&(await Ae.handleFileSelect(ge.files),ge.value="")}))}else{st.style.display="";let x=(mr=t.attachments)!=null?mr:{};ge&&(ge.accept=((hr=x.allowedTypes)!=null?hr:Jt).join(","),ge.multiple=((fr=x.maxFiles)!=null?fr:4)>1),Ae&&Ae.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else st&&(st.style.display="none"),Ae&&Ae.clearAttachments();let ze=(wr=t.sendButton)!=null?wr:{},$n=(yr=ze.useIcon)!=null?yr:!1,wn=(vr=ze.iconText)!=null?vr:"\u2191",yn=ze.iconName,zt=(br=ze.tooltipText)!=null?br:"Send message",vn=(Cr=ze.showTooltip)!=null?Cr:!1,bn=(xr=ze.size)!=null?xr:"40px",On=ze.backgroundColor,Rt=ze.textColor;if($n){if(D.style.width=bn,D.style.height=bn,D.style.minWidth=bn,D.style.minHeight=bn,D.style.fontSize="18px",D.style.lineHeight="1",D.innerHTML="",yn){let x=parseFloat(bn)||24,ue=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",Oe=oe(yn,x,ue,2);Oe?(D.appendChild(Oe),D.style.color=ue):(D.textContent=wn,Rt?D.style.color=Rt:D.classList.add("tvw-text-white"))}else D.textContent=wn,Rt?D.style.color=Rt: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",On?(D.style.backgroundColor=On,D.classList.remove("tvw-bg-cw-primary")):D.classList.add("tvw-bg-cw-primary")}else D.textContent=(Ar=(Sr=t.copy)==null?void 0:Sr.sendButtonLabel)!=null?Ar:"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",On?(D.style.backgroundColor=On,D.classList.remove("tvw-bg-cw-accent")):D.classList.add("tvw-bg-cw-accent"),Rt?D.style.color=Rt:D.classList.add("tvw-text-white");ze.borderWidth?(D.style.borderWidth=ze.borderWidth,D.style.borderStyle="solid"):(D.style.borderWidth="",D.style.borderStyle=""),ze.borderColor?D.style.borderColor=ze.borderColor:D.style.borderColor="",ze.paddingX?(D.style.paddingLeft=ze.paddingX,D.style.paddingRight=ze.paddingX):(D.style.paddingLeft="",D.style.paddingRight=""),ze.paddingY?(D.style.paddingTop=ze.paddingY,D.style.paddingBottom=ze.paddingY):(D.style.paddingTop="",D.style.paddingBottom="");let Cn=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip");if(vn&&zt)if(Cn)Cn.textContent=zt,Cn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=zt,nt==null||nt.insertBefore(x,D)}else Cn&&(Cn.style.display="none");let xn=(Tr=t.statusIndicator)!=null?Tr:{},xi=(Mr=xn.visible)!=null?Mr:!0;if(dt.style.display=xi?"":"none",H){let x=H.getStatus(),ue=Oe=>{var ne,ve,gt,at;return Oe==="idle"?(ne=xn.idleText)!=null?ne:mt.idle:Oe==="connecting"?(ve=xn.connectingText)!=null?ve:mt.connecting:Oe==="connected"?(gt=xn.connectedText)!=null?gt:mt.connected:Oe==="error"?(at=xn.errorText)!=null?at:mt.error:mt[Oe]};dt.textContent=ue(x)}},open(){h&&E(!0,"api")},close(){h&&E(!1,"api")},toggle(){h&&E(!R,"api")},clearChat(){H.clearMessages();try{localStorage.removeItem(pn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${pn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==pn)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(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!X||H.isStreaming()?!1:(!R&&h&&E(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let c=(l==null?void 0:l.trim())||X.value.trim();return c?(!R&&h&&E(!0,"system"),X.value="",X.style.height="auto",H.sendMessage(c),!0):!1},startVoiceRecognition(){return me||H.isStreaming()||!Ie()?!1:(!R&&h&&E(!0,"system"),Le.manuallyDeactivated=!1,jt(),_e("user"),!0)},stopVoiceRecognition(){return me?(Le.manuallyDeactivated=!0,jt(),We("user"),!0):!1},injectMessage(l){return!R&&h&&E(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){return!R&&h&&E(!0,"system"),H.injectAssistantMessage(l)},injectUserMessage(l){return!R&&h&&E(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!R&&h&&E(!0,"system"),H.injectSystemMessage(l)},injectTestMessage(l){!R&&h&&E(!0,"system"),H.injectTestEvent(l)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&R},isVoiceActive(){return Le.active},getState(){return{open:h&&R,launcherEnabled:h,voiceActive:Le.active,streaming:H.isStreaming()}},showCSATFeedback(l){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=os({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.submitCSATFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!R&&h&&E(!0,"system");let c=V.querySelector(".tvw-feedback-container");c&&c.remove();let A=rs({onSubmit:async(P,b)=>{var Q;H.isClientTokenMode()&&await H.submitNPSFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});V.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return H.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return H.submitNPSFeedback(l,c)},destroy(){ke.forEach(l=>l()),z.remove(),le==null||le.destroy(),he==null||he.remove(),rt&&q.removeEventListener("click",rt)}};if((((Gs=o==null?void 0:o.debugTools)!=null?Gs:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:Dt,getMessages:Dt.getMessages,getStatus:Dt.getStatus,getMetadata:Dt.getPersistentMetadata,updateMetadata:Dt.updatePersistentMetadata,clearHistory:()=>Dt.clearChat(),setVoiceActive:A=>A?Dt.startVoiceRecognition():Dt.stopVoiceRecognition()};window.AgentWidgetBrowser=c,ke.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return Dt};var Ls={},sa=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},oa=()=>{try{if(typeof Ls!="undefined"&&Ls.url)return new URL("../widget.css",Ls.url).href}catch{}return null},mi=e=>{let n=oa(),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)}},Ps=e=>{var u,f,g,m;let n=sa(e.target),o=document.createElement("div");o.className="persona-host";let t=(g=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?g:!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),mi(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),mi(o);let a=is(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var hi={name:"@runtypelabs/persona",version:"1.38.1",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 tn=hi.version;function Ut(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ia(e){if(e)return{getHeaders:Ut(e.getHeaders),onFeedback:Ut(e.onFeedback),onCopy:Ut(e.onCopy),requestMiddleware:Ut(e.requestMiddleware),actionHandlers:Ut(e.actionHandlers),actionParsers:Ut(e.actionParsers),postprocessMessage:Ut(e.postprocessMessage),contextProviders:Ut(e.contextProviders),streamParser:Ut(e.streamParser)}}var fi=`({ text, message }: any) => {
|
|
60
|
+
`}if(!Se){let Jt="max-height: -moz-available !important; max-height: stretch !important;",Sn=l?"":"padding-top: 1.25em !important;";J.style.cssText+=Jt+Sn}};Pt(),Zn(e,t);let Fe=[],st=null,kt=()=>{st&&(st(),st=null),t.colorScheme==="auto"&&(st=ei(()=>{Zn(e,t)}))};kt(),Fe.push(()=>{st&&(st(),st=null)});let mt=di(Ct),ht=null,P,te=!1,we=!0,Ge=0,St=0,ze=null,ft=!1,Lt=0,Ht=!1,fn=125,Kt=2e3,Fn=5,wn=50,sn=new Map,We={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},yn=(Zs=(Qs=t.voiceRecognition)==null?void 0:Qs.autoResume)!=null?Zs:!1,vn=l=>{s.emit("voice:state",{active:We.active,source:l,timestamp:Date.now()})},Dt=()=>{f(l=>({...l,voiceState:{active:We.active,timestamp:Date.now(),manuallyDeactivated:We.manuallyDeactivated}}))},$n=()=>{var H,b;if(((H=t.voiceRecognition)==null?void 0:H.enabled)===!1)return;let l=Hs(a.voiceState),c=!!l.active,T=Number((b=l.timestamp)!=null?b:0);We.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-T<ra&&setTimeout(()=>{We.active||(We.manuallyDeactivated=!1,be("restore"))},1e3)},B=()=>P?hi(P.getMessages()).filter(l=>!l.__skipPersist):[];function le(l){if(!(i!=null&&i.save))return;let T={messages:l?hi(l):P?B():[],metadata:a};try{let H=i.save(T);H instanceof Promise&&H.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",b)})}catch(H){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)}}let he=(l=!1)=>{if(!we)return;let c=Date.now();ft&&c<Lt&&!l||(ft&&c>=Lt&&(ft=!1),!(!l&&!te)&&(c-St<fn||(St=c,ze&&cancelAnimationFrame(ze),ze=requestAnimationFrame(()=>{ft||!we||(Ht=!0,de.scrollTop=de.scrollHeight,Ge=de.scrollTop,requestAnimationFrame(()=>{Ht=!1}),ze=null)}))))},Ee=null,Ze=()=>J.querySelector("#persona-scroll-container")||de,ot=(l,c=500)=>{let T=l.scrollTop,H=l.clientHeight,b=l.scrollHeight,X=b-T;if(T+H>=b-2||Math.abs(X)<5)return;Ee!==null&&(cancelAnimationFrame(Ee),Ee=null);let W=performance.now(),K=Ce=>1-Math.pow(1-Ce,3),G=Ce=>{let $=l.scrollHeight;$!==b&&(b=$,X=b-T);let je=Ce-W,Se=Math.min(je/c,1),ue=K(Se),Je=T+X*ue;l.scrollTop=Je,Se<1?Ee=requestAnimationFrame(G):(l.scrollTop=l.scrollHeight,Ee=null)};Ee=requestAnimationFrame(G)},$e=l=>{let c=new Map;l.forEach(T=>{let H=sn.get(T.id);c.set(T.id,{streaming:T.streaming,role:T.role}),!H&&T.role==="assistant"&&s.emit("assistant:message",T),T.role==="assistant"&&(H!=null&&H.streaming)&&T.streaming===!1&&s.emit("assistant:complete",T)}),sn.clear(),c.forEach((T,H)=>{sn.set(H,T)})},wt=(l,c,T)=>{let H=document.createElement("div");c.forEach(W=>{var je,Se;let K=null,G=r.find(ue=>!!(W.variant==="reasoning"&&ue.renderReasoning||W.variant==="tool"&&ue.renderToolCall||!W.variant&&ue.renderMessage)),Ce=(je=t.layout)==null?void 0:je.messages;if(G)if(W.variant==="reasoning"&&W.reasoning&&G.renderReasoning){if(!z)return;K=G.renderReasoning({message:W,defaultRenderer:()=>As(W),config:t})}else if(W.variant==="tool"&&W.toolCall&&G.renderToolCall){if(!_)return;K=G.renderToolCall({message:W,defaultRenderer:()=>Ts(W,t),config:t})}else G.renderMessage&&(K=G.renderMessage({message:W,defaultRenderer:()=>{let ue=cn(W,T,Ce,t.messageActions,ne);return W.role!=="user"&&Ms(ue,W,t,P),ue},config:t}));if(!K&&W.role==="assistant"&&!W.variant&&t.enableComponentStreaming!==!1&&rs(W)){let Je=is(W);if(Je){let Ye=os(Je,{config:t,message:W,transform:T});if(Ye){let rt=document.createElement("div");if(rt.className=["vanilla-message-bubble","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-p-4"].join(" "),rt.id=`bubble-${W.id}`,rt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=T({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),rt.appendChild(Tt)}rt.appendChild(Ye),K=rt}}}if(!K)if(W.variant==="reasoning"&&W.reasoning){if(!z)return;K=As(W)}else if(W.variant==="tool"&&W.toolCall){if(!_)return;K=Ts(W,t)}else{let ue=(Se=t.layout)==null?void 0:Se.messages;ue!=null&&ue.renderUserMessage&&W.role==="user"?K=ue.renderUserMessage({message:W,config:t,streaming:!!W.streaming}):ue!=null&&ue.renderAssistantMessage&&W.role==="assistant"?K=ue.renderAssistantMessage({message:W,config:t,streaming:!!W.streaming}):K=cn(W,T,ue,t.messageActions,ne),W.role!=="user"&&K&&Ms(K,W,t,P)}let $=document.createElement("div");$.className="tvw-flex",$.id=`wrapper-${W.id}`,$.setAttribute("data-wrapper-id",W.id),W.role==="user"&&$.classList.add("tvw-justify-end"),$.appendChild(K),H.appendChild($)});let b=c.some(W=>W.role==="assistant"&&W.streaming),X=c[c.length-1],ce=(X==null?void 0:X.role)==="assistant"&&!X.streaming;if(te&&c.some(W=>W.role==="user")&&!b&&!ce){let W=Hn(),K=document.createElement("div");K.className=["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "),K.setAttribute("data-typing-indicator","true"),K.appendChild(W);let G=document.createElement("div");G.className="tvw-flex",G.id="wrapper-typing-indicator",G.setAttribute("data-wrapper-id","typing-indicator"),G.appendChild(K),H.appendChild(G)}ni(l,H),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ze();ot(W)})})},se=()=>{h&&(I?(J.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-95","tvw-opacity-0"),L.classList.add("tvw-scale-100","tvw-opacity-100"),Oe?Oe.element.style.display="none":Ne&&(Ne.style.display="none")):(J.classList.add("tvw-pointer-events-none","tvw-opacity-0"),L.classList.remove("tvw-scale-100","tvw-opacity-100"),L.classList.add("tvw-scale-95","tvw-opacity-0"),Oe?Oe.element.style.display="":Ne&&(Ne.style.display="")))},S=(l,c="user")=>{if(!h||I===l)return;let T=I;I=l,se(),I&&(bn(),he(!0));let H={open:I,source:c,timestamp:Date.now()};I&&!T?s.emit("widget:opened",H):!I&&T&&s.emit("widget:closed",H),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()})},E=l=>{j.disabled=l,F&&(F.disabled=l),mt.buttons.forEach(c=>{c.disabled=l})},Y=()=>{var b,X,ce,W,K,G,Ce,$,je,Se,ue,Je,Ye,rt;Rt.textContent=(X=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?X:"Hello \u{1F44B}",Ft.textContent=(W=(ce=t.copy)==null?void 0:ce.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",ee.placeholder=(G=(K=t.copy)==null?void 0:K.inputPlaceholder)!=null?G:"How can I help...",(($=(Ce=t.sendButton)==null?void 0:Ce.useIcon)!=null?$:!1)||(j.textContent=(Se=(je=t.copy)==null?void 0:je.sendButtonLabel)!=null?Se:"Send");let c=(Je=(ue=t.theme)==null?void 0:ue.inputFontFamily)!=null?Je:"sans-serif",T=(rt=(Ye=t.theme)==null?void 0:Ye.inputFontWeight)!=null?rt:"400",H=Tt=>{switch(Tt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ee.style.fontFamily=H(c),ee.style.fontWeight=T};t.clientToken&&(t={...t,getStoredSessionId:()=>{let l=a.session_id;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(c=>({...c,session_id:l}))}}),P=new an(t,{onMessagesChanged(l){wt(qe,l,k),P&&(l.some(H=>H.role==="user")?mt.render([],P,ee,l):mt.render(t.suggestionChips,P,ee,l,t.suggestionChipsConfig)),he(!te),$e(l);let c=[...l].reverse().find(T=>T.role==="user");We.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),le(l)},onStatusChanged(l){var H;let c=(H=t.statusIndicator)!=null?H:{},T=b=>{var X,ce,W,K;return b==="idle"?(X=c.idleText)!=null?X:pt.idle:b==="connecting"?(ce=c.connectingText)!=null?ce:pt.connecting:b==="connected"?(W=c.connectedText)!=null?W:pt.connected:b==="error"?(K=c.errorText)!=null?K:pt.error:pt[b]};vt.textContent=T(l)},onStreamingChanged(l){te=l,E(l),P&&wt(qe,P.getMessages(),k),l||he(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Hs(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&P.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Pe=l=>{var b;l.preventDefault();let c=ee.value.trim(),T=(b=U==null?void 0:U.hasAttachments())!=null?b:!1;if(!c&&!T)return;let H;T&&(H=[],H.push(...U.getContentParts()),c&&H.push(Xn(c))),ee.value="",ee.style.height="auto",P.sendMessage(c,{contentParts:H}),T&&U.clearAttachments()},He=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),j.click())},ke=null,ye=!1,Ie=null,Le=null,ve=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,be=(l="user")=>{var X,ce,W,K;if(ye||P.isStreaming())return;let c=ve();if(!c)return;ke=new c;let H=(ce=((X=t.voiceRecognition)!=null?X:{}).pauseDuration)!=null?ce:2e3;ke.continuous=!0,ke.interimResults=!0,ke.lang="en-US";let b=ee.value;ke.onresult=G=>{let Ce="",$="";for(let Se=0;Se<G.results.length;Se++){let ue=G.results[Se],Je=ue[0].transcript;ue.isFinal?Ce+=Je+" ":$=Je}let je=b+Ce+$;ee.value=je,Ie&&clearTimeout(Ie),(Ce||$)&&(Ie=window.setTimeout(()=>{let Se=ee.value.trim();Se&&ke&&ye&&(Te(),ee.value="",ee.style.height="auto",P.sendMessage(Se,{viaVoice:!0}))},H))},ke.onerror=G=>{G.error!=="no-speech"&&Te()},ke.onend=()=>{if(ye){let G=ee.value.trim();G&&G!==b.trim()&&(ee.value="",ee.style.height="auto",P.sendMessage(G,{viaVoice:!0})),Te()}};try{if(ke.start(),ye=!0,We.active=!0,l!=="system"&&(We.manuallyDeactivated=!1),vn(l),Dt(),F){Le={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let G=(W=t.voiceRecognition)!=null?W:{},Ce=(K=G.recordingBackgroundColor)!=null?K:"#ef4444",$=G.recordingIconColor,je=G.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=Ce,$){F.style.color=$;let Se=F.querySelector("svg");Se&&Se.setAttribute("stroke",$)}je&&(F.style.borderColor=je),F.setAttribute("aria-label","Stop voice recognition")}}catch{Te("system")}},Te=(l="user")=>{if(ye){if(ye=!1,Ie&&(clearTimeout(Ie),Ie=null),ke){try{ke.stop()}catch{}ke=null}if(We.active=!1,vn(l),Dt(),F){if(F.classList.remove("tvw-voice-recording"),Le){F.style.backgroundColor=Le.backgroundColor,F.style.color=Le.color,F.style.borderColor=Le.borderColor;let c=F.querySelector("svg");c&&c.setAttribute("stroke",Le.color||"currentColor"),Le=null}F.setAttribute("aria-label","Start voice recognition")}}},Ae=(l,c)=>{var Je,Ye,rt,Tt,Q,Me,Vt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let H=g("div","tvw-send-button-wrapper"),b=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");b.type="button",b.setAttribute("aria-label","Start voice recognition");let X=(Je=l==null?void 0:l.iconName)!=null?Je:"mic",ce=(Ye=c==null?void 0:c.size)!=null?Ye:"40px",W=(rt=l==null?void 0:l.iconSize)!=null?rt:ce,K=parseFloat(W)||24,G=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,Ce=(Q=l==null?void 0:l.iconColor)!=null?Q:c==null?void 0:c.textColor;b.style.width=W,b.style.height=W,b.style.minWidth=W,b.style.minHeight=W,b.style.fontSize="18px",b.style.lineHeight="1";let $=Ce||"currentColor",je=ie(X,K,$,1.5);je?(b.appendChild(je),b.style.color=$):(b.textContent="\u{1F3A4}",b.style.color=$),G?b.style.backgroundColor=G:b.classList.add("tvw-bg-cw-primary"),Ce?b.style.color=Ce:!Ce&&!(c!=null&&c.textColor)&&b.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(b.style.borderWidth=l.borderWidth,b.style.borderStyle="solid"),l!=null&&l.borderColor&&(b.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(b.style.paddingLeft=l.paddingX,b.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(b.style.paddingTop=l.paddingY,b.style.paddingBottom=l.paddingY),H.appendChild(b);let Se=(Me=l==null?void 0:l.tooltipText)!=null?Me:"Start voice recognition";if(((Vt=l==null?void 0:l.showTooltip)!=null?Vt:!1)&&Se){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=Se,H.appendChild(Xt)}return{micButton:b,micButtonWrapper:H}},Qe=()=>{if(ye){let l=ee.value.trim();We.manuallyDeactivated=!0,Dt(),Te("user"),l&&(ee.value="",ee.style.height="auto",P.sendMessage(l))}else We.manuallyDeactivated=!1,Dt(),be("user")};F&&(F.addEventListener("click",Qe),Fe.push(()=>{Te("system"),F&&F.removeEventListener("click",Qe)}));let At=s.on("assistant:complete",()=>{yn&&(We.active||We.manuallyDeactivated||yn==="assistant"&&!We.lastUserMessageWasVoice||setTimeout(()=>{!We.active&&!We.manuallyDeactivated&&be("auto")},600))});Fe.push(At);let Bt=s.on("action:resubmit",()=>{setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)});Fe.push(Bt);let on=()=>{S(!I,"user")},Oe=null,Ne=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});c&&(Ne=c)}Ne||(Oe=Pn(t,on))}Oe?e.appendChild(Oe.element):Ne&&e.appendChild(Ne),se(),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming()),he(!0),$n();let bn=()=>{var T,H,b,X,ce,W,K,G;let l=(H=(T=t.launcher)==null?void 0:T.sidebarMode)!=null?H:!1,c=l||((X=(b=t.launcher)==null?void 0:b.fullHeight)!=null?X:!1);if(!h){L.style.height="",L.style.width="";return}if(!l){let Ce=(W=(ce=t==null?void 0:t.launcher)==null?void 0:ce.width)!=null?W:t==null?void 0:t.launcherWidth,$=Ce!=null?Ce:"min(400px, calc(100vw - 24px))";L.style.width=$,L.style.maxWidth=$}if(!c){let Ce=window.innerHeight,$=64,je=(G=(K=t.launcher)==null?void 0:K.heightOffset)!=null?G:0,Se=Math.max(200,Ce-$),ue=Math.min(640,Se),Je=Math.max(200,ue-je);L.style.height=`${Je}px`}};bn(),window.addEventListener("resize",bn),Fe.push(()=>window.removeEventListener("resize",bn)),Ge=de.scrollTop;let Fs=()=>{let l=de.scrollTop,c=de.scrollHeight,T=de.clientHeight,H=c-l-T,b=Math.abs(l-Ge);if(Ge=l,!Ht&&!(b<=Fn)){if(!we&&H<wn){ft=!1,we=!0;return}we&&H>wn&&(ft=!0,Lt=Date.now()+Kt,we=!1)}};de.addEventListener("scroll",Fs,{passive:!0}),Fe.push(()=>de.removeEventListener("scroll",Fs)),Fe.push(()=>{ze&&cancelAnimationFrame(ze)});let $s=()=>{D&&(ht&&(D.removeEventListener("click",ht),ht=null),h?(D.style.display="",ht=()=>{I=!1,se()},D.addEventListener("click",ht)):D.style.display="none")};$s(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(T){console.error("[AgentWidget] Failed to clear default localStorage:",T)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(T){console.error("[AgentWidget] Failed to clear custom localStorage:",T)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let T=i.clear();T instanceof Promise&&T.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",H)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)}a={},w.syncFromMetadata()})})(),xt.addEventListener("submit",Pe),ee.addEventListener("keydown",He),Fe.push(()=>{xt.removeEventListener("submit",Pe),ee.removeEventListener("keydown",He)}),Fe.push(()=>{P.cancel()}),Oe?Fe.push(()=>{Oe==null||Oe.destroy()}):Ne&&Fe.push(()=>{Ne==null||Ne.remove()});let _t={update(l){var to,no,so,oo,ro,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,yo,vo,bo,Co,xo,So,Ao,To,Mo,Eo,Wo,ko,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,Oo,No,jo,Do,_o,qo,Uo,zo,Jo,Yo,Ko,Vo,Xo,Go,Qo,Zo,er,tr,nr,sr,or,rr,ir,ar,lr,dr,cr,ur,pr,gr,mr,hr,fr,wr,yr,vr,br,Cr,xr,Sr,Ar,Tr,Mr,Er,Wr,kr;let c=t.toolCall,T=t.colorScheme;t={...t,...l},Pt(),Zn(e,t),t.colorScheme!==T&&kt();let H=Bn.getForInstance(t.plugins);if(r.length=0,r.push(...H),h=(no=(to=t.launcher)==null?void 0:to.enabled)!=null?no:!0,R=(oo=(so=t.launcher)==null?void 0:so.autoExpand)!=null?oo:!1,z=(io=(ro=t.features)==null?void 0:ro.showReasoning)!=null?io:!0,_=(lo=(ao=t.features)==null?void 0:ao.showToolCalls)!=null?lo:!0,((co=t.launcher)==null?void 0:co.enabled)===!1&&Oe&&(Oe.destroy(),Oe=null),((uo=t.launcher)==null?void 0:uo.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((po=t.launcher)==null?void 0:po.enabled)!==!1&&!Oe&&!Ne){let x=r.find(pe=>pe.renderLauncher);if(x!=null&&x.renderLauncher){let pe=x.renderLauncher({config:t,defaultRenderer:()=>Pn(t,on).element,onToggle:on});pe&&(Ne=pe,e.appendChild(Ne))}Ne||(Oe=Pn(t,on),e.appendChild(Oe.element))}Oe&&Oe.update(t),lt&&((go=t.launcher)==null?void 0:go.title)!==void 0&&(lt.textContent=t.launcher.title),dt&&((mo=t.launcher)==null?void 0:mo.subtitle)!==void 0&&(dt.textContent=t.launcher.subtitle);let b=(ho=t.layout)==null?void 0:ho.header;if((b==null?void 0:b.layout)!==A&&Ve){let x=b?ln(t,b,{showClose:h,onClose:()=>S(!1,"user")}):Ut({config:t,showClose:h,onClose:()=>S(!1,"user")});Ve.replaceWith(x.header),Ve=x.header,fe=x.iconHolder,lt=x.headerTitle,dt=x.headerSubtitle,D=x.closeButton,A=b==null?void 0:b.layout}else if(b&&(fe&&(fe.style.display=b.showIcon===!1?"none":""),lt&&(lt.style.display=b.showTitle===!1?"none":""),dt&&(dt.style.display=b.showSubtitle===!1?"none":""),D&&(D.style.display=b.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){q.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:pe}=q;pe&&!pe.classList.contains("tvw-absolute")&&(x?pe.classList.remove("tvw-ml-auto"):pe.classList.add("tvw-ml-auto"))}}let ce=((fo=t.layout)==null?void 0:fo.showHeader)!==!1;Ve&&(Ve.style.display=ce?"":"none");let W=((wo=t.layout)==null?void 0:wo.showFooter)!==!1;ct&&(ct.style.display=W?"":"none"),h!==y?h?S(R,"auto"):(I=!0,se()):R!==M&&S(R,"auto"),M=R,y=h,bn(),$s(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&P&&wt(qe,P.getMessages(),k);let $=(yo=t.launcher)!=null?yo:{},je=(vo=$.headerIconHidden)!=null?vo:!1,Se=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showIcon,ue=je||Se===!1,Je=$.headerIconName,Ye=(xo=$.headerIconSize)!=null?xo:"48px";if(fe){let x=Z.querySelector(".tvw-border-b-cw-divider"),pe=x==null?void 0:x.querySelector(".tvw-flex-col");if(ue)fe.style.display="none",x&&pe&&!x.contains(pe)&&x.insertBefore(pe,x.firstChild);else{if(fe.style.display="",fe.style.height=Ye,fe.style.width=Ye,x&&pe&&(x.contains(fe)?fe.nextSibling!==pe&&(fe.remove(),x.insertBefore(fe,pe)):x.insertBefore(fe,pe)),Je){let oe=parseFloat(Ye)||24,xe=ie(Je,oe*.6,"#ffffff",2);xe?fe.replaceChildren(xe):fe.textContent=(So=$.agentIconText)!=null?So:"\u{1F4AC}"}else if($.iconUrl){let oe=fe.querySelector("img");if(oe)oe.src=$.iconUrl,oe.style.height=Ye,oe.style.width=Ye;else{let xe=document.createElement("img");xe.src=$.iconUrl,xe.alt="",xe.className="tvw-rounded-xl tvw-object-cover",xe.style.height=Ye,xe.style.width=Ye,fe.replaceChildren(xe)}}else{let oe=fe.querySelector("svg"),xe=fe.querySelector("img");(oe||xe)&&fe.replaceChildren(),fe.textContent=(Ao=$.agentIconText)!=null?Ao:"\u{1F4AC}"}let De=fe.querySelector("img");De&&(De.style.height=Ye,De.style.width=Ye)}}let rt=(Mo=(To=t.layout)==null?void 0:To.header)==null?void 0:Mo.showTitle,Tt=(Wo=(Eo=t.layout)==null?void 0:Eo.header)==null?void 0:Wo.showSubtitle;if(lt&&(lt.style.display=rt===!1?"none":""),dt&&(dt.style.display=Tt===!1?"none":""),D){((Lo=(ko=t.layout)==null?void 0:ko.header)==null?void 0:Lo.showCloseButton)===!1?D.style.display="none":D.style.display="";let pe=(Po=$.closeButtonSize)!=null?Po:"32px",De=(Ho=$.closeButtonPlacement)!=null?Ho:"inline";D.style.height=pe,D.style.width=pe;let{closeButtonWrapper:oe}=q,xe=De==="top-right",ut=oe==null?void 0:oe.classList.contains("tvw-absolute");if(oe&&xe!==ut)if(oe.remove(),xe)oe.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Z.style.position="relative",Z.appendChild(oe);else{let ae=(Io=(Bo=$.clearChat)==null?void 0:Bo.placement)!=null?Io:"inline",et=(Fo=(Ro=$.clearChat)==null?void 0:Ro.enabled)!=null?Fo:!0;oe.className=et&&ae==="inline"?"":"tvw-ml-auto";let bt=Z.querySelector(".tvw-border-b-cw-divider");bt&&bt.appendChild(oe)}if($.closeButtonColor?(D.style.color=$.closeButtonColor,D.classList.remove("tvw-text-cw-muted")):(D.style.color="",D.classList.add("tvw-text-cw-muted")),$.closeButtonBackgroundColor?(D.style.backgroundColor=$.closeButtonBackgroundColor,D.classList.remove("hover:tvw-bg-gray-100")):(D.style.backgroundColor="",D.classList.add("hover:tvw-bg-gray-100")),$.closeButtonBorderWidth||$.closeButtonBorderColor){let ae=$.closeButtonBorderWidth||"0px",et=$.closeButtonBorderColor||"transparent";D.style.border=`${ae} solid ${et}`,D.classList.remove("tvw-border-none")}else D.style.border="",D.classList.add("tvw-border-none");$.closeButtonBorderRadius?(D.style.borderRadius=$.closeButtonBorderRadius,D.classList.remove("tvw-rounded-full")):(D.style.borderRadius="",D.classList.add("tvw-rounded-full")),$.closeButtonPaddingX?(D.style.paddingLeft=$.closeButtonPaddingX,D.style.paddingRight=$.closeButtonPaddingX):(D.style.paddingLeft="",D.style.paddingRight=""),$.closeButtonPaddingY?(D.style.paddingTop=$.closeButtonPaddingY,D.style.paddingBottom=$.closeButtonPaddingY):(D.style.paddingTop="",D.style.paddingBottom="");let it=($o=$.closeButtonIconName)!=null?$o:"x",Mt=(Oo=$.closeButtonIconText)!=null?Oo:"\xD7";D.innerHTML="";let yt=ie(it,"20px",$.closeButtonColor||"",2);yt?D.appendChild(yt):D.textContent=Mt;let _e=(No=$.closeButtonTooltipText)!=null?No:"Close chat",Et=(jo=$.closeButtonShowTooltip)!=null?jo:!0;if(D.setAttribute("aria-label",_e),oe&&(oe._cleanupTooltip&&(oe._cleanupTooltip(),delete oe._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!D)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=D.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};oe.addEventListener("mouseenter",et),oe.addEventListener("mouseleave",bt),D.addEventListener("focus",et),D.addEventListener("blur",bt),oe._cleanupTooltip=()=>{bt(),oe&&(oe.removeEventListener("mouseenter",et),oe.removeEventListener("mouseleave",bt)),D&&(D.removeEventListener("focus",et),D.removeEventListener("blur",bt))}}}let{clearChatButton:Q,clearChatButtonWrapper:Me}=q;if(Q){let x=(Do=$.clearChat)!=null?Do:{},pe=(_o=x.enabled)!=null?_o:!0,De=(Uo=(qo=t.layout)==null?void 0:qo.header)==null?void 0:Uo.showClearChat,oe=De!==void 0?De:pe,xe=(zo=x.placement)!=null?zo:"inline";if(Me){Me.style.display=oe?"":"none";let{closeButtonWrapper:ut}=q;ut&&!ut.classList.contains("tvw-absolute")&&(oe?ut.classList.remove("tvw-ml-auto"):ut.classList.add("tvw-ml-auto"));let it=xe==="top-right",Mt=Me.classList.contains("tvw-absolute");if(it!==Mt&&oe){if(Me.remove(),it)Me.className="tvw-absolute tvw-top-4 tvw-z-50",Me.style.right="48px",Z.style.position="relative",Z.appendChild(Me);else{Me.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Me.style.right="";let _e=Z.querySelector(".tvw-border-b-cw-divider"),Et=q.closeButtonWrapper;_e&&Et&&Et.parentElement===_e?_e.insertBefore(Me,Et):_e&&_e.appendChild(Me)}let yt=q.closeButtonWrapper;yt&&!yt.classList.contains("tvw-absolute")&&(it?yt.classList.add("tvw-ml-auto"):yt.classList.remove("tvw-ml-auto"))}}if(oe){let ut=(Jo=x.size)!=null?Jo:"32px";Q.style.height=ut,Q.style.width=ut;let it=(Yo=x.iconName)!=null?Yo:"refresh-cw",Mt=(Ko=x.iconColor)!=null?Ko:"";Q.innerHTML="";let yt=ie(it,"20px",Mt||"",2);if(yt&&Q.appendChild(yt),Mt?(Q.style.color=Mt,Q.classList.remove("tvw-text-cw-muted")):(Q.style.color="",Q.classList.add("tvw-text-cw-muted")),x.backgroundColor?(Q.style.backgroundColor=x.backgroundColor,Q.classList.remove("hover:tvw-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ae=x.borderWidth||"0px",et=x.borderColor||"transparent";Q.style.border=`${ae} solid ${et}`,Q.classList.remove("tvw-border-none")}else Q.style.border="",Q.classList.add("tvw-border-none");x.borderRadius?(Q.style.borderRadius=x.borderRadius,Q.classList.remove("tvw-rounded-full")):(Q.style.borderRadius="",Q.classList.add("tvw-rounded-full")),x.paddingX?(Q.style.paddingLeft=x.paddingX,Q.style.paddingRight=x.paddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),x.paddingY?(Q.style.paddingTop=x.paddingY,Q.style.paddingBottom=x.paddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let _e=(Vo=x.tooltipText)!=null?Vo:"Clear chat",Et=(Xo=x.showTooltip)!=null?Xo:!0;if(Q.setAttribute("aria-label",_e),Me&&(Me._cleanupTooltip&&(Me._cleanupTooltip(),delete Me._cleanupTooltip),Et&&_e)){let ae=null,et=()=>{if(ae||!Q)return;ae=g("div","tvw-clear-chat-tooltip"),ae.textContent=_e;let En=g("div");En.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(En);let Gt=Q.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Gt.left+Gt.width/2}px`,ae.style.top=`${Gt.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},bt=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};Me.addEventListener("mouseenter",et),Me.addEventListener("mouseleave",bt),Q.addEventListener("focus",et),Q.addEventListener("blur",bt),Me._cleanupTooltip=()=>{bt(),Me&&(Me.removeEventListener("mouseenter",et),Me.removeEventListener("mouseleave",bt)),Q&&(Q.removeEventListener("focus",et),Q.removeEventListener("blur",bt))}}}}let Vt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[In],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[tn.message,tn.messageAndClick];w=Rn({parsers:Vt,handlers:Xt,getSessionMetadata:u,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),k=fi(t,w,C),P.updateConfig(t),wt(qe,P.getMessages(),k),mt.render(t.suggestionChips,P,ee,void 0,t.suggestionChipsConfig),Y(),E(P.isStreaming());let On=((Go=t.voiceRecognition)==null?void 0:Go.enabled)===!0,Nn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(On&&Nn)if(!F||!Ue){let x=Ae(t.voiceRecognition,t.sendButton);x&&(F=x.micButton,Ue=x.micButtonWrapper,Ot.insertBefore(Ue,at),F.addEventListener("click",Qe),F.disabled=P.isStreaming())}else{let x=(Qo=t.voiceRecognition)!=null?Qo:{},pe=(Zo=t.sendButton)!=null?Zo:{},De=(er=x.iconName)!=null?er:"mic",oe=(tr=pe.size)!=null?tr:"40px",xe=(nr=x.iconSize)!=null?nr:oe,ut=parseFloat(xe)||24;F.style.width=xe,F.style.height=xe,F.style.minWidth=xe,F.style.minHeight=xe;let it=(or=(sr=x.iconColor)!=null?sr:pe.textColor)!=null?or:"currentColor";F.innerHTML="";let Mt=ie(De,ut,it,2);Mt?F.appendChild(Mt):F.textContent="\u{1F3A4}";let yt=(rr=x.backgroundColor)!=null?rr:pe.backgroundColor;yt?(F.style.backgroundColor=yt,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),it?(F.style.color=it,F.classList.remove("tvw-text-white")):!it&&!pe.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),x.borderWidth?(F.style.borderWidth=x.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),x.borderColor?F.style.borderColor=x.borderColor:F.style.borderColor="",x.paddingX?(F.style.paddingLeft=x.paddingX,F.style.paddingRight=x.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),x.paddingY?(F.style.paddingTop=x.paddingY,F.style.paddingBottom=x.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let _e=Ue==null?void 0:Ue.querySelector(".tvw-send-button-tooltip"),Et=(ir=x.tooltipText)!=null?ir:"Start voice recognition";if(((ar=x.showTooltip)!=null?ar:!1)&&Et)if(_e)_e.textContent=Et,_e.style.display="";else{let et=document.createElement("div");et.className="tvw-send-button-tooltip",et.textContent=Et,Ue==null||Ue.insertBefore(et,F)}else _e&&(_e.style.display="none");Ue.style.display="",F.disabled=P.isStreaming()}else F&&Ue&&(Ue.style.display="none",ye&&Te());if(((lr=t.attachments)==null?void 0:lr.enabled)===!0)if(!tt||!ge){let x=(dr=t.attachments)!=null?dr:{},De=(ur=((cr=t.sendButton)!=null?cr:{}).size)!=null?ur:"40px";nt||(nt=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),nt.style.display="none",xt.insertBefore(nt,ee)),me||(me=document.createElement("input"),me.type="file",me.accept=((pr=x.allowedTypes)!=null?pr:Yt).join(","),me.multiple=((gr=x.maxFiles)!=null?gr:4)>1,me.style.display="none",me.setAttribute("aria-label","Attach files"),xt.insertBefore(me,ee)),tt=g("div","tvw-send-button-wrapper"),ge=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),ge.type="button",ge.setAttribute("aria-label",(mr=x.buttonTooltipText)!=null?mr:"Attach file");let oe=(hr=x.buttonIconName)!=null?hr:"paperclip",xe=De,ut=parseFloat(xe)||40,it=Math.round(ut*.6);ge.style.width=xe,ge.style.height=xe,ge.style.minWidth=xe,ge.style.minHeight=xe,ge.style.fontSize="18px",ge.style.lineHeight="1",ge.style.backgroundColor="transparent",ge.style.color="var(--cw-primary, #111827)",ge.style.border="none",ge.style.borderRadius="6px",ge.style.transition="background-color 0.15s ease",ge.addEventListener("mouseenter",()=>{ge.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),ge.addEventListener("mouseleave",()=>{ge.style.backgroundColor="transparent"});let Mt=ie(oe,it,"currentColor",1.5);Mt?ge.appendChild(Mt):ge.textContent="\u{1F4CE}",ge.addEventListener("click",Et=>{Et.preventDefault(),me==null||me.click()}),tt.appendChild(ge);let yt=(fr=x.buttonTooltipText)!=null?fr:"Attach file",_e=g("div","tvw-send-button-tooltip");_e.textContent=yt,tt.appendChild(_e),$t.append(tt),!U&&me&&nt&&(U=Zt.fromConfig(x),U.setPreviewsContainer(nt),me.addEventListener("change",async()=>{U&&(me!=null&&me.files)&&(await U.handleFileSelect(me.files),me.value="")}))}else{tt.style.display="";let x=(wr=t.attachments)!=null?wr:{};me&&(me.accept=((yr=x.allowedTypes)!=null?yr:Yt).join(","),me.multiple=((vr=x.maxFiles)!=null?vr:4)>1),U&&U.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else tt&&(tt.style.display="none"),U&&U.clearAttachments();let Ke=(br=t.sendButton)!=null?br:{},jn=(Cr=Ke.useIcon)!=null?Cr:!1,Cn=(xr=Ke.iconText)!=null?xr:"\u2191",xn=Ke.iconName,Jt=(Sr=Ke.tooltipText)!=null?Sr:"Send message",Sn=(Ar=Ke.showTooltip)!=null?Ar:!1,An=(Tr=Ke.size)!=null?Tr:"40px",Dn=Ke.backgroundColor,Nt=Ke.textColor;if(jn){if(j.style.width=An,j.style.height=An,j.style.minWidth=An,j.style.minHeight=An,j.style.fontSize="18px",j.style.lineHeight="1",j.innerHTML="",xn){let x=parseFloat(An)||24,pe=Nt&&typeof Nt=="string"&&Nt.trim()?Nt.trim():"currentColor",De=ie(xn,x,pe,2);De?(j.appendChild(De),j.style.color=pe):(j.textContent=Cn,Nt?j.style.color=Nt:j.classList.add("tvw-text-white"))}else j.textContent=Cn,Nt?j.style.color=Nt:j.classList.add("tvw-text-white");j.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-primary")):j.classList.add("tvw-bg-cw-primary")}else j.textContent=(Er=(Mr=t.copy)==null?void 0:Mr.sendButtonLabel)!=null?Er:"Send",j.style.width="",j.style.height="",j.style.minWidth="",j.style.minHeight="",j.style.fontSize="",j.style.lineHeight="",j.className="tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-50 tvw-cursor-pointer",Dn?(j.style.backgroundColor=Dn,j.classList.remove("tvw-bg-cw-accent")):j.classList.add("tvw-bg-cw-accent"),Nt?j.style.color=Nt:j.classList.add("tvw-text-white");Ke.borderWidth?(j.style.borderWidth=Ke.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Ke.borderColor?j.style.borderColor=Ke.borderColor:j.style.borderColor="",Ke.paddingX?(j.style.paddingLeft=Ke.paddingX,j.style.paddingRight=Ke.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Ke.paddingY?(j.style.paddingTop=Ke.paddingY,j.style.paddingBottom=Ke.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Tn=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(Sn&&Jt)if(Tn)Tn.textContent=Jt,Tn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=Jt,at==null||at.insertBefore(x,j)}else Tn&&(Tn.style.display="none");let Mn=(Wr=t.statusIndicator)!=null?Wr:{},Ti=(kr=Mn.visible)!=null?kr:!0;if(vt.style.display=Ti?"":"none",P){let x=P.getStatus(),pe=De=>{var oe,xe,ut,it;return De==="idle"?(oe=Mn.idleText)!=null?oe:pt.idle:De==="connecting"?(xe=Mn.connectingText)!=null?xe:pt.connecting:De==="connected"?(ut=Mn.connectedText)!=null?ut:pt.connected:De==="error"?(it=Mn.errorText)!=null?it:pt.error:pt[De]};vt.textContent=pe(x)}},open(){h&&S(!0,"api")},close(){h&&S(!1,"api")},toggle(){h&&S(!I,"api")},clearChat(){P.clearMessages();try{localStorage.removeItem(hn),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${hn}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==hn)try{localStorage.removeItem(t.clearChatHistoryStorageKey),t.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${t.clearChatHistoryStorageKey}`)}catch(c){console.error("[AgentWidget] Failed to clear custom localStorage:",c)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let c=i.clear();c instanceof Promise&&c.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",c)}a={},w.syncFromMetadata()},setMessage(l){return!ee||P.isStreaming()?!1:(!I&&h&&S(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(P.isStreaming())return!1;let c=(l==null?void 0:l.trim())||ee.value.trim();return c?(!I&&h&&S(!0,"system"),ee.value="",ee.style.height="auto",P.sendMessage(c),!0):!1},startVoiceRecognition(){return ye||P.isStreaming()||!ve()?!1:(!I&&h&&S(!0,"system"),We.manuallyDeactivated=!1,Dt(),be("user"),!0)},stopVoiceRecognition(){return ye?(We.manuallyDeactivated=!0,Dt(),Te("user"),!0):!1},injectMessage(l){return!I&&h&&S(!0,"system"),P.injectMessage(l)},injectAssistantMessage(l){!I&&h&&S(!0,"system");let c=P.injectAssistantMessage(l);return v&&(v=!1,N&&(clearTimeout(N),N=null),setTimeout(()=>{P&&!P.isStreaming()&&P.continueConversation()},100)),c},injectUserMessage(l){return!I&&h&&S(!0,"system"),P.injectUserMessage(l)},injectSystemMessage(l){return!I&&h&&S(!0,"system"),P.injectSystemMessage(l)},injectTestMessage(l){!I&&h&&S(!0,"system"),P.injectTestEvent(l)},getMessages(){return P.getMessages()},getStatus(){return P.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){f(l)},on(l,c){return s.on(l,c)},off(l,c){s.off(l,c)},isOpen(){return h&&I},isVoiceActive(){return We.active},getState(){return{open:h&&I,launcherEnabled:h,voiceActive:We.active,streaming:P.isStreaming()}},showCSATFeedback(l){!I&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=as({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitCSATFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&S(!0,"system");let c=qe.querySelector(".tvw-feedback-container");c&&c.remove();let T=ls({onSubmit:async(H,b)=>{var X;P.isClientTokenMode()&&await P.submitNPSFeedback(H,b),(X=l==null?void 0:l.onSubmit)==null||X.call(l,H,b)},onDismiss:l==null?void 0:l.onDismiss,...l});qe.appendChild(T),T.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return P.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return P.submitNPSFeedback(l,c)},destroy(){Fe.forEach(l=>l()),J.remove(),Oe==null||Oe.destroy(),Ne==null||Ne.remove(),ht&&D.removeEventListener("click",ht)}};if((((eo=o==null?void 0:o.debugTools)!=null?eo:!1)||!!t.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,c={controller:_t,getMessages:_t.getMessages,getStatus:_t.getStatus,getMetadata:_t.getPersistentMetadata,updateMetadata:_t.updatePersistentMetadata,clearHistory:()=>_t.clearChat(),setVoiceActive:T=>T?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,Fe.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return _t};var Bs={},ia=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},aa=()=>{try{if(typeof Bs!="undefined"&&Bs.url)return new URL("../widget.css",Bs.url).href}catch{}return null},wi=e=>{let n=aa(),o=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let t=document.head.querySelector("link[data-persona]");if(!t)return;let r=t.cloneNode(!0);e.insertBefore(r,e.firstChild)};if(e instanceof ShadowRoot)if(n){let t=document.createElement("link");t.rel="stylesheet",t.href=n,t.setAttribute("data-persona","true"),e.insertBefore(t,e.firstChild)}else o();else if(!document.head.querySelector("link[data-persona]")&&n){let r=document.createElement("link");r.rel="stylesheet",r.href=n,r.setAttribute("data-persona","true"),document.head.appendChild(r)}},Is=e=>{var u,f,p,m;let n=ia(e.target),o=document.createElement("div");o.className="persona-host";let t=(p=(f=(u=e.config)==null?void 0:u.launcher)==null?void 0:f.enabled)!=null?p:!0;t||(o.style.height="100%"),n.appendChild(o);let r=e.useShadowDom===!0,s,i;if(r){let w=o.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),wi(w)}else i=o,s=document.createElement("div"),s.id="persona-root",t||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),o.appendChild(s),wi(o);let a=ds(s,e.config,{debugTools:e.debugTools});(m=e.onReady)==null||m.call(e);let d={...a,host:o,destroy(){a.destroy(),o.remove(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}};return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=d),d};var yi={name:"@runtypelabs/persona",version:"1.38.3",description:"Themeable, plugable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var nn=yi.version;function zt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function da(e){if(e)return{getHeaders:zt(e.getHeaders),onFeedback:zt(e.onFeedback),onCopy:zt(e.onCopy),requestMiddleware:zt(e.requestMiddleware),actionHandlers:zt(e.actionHandlers),actionParsers:zt(e.actionParsers),postprocessMessage:zt(e.postprocessMessage),contextProviders:zt(e.contextProviders),streamParser:zt(e.streamParser)}}var vi=`({ text, message }: any) => {
|
|
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
|
+
}`,bi=`function(ctx) {
|
|
74
74
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
75
75
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
76
76
|
var cleanJson = jsonSource
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
84
84
|
} catch (e) { return null; }
|
|
85
85
|
return null;
|
|
86
|
-
}`,
|
|
86
|
+
}`,Ci=`(action: any, context: any) => {
|
|
87
87
|
if (action.type !== 'nav_then_click') return;
|
|
88
88
|
const payload = action.payload || action.raw || {};
|
|
89
89
|
const url = payload?.page;
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
101
101
|
window.location.href = targetUrl;
|
|
102
102
|
return { handled: true, displayText: text };
|
|
103
|
-
}`,
|
|
103
|
+
}`,xi=`function(action, context) {
|
|
104
104
|
if (action.type !== 'nav_then_click') return;
|
|
105
105
|
var payload = action.payload || action.raw || {};
|
|
106
106
|
var url = payload.page;
|
|
@@ -117,24 +117,24 @@
|
|
|
117
117
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
118
118
|
window.location.href = targetUrl;
|
|
119
119
|
return { handled: true, displayText: text };
|
|
120
|
-
}`,
|
|
120
|
+
}`,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
|
+
}`,ua=`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 pa(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(...ls(e," ")),t.push(...ds(e," ",o)),t.push(...cs(e," ")),t.push(...us(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(${aa}),`)),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(` ${fi}`),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(` ${fi}`),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(` ${yi}`),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(` ${yi}`),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
|
|
136
|
-
`)}function
|
|
132
|
+
}`;function pa(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 cs(e){var n,o;return(o=(n=e.parserType)!=null?n:pa(e.streamParser))!=null?o:"plain"}function us(e,n){let o=[];return e.toolCall&&(o.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([t,r])=>{typeof r=="string"&&o.push(`${n} ${t}: "${r}",`)}),o.push(`${n}},`)),o}function ps(e,n,o){let t=[],r=e.messageActions&&Object.entries(e.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(o==null?void 0:o.onFeedback)||(o==null?void 0:o.onCopy);return(r||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},`))}),o!=null&&o.onFeedback&&t.push(`${n} onFeedback: ${o.onFeedback},`),o!=null&&o.onCopy&&t.push(`${n} onCopy: ${o.onCopy},`),t.push(`${n}},`)),t}function gs(e,n){let o=[];if(e.markdown){let t=e.markdown.options&&Object.keys(e.markdown.options).length>0,r=e.markdown.disableDefaultStyles!==void 0;(t||r)&&(o.push(`${n}markdown: {`),t&&(o.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,i])=>{typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`)}),o.push(`${n} },`)),r&&o.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),o.push(`${n}},`))}return o}function ms(e,n){let o=[];if(e.layout){let t=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),r=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(t||r)&&(o.push(`${n}layout: {`),t&&(o.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),r&&(o.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(o.push(`${n} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?o.push(`${n} ${a}: "${d}",`):typeof d=="boolean"&&o.push(`${n} ${a}: ${d},`)}),o.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(o.push(`${n} timestamp: {`),Object.entries(i).forEach(([d,u])=>{d!=="format"&&(typeof u=="string"?o.push(`${n} ${d}: "${u}",`):typeof u=="boolean"&&o.push(`${n} ${d}: ${u},`))}),o.push(`${n} },`)):typeof i=="string"?o.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&o.push(`${n} ${s}: ${i},`))}),o.push(`${n} },`)),o.push(`${n}},`))}return o}function Rs(e,n){let o=[];return e&&(e.getHeaders&&o.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&o.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&o.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&o.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&o.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&o.push(`${n}streamParser: ${e.streamParser},`)),o}function Si(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:da(o.hooks)}:void 0;return n==="esm"?ga(t,r):n==="script-installer"?fa(t):n==="script-advanced"?ya(t,r):n==="react-component"?ma(t,r):n==="react-advanced"?ha(t,r):wa(t,r)}function ga(e,n){let o=n==null?void 0:n.hooks,t=cs(e),r=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}",`),r&&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(...us(e," ")),s.push(...ps(e," ",o)),s.push(...gs(e," ")),s.push(...ms(e," ")),s.push(...Rs(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
133
|
+
`)}function ma(e,n){let o=n==null?void 0:n.hooks,t=cs(e),r=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}",`),r&&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(...us(e," ")),s.push(...ps(e," ",o)),s.push(...gs(e," ")),s.push(...ms(e," ")),s.push(...Rs(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.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 ha(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(...us(e," ")),t.push(...ps(e," ",o)),t.push(...gs(e," ")),t.push(...ms(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(${ca}),`)),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(` ${vi}`),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(` ${vi}`),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(` ${Ci}`),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(` ${Ci}`),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 Ai(e){var r;let n=cs(e),o=n!=="plain",t={};if(e.apiUrl&&(t.apiUrl=e.apiUrl),e.clientToken&&(t.clientToken=e.clientToken),e.flowId&&(t.flowId=e.flowId),o&&(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),((r=e.suggestionChips)==null?void 0:r.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 fa(e){let n=Ai(e),o=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${nn}/dist/install.global.js" data-config='${o}'></script>`}function wa(e,n){let o=n==null?void 0:n.hooks,t=cs(e),r=t!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${nn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${nn}/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}",`),r&&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(...us(e," ")),s.push(...ps(e," ",o)),s.push(...gs(e," ")),s.push(...ms(e," ")),s.push(...Rs(o," ")),e.debug&&s.push(` debug: ${e.debug},`),o!=null&&o.postprocessMessage?s.push(` postprocessMessage: ${o.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
136
|
+
`)}function ya(e,n){let o=n==null?void 0:n.hooks,t=Ai(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
|
|
137
137
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
138
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
139
|
-
`)}var
|
|
138
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${nn}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return o!=null&&o.getHeaders&&(s.push(` widgetConfig.getHeaders = ${o.getHeaders};`),s.push("")),o!=null&&o.contextProviders&&(s.push(` widgetConfig.contextProviders = ${o.contextProviders};`),s.push("")),o!=null&&o.streamParser?s.push(` widgetConfig.streamParser = ${o.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${ua});`),s.push(" };")),s.push(""),o!=null&&o.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${o.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${bi}`),s.push(" ];")),s.push(""),o!=null&&o.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${o.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${xi}`),s.push(" ]);")):(s.push(" // Action handlers for navigation and other actions"),s.push(" widgetConfig.actionHandlers = ["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${xi}`),s.push(" ];")),s.push(""),o!=null&&o.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${o.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),o!=null&&o.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${o.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(o!=null&&o.onFeedback||o!=null&&o.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),o!=null&&o.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${o.onFeedback};`),o!=null&&o.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${o.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
|
|
139
|
+
`)}var va=Is;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,validateImageFile});
|
|
140
140
|
//# sourceMappingURL=index.cjs.map
|