@runtypelabs/persona 1.36.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +1080 -0
  2. package/dist/index.cjs +140 -0
  3. package/dist/index.cjs.map +1 -0
  4. package/dist/index.d.cts +2626 -0
  5. package/dist/index.d.ts +2626 -0
  6. package/dist/index.global.js +1843 -0
  7. package/dist/index.global.js.map +1 -0
  8. package/dist/index.js +140 -0
  9. package/dist/index.js.map +1 -0
  10. package/dist/install.global.js +2 -0
  11. package/dist/install.global.js.map +1 -0
  12. package/dist/widget.css +1627 -0
  13. package/package.json +79 -0
  14. package/src/@types/idiomorph.d.ts +37 -0
  15. package/src/client.test.ts +387 -0
  16. package/src/client.ts +1589 -0
  17. package/src/components/composer-builder.ts +530 -0
  18. package/src/components/feedback.ts +379 -0
  19. package/src/components/forms.ts +170 -0
  20. package/src/components/header-builder.ts +455 -0
  21. package/src/components/header-layouts.ts +303 -0
  22. package/src/components/launcher.ts +193 -0
  23. package/src/components/message-bubble.ts +528 -0
  24. package/src/components/messages.ts +54 -0
  25. package/src/components/panel.ts +204 -0
  26. package/src/components/reasoning-bubble.ts +144 -0
  27. package/src/components/registry.ts +87 -0
  28. package/src/components/suggestions.ts +97 -0
  29. package/src/components/tool-bubble.ts +288 -0
  30. package/src/defaults.ts +321 -0
  31. package/src/index.ts +175 -0
  32. package/src/install.ts +284 -0
  33. package/src/plugins/registry.ts +77 -0
  34. package/src/plugins/types.ts +95 -0
  35. package/src/postprocessors.ts +194 -0
  36. package/src/runtime/init.ts +162 -0
  37. package/src/session.ts +376 -0
  38. package/src/styles/tailwind.css +20 -0
  39. package/src/styles/widget.css +1627 -0
  40. package/src/types.ts +1635 -0
  41. package/src/ui.ts +3341 -0
  42. package/src/utils/actions.ts +227 -0
  43. package/src/utils/attachment-manager.ts +384 -0
  44. package/src/utils/code-generators.test.ts +500 -0
  45. package/src/utils/code-generators.ts +1806 -0
  46. package/src/utils/component-middleware.ts +137 -0
  47. package/src/utils/component-parser.ts +119 -0
  48. package/src/utils/constants.ts +16 -0
  49. package/src/utils/content.ts +306 -0
  50. package/src/utils/dom.ts +25 -0
  51. package/src/utils/events.ts +41 -0
  52. package/src/utils/formatting.test.ts +166 -0
  53. package/src/utils/formatting.ts +470 -0
  54. package/src/utils/icons.ts +92 -0
  55. package/src/utils/message-id.ts +37 -0
  56. package/src/utils/morph.ts +36 -0
  57. package/src/utils/positioning.ts +17 -0
  58. package/src/utils/storage.ts +72 -0
  59. package/src/utils/theme.ts +105 -0
  60. package/src/widget.css +1 -0
  61. package/widget.css +1 -0
package/dist/index.cjs ADDED
@@ -0,0 +1,140 @@
1
+ "use strict";var bi=Object.create;var Rn=Object.defineProperty;var Ci=Object.getOwnPropertyDescriptor;var xi=Object.getOwnPropertyNames;var Si=Object.getPrototypeOf,Ai=Object.prototype.hasOwnProperty;var Ti=(e,n)=>{for(var o in n)Rn(e,o,{get:n[o],enumerable:!0})},Tr=(e,n,o,t)=>{if(n&&typeof n=="object"||typeof n=="function")for(let r of xi(n))!Ai.call(e,r)&&r!==o&&Rn(e,r,{get:()=>n[r],enumerable:!(t=Ci(n,r))||t.enumerable});return e};var Ei=(e,n,o)=>(o=e!=null?bi(Si(e)):{},Tr(n||!e||!e.__esModule?Rn(o,"default",{value:e,enumerable:!0}):o,e)),Mi=e=>Tr(Rn({},"__esModule",{value:!0}),e);var ga={};Ti(ga,{AgentWidgetClient:()=>Gt,AgentWidgetSession:()=>nn,AttachmentManager:()=>Qt,DEFAULT_DARK_THEME:()=>As,DEFAULT_LIGHT_THEME:()=>Ss,DEFAULT_WIDGET_CONFIG:()=>Be,attachHeaderToContainer:()=>Zt,buildComposer:()=>on,buildDefaultHeader:()=>ms,buildExpandedHeader:()=>fs,buildHeader:()=>qt,buildHeaderWithLayout:()=>sn,buildMinimalHeader:()=>hs,componentRegistry:()=>dn,createActionManager:()=>kn,createAgentExperience:()=>os,createBubbleWithLayout:()=>ti,createCSATFeedback:()=>ns,createComponentMiddleware:()=>di,createComponentStreamParser:()=>Qn,createDirectivePostprocessor:()=>Lr,createFlexibleJsonStreamParser:()=>Ir,createImagePart:()=>jr,createJsonStreamParser:()=>_n,createLocalStorageAdapter:()=>Gn,createMarkdownProcessor:()=>xn,createMarkdownProcessorFromConfig:()=>Sn,createMessageActions:()=>ys,createNPSFeedback:()=>ss,createPlainTextParser:()=>On,createRegexJsonParser:()=>Dn,createStandardBubble:()=>rn,createTextPart:()=>Un,createTypingIndicator:()=>Tn,createXmlParser:()=>jn,default:()=>pa,defaultActionHandlers:()=>en,defaultJsonActionParser:()=>Mn,directivePostprocessor:()=>Pr,escapeHtml:()=>Fn,extractComponentDirectiveFromMessage:()=>ts,fileToImagePart:()=>qr,generateAssistantMessageId:()=>zn,generateCodeSnippet:()=>wi,generateMessageId:()=>$r,generateUserMessageId:()=>qn,getDisplayText:()=>Or,getHeaderLayout:()=>ws,getImageParts:()=>_r,hasComponentDirective:()=>es,hasImages:()=>Dr,headerLayouts:()=>Xn,initAgentWidget:()=>Ws,isComponentDirectiveType:()=>li,markdownPostprocessor:()=>us,mergeWithDefaults:()=>Vn,normalizeContent:()=>Nr,pluginRegistry:()=>En,renderComponentDirective:()=>Zn,validateImageFile:()=>zr});module.exports=Mi(ga);var Mr=require("marked"),ki=e=>{if(e)return e},xn=e=>{var r,s;let n=e==null?void 0:e.markedOptions,o=new Mr.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=ki(e==null?void 0:e.renderer);return t&&o.use({renderer:t}),i=>o.parse(i)},Sn=e=>e?xn({markedOptions:e.options,renderer:e.renderer}):xn(),Wi=xn(),us=e=>Wi(e),Fn=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),kr=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Er=e=>`%%FORM_PLACEHOLDER_${e}%%`,Wr=(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=Er(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=Er(n.length);return n.push({token:s,type:r}),s}),o},Lr=e=>{let n=Sn(e);return o=>{let t=[],r=Wr(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="${kr(a)}"></div>`;s=s.replace(d,f)}),s}},Pr=e=>{let n=[],o=Wr(e,n),t=us(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="${kr(s)}"></div>`;t=t.replace(i,d)}),t};var jt=require("partial-json"),$n=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ps=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)}},Li=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`},Hr=e=>e.status==="complete"?Li(e):e.status==="pending"?"Waiting":"",Pi=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 Br=e=>e.status==="complete"?Pi(e):"Using tool...",Hi=()=>{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
+ `).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()=>{}}},Nn=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},On=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Dn=()=>{var n;let e=Hi();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)}},_n=()=>{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,jt.parse)(o,jt.STR|jt.OBJ);r&&typeof r=="object"&&(r.component&&typeof r.component=="string"?e=typeof r.text=="string"?$n(r.text):"":r.type==="init"&&r.form?e="":typeof r.text=="string"&&(e=$n(r.text)))}catch{}return n=o.length,e!==null?{text:e,raw:o}:null},close:()=>{}}},Ir=e=>{let n=null,o=0,r=e||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?$n(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?$n(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,jt.parse)(s,jt.STR|jt.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 Bi="https://api.travrse.ai/v1/dispatch",Rr="https://api.travrse.ai",Fr=e=>!!(e.contentParts&&e.contentParts.length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Ii(e){switch(e){case"json":return _n;case"regex-json":return Dn;case"xml":return jn;case"plain":default:return On}}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:Bi,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(t=n.streamParser)!=null?t:Ii(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$/,""))||Rr;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$/,""))||Rr}/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 p=await this.buildPayload(n.messages),f=p.metadata?Object.fromEntries(Object.entries(p.metadata).filter(([w])=>w!=="session_id")):void 0,m={session_id:d.sessionId,messages:n.messages.filter(Fr).map(w=>{var h,R;return{id:w.id,role:w.role,content:(R=(h=w.contentParts)!=null?h:w.rawContent)!=null?R:w.content}}),...n.assistantMessageId&&{assistant_message_id:n.assistantMessageId},...f&&Object.keys(f).length>0&&{metadata:f},...p.context&&{context:p.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",m);let g=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(m),signal:t.signal});if(!g.ok){let w=await g.json().catch(()=>({error:"Chat request failed"}));if(g.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(g.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(!g.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(g.body,o,n.assistantMessageId)}finally{o({type:"status",status:"idle"})}}catch(d){let p=d instanceof Error?d:new Error(String(d));throw!p.message.includes("Session expired")&&!p.message.includes("Message limit")&&o({type:"error",error:p}),p}}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(Fr).sort((r,s)=>{let i=new Date(r.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(r=>{var s,i;return{role:r.role,content:(i=(s=r.contentParts)!=null?s:r.rawContent)!=null?i: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 Pe,V,_,tt,at,lt,Lt,Ft,q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,kt,ft,ot,$,wt,yt,At,te,ye,Re,vt,Ze,Bt,It,Nt,tn,Ot,We,pn,gn,Dt,Wn,Ln,mn,Yt;let r=n.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,p=()=>a+d++,f=L=>{let le=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Se=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,De=L.tools?L.tools.map(et=>({...et,chunks:et.chunks?[...et.chunks]:void 0})):void 0;return{...L,reasoning:le,toolCall:Se,tools:De}},m=L=>{o({type:"message",message:f(L)})},g=null,w={current:null},h=new Map,R=new Map,M={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}},I=L=>{var le,Se,De,et,Ke;return S((Ke=(et=(De=(Se=(le=L.stepId)!=null?le:L.step_id)!=null?Se:L.step)!=null?De:L.parentId)!=null?et:L.flowStepId)!=null?Ke:L.flow_step_id)},v=L=>{var le,Se,De,et,Ke,Le,W;return S((W=(Le=(Ke=(et=(De=(Se=(le=L.callId)!=null?le:L.call_id)!=null?Se:L.requestId)!=null?De:L.request_id)!=null?et:L.toolCallId)!=null?Ke:L.tool_call_id)!=null?Le:L.stepId)!=null?W:L.step_id)},O=()=>g||(g={id:t!=null?t:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(g),g),C=(L,le)=>{M.lastId=le,L&&M.byStep.set(L,le)},k=(L,le)=>{var Ke;let Se=(Ke=L.reasoningId)!=null?Ke:L.id,De=I(L);if(Se){let Le=String(Se);return C(De,Le),Le}if(De){let Le=M.byStep.get(De);if(Le)return M.lastId=Le,Le}if(M.lastId&&!le)return M.lastId;if(!le)return null;let et=`reason-${p()}`;return C(De,et),et},K=L=>{let le=h.get(L);if(le)return le;let Se={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:L,status:"streaming",chunks:[]}};return h.set(L,Se),m(Se),Se},J=(L,le)=>{y.lastId=le,L&&y.byCall.set(L,le)},U=(L,le)=>{var Ke;let Se=(Ke=L.toolId)!=null?Ke:L.id,De=v(L);if(Se){let Le=String(Se);return J(De,Le),Le}if(De){let Le=y.byCall.get(De);if(Le)return y.lastId=Le,Le}if(y.lastId&&!le)return y.lastId;if(!le)return null;let et=`tool-${p()}`;return J(De,et),et},j=L=>{let le=R.get(L);if(le)return le;let Se={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:L,status:"pending"}};return R.set(L,Se),m(Se),Se},D=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let le=Number(L);if(!Number.isNaN(le)&&Number.isFinite(le))return le;let Se=Date.parse(L);if(!Number.isNaN(Se))return Se}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},H=new Map,X=new Map;for(;;){let{done:L,value:le}=await r.read();if(L)break;i+=s.decode(le,{stream:!0});let Se=i.split(`
5
+
6
+ `);i=(Pe=Se.pop())!=null?Pe:"";for(let De of Se){let et=De.split(`
7
+ `),Ke="message",Le="";for(let oe of et)oe.startsWith("event:")?Ke=oe.replace("event:","").trim():oe.startsWith("data:")&&(Le+=oe.replace("data:","").trim());if(!Le)continue;let W;try{W=JSON.parse(Le)}catch(oe){o({type:"error",error:oe instanceof Error?oe:new Error("Failed to parse chat stream payload")});continue}let bt=Ke!=="message"?Ke:(V=W.type)!=null?V:"message";if(this.parseSSEEvent){w.current=g;let oe=await this.handleCustomSSEEvent(W,o,w,m,p);if(w.current&&!g&&(g=w.current),oe)continue}if(bt==="reason_start"){let oe=(_=k(W,!0))!=null?_:`reason-${p()}`,B=K(oe);B.reasoning=(tt=B.reasoning)!=null?tt:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(lt=B.reasoning.startedAt)!=null?lt:D((at=W.startedAt)!=null?at:W.timestamp),B.reasoning.completedAt=void 0,B.reasoning.durationMs=void 0,B.streaming=!0,B.reasoning.status="streaming",m(B)}else if(bt==="reason_chunk"){let oe=(Ft=(Lt=k(W,!1))!=null?Lt:k(W,!0))!=null?Ft:`reason-${p()}`,B=K(oe);B.reasoning=(q=B.reasoning)!=null?q:{id:oe,status:"streaming",chunks:[]},B.reasoning.startedAt=(dt=B.reasoning.startedAt)!=null?dt:D((we=W.startedAt)!=null?we:W.timestamp);let E=(ut=(Ue=(ct=W.reasoningText)!=null?ct:W.text)!=null?Ue:W.delta)!=null?ut:"";if(E&&W.hidden!==!0&&B.reasoning.chunks.push(String(E)),B.reasoning.status=W.done?"complete":"streaming",W.done){B.reasoning.completedAt=D(($t=W.completedAt)!=null?$t:W.timestamp);let z=(Pt=B.reasoning.startedAt)!=null?Pt:Date.now();B.reasoning.durationMs=Math.max(0,((Ht=B.reasoning.completedAt)!=null?Ht:Date.now())-z)}B.streaming=B.reasoning.status!=="complete",m(B)}else if(bt==="reason_complete"){let oe=(Oe=(F=k(W,!1))!=null?F:k(W,!0))!=null?Oe:`reason-${p()}`,B=h.get(oe);if(B!=null&&B.reasoning){B.reasoning.status="complete",B.reasoning.completedAt=D((me=W.completedAt)!=null?me:W.timestamp);let z=(nt=B.reasoning.startedAt)!=null?nt:Date.now();B.reasoning.durationMs=Math.max(0,((he=B.reasoning.completedAt)!=null?he:Date.now())-z),B.streaming=!1,m(B)}let E=I(W);E&&M.byStep.delete(E)}else if(bt==="tool_start"){let oe=(st=U(W,!0))!=null?st:`tool-${p()}`,B=j(oe),E=(Te=B.toolCall)!=null?Te:{id:oe,status:"pending"};E.name=(xt=W.toolName)!=null?xt:E.name,E.status="running",W.args!==void 0&&(E.args=W.args),E.startedAt=(ae=E.startedAt)!=null?ae:D((St=W.startedAt)!=null?St:W.timestamp),E.completedAt=void 0,E.durationMs=void 0,B.toolCall=E,B.streaming=!0,m(B)}else if(bt==="tool_chunk"){let oe=(Qe=(Je=U(W,!1))!=null?Je:U(W,!0))!=null?Qe:`tool-${p()}`,B=j(oe),E=(He=B.toolCall)!=null?He:{id:oe,status:"running"};E.startedAt=(kt=E.startedAt)!=null?kt:D((Ye=W.startedAt)!=null?Ye:W.timestamp);let z=($=(ot=(ft=W.text)!=null?ft:W.delta)!=null?ot:W.message)!=null?$:"";z&&(E.chunks=(wt=E.chunks)!=null?wt:[],E.chunks.push(String(z))),E.status="running",B.toolCall=E,B.streaming=!0,m(B)}else if(bt==="tool_complete"){let oe=(At=(yt=U(W,!1))!=null?yt:U(W,!0))!=null?At:`tool-${p()}`,B=j(oe),E=(te=B.toolCall)!=null?te:{id:oe,status:"running"};if(E.status="complete",W.result!==void 0&&(E.result=W.result),typeof W.duration=="number"&&(E.duration=W.duration),E.completedAt=D((ye=W.completedAt)!=null?ye:W.timestamp),typeof W.duration=="number")E.durationMs=W.duration;else{let fe=(Re=E.startedAt)!=null?Re:Date.now();E.durationMs=Math.max(0,((vt=E.completedAt)!=null?vt:Date.now())-fe)}B.toolCall=E,B.streaming=!1,m(B);let z=v(W);z&&y.byCall.delete(z)}else if(bt==="step_chunk"){let oe=W.stepType,B=W.executionType;if(oe==="tool"||B==="context")continue;let E=O(),z=(Nt=(It=(Bt=(Ze=W.text)!=null?Ze:W.delta)!=null?Bt:W.content)!=null?It:W.chunk)!=null?Nt:"";if(z){let Ee=((tn=X.get(E.id))!=null?tn:"")+z;E.rawContent=Ee,H.has(E.id)||H.set(E.id,this.createStreamParser());let Xe=H.get(E.id),Ie=Ee.trim().startsWith("{")||Ee.trim().startsWith("[");if(Ie&&X.set(E.id,Ee),Xe.__isPlainTextParser===!0){E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E);continue}let ke=Xe.processChunk(Ee);if(ke instanceof Promise)ke.then(Ce=>{var Ve;let xe=typeof Ce=="string"?Ce:(Ve=Ce==null?void 0:Ce.text)!=null?Ve:null;if(xe!==null&&xe.trim()!==""){let ce=g;ce&&ce.id===E.id&&(ce.content=xe,m(ce))}else if(!Ie&&!Ee.trim().startsWith("<")){let ce=g;ce&&ce.id===E.id&&(ce.content+=z,X.delete(ce.id),H.delete(ce.id),ce.rawContent=void 0,m(ce))}}).catch(()=>{E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E)});else{let Ce=typeof ke=="string"?ke:(Ot=ke==null?void 0:ke.text)!=null?Ot:null;Ce!==null&&Ce.trim()!==""?(E.content=Ce,m(E)):!Ie&&!Ee.trim().startsWith("<")&&(E.content+=z,X.delete(E.id),H.delete(E.id),E.rawContent=void 0,m(E))}}if(W.isComplete){let fe=(pn=(We=W.result)==null?void 0:We.response)!=null?pn:E.content;if(fe){let Ee=X.get(E.id),Xe=Ee!=null?Ee:Y(fe);E.rawContent=Xe;let Ie=H.get(E.id),_e=null,ke=!1;if(Ie&&(_e=Ie.getExtractedText(),_e===null&&(_e=Nn(Xe)),_e===null)){let Ce=Ie.processChunk(Xe);Ce instanceof Promise?(ke=!0,Ce.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=g;se&&se.id===E.id&&(se.content=Ve,se.streaming=!1,H.delete(se.id),X.delete(se.id),m(se))}})):_e=typeof Ce=="string"?Ce:(gn=Ce==null?void 0:Ce.text)!=null?gn:null}if(!ke){_e!==null&&_e.trim()!==""?E.content=_e:X.has(E.id)||(E.content=Y(fe));let Ce=H.get(E.id);if(Ce){let xe=(Dt=Ce.close)==null?void 0:Dt.call(Ce);xe instanceof Promise&&xe.catch(()=>{}),H.delete(E.id)}X.delete(E.id),E.streaming=!1,m(E)}}}}else if(bt==="step_complete"){let oe=W.stepType,B=W.executionType;if(oe==="tool"||B==="context")continue;let E=(Wn=W.result)==null?void 0:Wn.response,z=O();if(E!=null){let fe=H.get(z.id),Ee=!1,Xe=!1;if(fe){let Ie=fe.getExtractedText(),_e=X.get(z.id),ke=_e!=null?_e:Y(E);if(z.rawContent=ke,Ie!==null&&Ie.trim()!=="")z.content=Ie,Ee=!0;else{let Ce=Nn(ke);if(Ce!==null)z.content=Ce,Ee=!0;else{let xe=fe.processChunk(ke);if(xe instanceof Promise)Xe=!0,xe.then(Ve=>{var se;let ce=typeof Ve=="string"?Ve:(se=Ve==null?void 0:Ve.text)!=null?se:null;if(ce!==null&&ce.trim()!==""){let de=g;de&&de.id===z.id&&(de.content=ce,de.streaming=!1,H.delete(de.id),X.delete(de.id),m(de))}else{let de=fe.getExtractedText(),mt=g;mt&&mt.id===z.id&&(de!==null&&de.trim()!==""?mt.content=de:X.has(mt.id)||(mt.content=Y(E)),mt.streaming=!1,H.delete(mt.id),X.delete(mt.id),m(mt))}});else{let Ve=typeof xe=="string"?xe:(Ln=xe==null?void 0:xe.text)!=null?Ln:null;if(Ve!==null&&Ve.trim()!=="")z.content=Ve,Ee=!0;else{let ce=fe.getExtractedText();ce!==null&&ce.trim()!==""&&(z.content=ce,Ee=!0)}}}}}if(!Xe){if(!z.rawContent){let Ie=X.get(z.id);z.rawContent=Ie!=null?Ie:Y(E)}if(!Ee&&!X.has(z.id)&&(z.content=Y(E)),fe){let Ie=(mn=fe.close)==null?void 0:mn.call(fe);Ie instanceof Promise&&Ie.catch(()=>{})}H.delete(z.id),X.delete(z.id),z.streaming=!1,m(z)}}else H.delete(z.id),X.delete(z.id),z.streaming=!1,m(z)}else if(bt==="flow_complete"){let oe=(Yt=W.result)==null?void 0:Yt.response;if(oe!=null){let B=O(),E=X.get(B.id),z=E!=null?E:Y(oe);B.rawContent=z;let fe=Y(oe),Ee=H.get(B.id);if(Ee){let _e=Nn(z);if(_e!==null)fe=_e;else{let ke=Ee.processChunk(z);ke instanceof Promise&&ke.then(xe=>{var ce;let Ve=typeof xe=="string"?xe:(ce=xe==null?void 0:xe.text)!=null?ce:null;if(Ve!==null){let se=g;se&&se.id===B.id&&(se.content=Ve,se.streaming=!1,m(se))}});let Ce=Ee.getExtractedText();Ce!==null&&(fe=Ce)}}H.delete(B.id),X.delete(B.id);let Xe=fe!==B.content,Ie=B.streaming!==!1;Xe&&(B.content=fe),B.streaming=!1,(Xe||Ie)&&m(B)}else if(g!==null){let B=g;H.delete(B.id),X.delete(B.id),B.streaming!==!1&&(B.streaming=!1,m(B))}o({type:"status",status:"idle"})}else bt==="error"&&W.error&&o({type:"error",error:W.error instanceof Error?W.error:new Error(String(W.error))})}}}};function $r(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function qn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function zn(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var nn=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)}async sendMessage(n,o){var p,f,m,g,w;let t=n.trim();if(!t&&(!(o!=null&&o.contentParts)||o.contentParts.length===0))return;(p=this.abortController)==null||p.abort();let r=qn(),s=zn(),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?(m=(f=this.callbacks).onError)==null||m.call(f,h):(w=(g=this.callbacks).onError)==null||w.call(g,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,p;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=(p=t.sequence)!=null?p:0;return i!==a?i-a:o.id.localeCompare(t.id)})}};var u=(e,n)=>{let o=document.createElement(e);return n&&(o.className=n),o};var Ri=Ei(require("lucide"),1),re=(e,n=24,o="currentColor",t=2)=>{try{let r=e.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Ri[r];return s?Fi(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 Fi(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(([p,f])=>{p!=="stroke"&&d.setAttribute(p,String(f))}),r.appendChild(d)}}}),r}function Nr(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Or(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Dr(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function _r(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Un(e){return{type:"text",text:e}}function jr(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 qr(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 zr(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 Ur=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$i=["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=[...Ur,...$i];function Ni(e){return Ur.includes(e)||e.startsWith("image/")}function Jn(e){return Ni(e.type)}async function Jr(e){return new Promise((n,o)=>{let t=new FileReader;t.onload=()=>{let r=t.result;Jn(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 Yr(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 Oi(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Kr(e,n){let o=Oi(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 Yn={allowedTypes:Jt,maxFileSize:10*1024*1024,maxFiles:4};function Di(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function _i(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:Yn.allowedTypes,maxFileSize:(t=n.maxFileSize)!=null?t:Yn.maxFileSize,maxFiles:(r=n.maxFiles)!=null?r:Yn.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:Yn.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,p;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 m=Yr(f,this.config.allowedTypes,this.config.maxFileSize);if(!m.valid){let g=(s=m.error)!=null&&s.includes("type")?"type":"size";(a=(i=this.config).onFileRejected)==null||a.call(i,f,g);continue}try{let g=await Jr(f),w=Jn(f)?URL.createObjectURL(f):null,h={id:Di(),file:f,previewUrl:w,contentPart:g};this.attachments.push(h),this.renderPreview(h)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(p=(d=this.config).onAttachmentsChange)==null||p.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=Jn(n.file),t=u("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=u("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=u("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=_i(n.file.type),d=re(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let p=u("span");p.textContent=Kr(n.file.type,n.file.name),p.style.fontSize="8px",p.style.fontWeight="600",p.style.color="var(--cw-muted, #6b7280)",p.style.textTransform="uppercase",p.style.lineHeight="1",i.appendChild(p),t.appendChild(i)}let r=u("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=re("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 gs=()=>{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"},ji=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"||gs()==="dark"?t:o},Xr=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let o=new MutationObserver(()=>{e(gs())});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(gs());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())}},Kn=(e,n)=>{let o=ji(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 Vr=require("idiomorph"),Gr=(e,n,o={})=>{let{preserveTypingAnimation:t=!0}=o;Vr.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 gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Wt={"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 An=(e,n)=>{let o=u("button");o.type="button",o.innerHTML=`
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
+ <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
+ <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
11
+ <span class="tvw-text-sm tvw-font-semibold tvw-text-cw-primary" data-role="launcher-title"></span>
12
+ <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
+ </span>
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,I,v,O,C,k,K,J,U,j,D;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=(I=i.subtitle)!=null?I:"Get answers fast");let p=o.querySelector(".tvw-flex-col");p&&(i.textHidden?p.style.display="none":p.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 H=parseFloat(Y)||24,X=re(i.agentIconName,H*.6,"#ffffff",2);X?(f.appendChild(X),f.style.display=""):(f.textContent=(O=i.agentIconText)!=null?O:"\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 m=o.querySelector("[data-role='launcher-image']");if(m){let Y=(k=i.agentIconSize)!=null?k:"40px";m.style.height=Y,m.style.width=Y,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(m.src=i.iconUrl,m.style.display="block"):m.style.display="none"}let g=o.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Y=(K=i.callToActionIconSize)!=null?K:"32px";g.style.height=Y,g.style.width=Y,i.callToActionIconBackgroundColor?(g.style.backgroundColor=i.callToActionIconBackgroundColor,g.classList.remove("tvw-bg-cw-primary")):(g.style.backgroundColor="",g.classList.add("tvw-bg-cw-primary"));let H=0;if(i.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=i.callToActionIconPadding,H=(parseFloat(i.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),i.callToActionIconHidden)g.style.display="none";else if(g.style.display="",g.innerHTML="",i.callToActionIconName){let X=parseFloat(Y)||24,Pe=Math.max(X-H,8),V=re(i.callToActionIconName,Pe,"currentColor",2);V?g.appendChild(V):g.textContent=(J=i.callToActionIconText)!=null?J:"\u2197"}else g.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}let w=i.position&&Wt[i.position]?Wt[i.position]:Wt["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=(j=i.border)!=null?j:R,o.style.boxShadow=(D=i.shadow)!=null?D:M},r=()=>{o.removeEventListener("click",n),o.remove()};return e&&t(e),{element:o,update:t,destroy:r}};var qt=e=>{var U,j,D,Y,H,X,Pe,V,_,tt,at,lt,Lt,Ft,q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St;let{config:n,showClose:o=!0}=e,t=u("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=(U=n==null?void 0:n.launcher)!=null?U:{},s=(j=r.headerIconSize)!=null?j:"48px",i=(D=r.closeButtonSize)!=null?D:"32px",a=(Y=r.closeButtonPlacement)!=null?Y:"inline",d=(H=r.headerIconHidden)!=null?H:!1,p=r.headerIconName,f=u("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(p){let ae=parseFloat(s)||24,Je=re(p,ae*.6,"#ffffff",2);Je?f.replaceChildren(Je):f.textContent=(Pe=(X=n==null?void 0:n.launcher)==null?void 0:X.agentIconText)!=null?Pe:"\u{1F4AC}"}else if((V=n==null?void 0:n.launcher)!=null&&V.iconUrl){let ae=u("img");ae.src=n.launcher.iconUrl,ae.alt="",ae.className="tvw-rounded-xl tvw-object-cover",ae.style.height=s,ae.style.width=s,f.replaceChildren(ae)}else f.textContent=(tt=(_=n==null?void 0:n.launcher)==null?void 0:_.agentIconText)!=null?tt:"\u{1F4AC}";let m=u("div","tvw-flex tvw-flex-col"),g=u("span","tvw-text-base tvw-font-semibold");g.textContent=(lt=(at=n==null?void 0:n.launcher)==null?void 0:at.title)!=null?lt:"Chat Assistant";let w=u("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",m.append(g,w),d?t.append(m):t.append(f,m);let h=(q=r.clearChat)!=null?q:{},R=(we=h.enabled)!=null?we:!0,M=(dt=h.placement)!=null?dt:"inline",y=null,S=null;if(R){let ae=(ct=h.size)!=null?ct:"32px",Je=(Ue=h.iconName)!=null?Ue:"refresh-cw",Qe=(ut=h.iconColor)!=null?ut:"",He=($t=h.backgroundColor)!=null?$t:"",Ye=(Pt=h.borderWidth)!=null?Pt:"",kt=(Ht=h.borderColor)!=null?Ht:"",ft=(F=h.borderRadius)!=null?F:"",ot=(Oe=h.paddingX)!=null?Oe:"",$=(me=h.paddingY)!=null?me:"",wt=(nt=h.tooltipText)!=null?nt:"Clear chat",yt=(he=h.showTooltip)!=null?he:!0;S=u("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"&&(S.style.right="48px"),y=u("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=ae,y.style.width=ae,y.type="button",y.setAttribute("aria-label",wt);let At=re(Je,"20px",Qe||"",2);if(At&&y.appendChild(At),Qe&&(y.style.color=Qe,y.classList.remove("tvw-text-cw-muted")),He&&(y.style.backgroundColor=He,y.classList.remove("hover:tvw-bg-gray-100")),Ye||kt){let te=Ye||"0px",ye=kt||"transparent";y.style.border=`${te} solid ${ye}`,y.classList.remove("tvw-border-none")}if(ft&&(y.style.borderRadius=ft,y.classList.remove("tvw-rounded-full")),ot?(y.style.paddingLeft=ot,y.style.paddingRight=ot):(y.style.paddingLeft="",y.style.paddingRight=""),$?(y.style.paddingTop=$,y.style.paddingBottom=$):(y.style.paddingTop="",y.style.paddingBottom=""),S.appendChild(y),yt&&wt&&y&&S){let te=null,ye=()=>{if(te||!y)return;te=u("div","tvw-clear-chat-tooltip"),te.textContent=wt;let vt=u("div");vt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(vt);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)},Re=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};S.addEventListener("mouseenter",ye),S.addEventListener("mouseleave",Re),y.addEventListener("focus",ye),y.addEventListener("blur",Re),S._cleanupTooltip=()=>{Re(),S&&(S.removeEventListener("mouseenter",ye),S.removeEventListener("mouseleave",Re)),y&&(y.removeEventListener("focus",ye),y.removeEventListener("blur",Re))}}M==="inline"&&t.appendChild(S)}let I=u("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":R&&M==="inline"?"":"tvw-ml-auto"),v=u("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 O=(st=r.closeButtonTooltipText)!=null?st:"Close chat",C=(Te=r.closeButtonShowTooltip)!=null?Te:!0;v.setAttribute("aria-label",O),v.style.display=o?"":"none";let k=(xt=r.closeButtonIconName)!=null?xt:"x",K=(St=r.closeButtonIconText)!=null?St:"\xD7",J=re(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 ae=r.closeButtonBorderWidth||"0px",Je=r.closeButtonBorderColor||"transparent";v.style.border=`${ae} solid ${Je}`,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&&O){let ae=null,Je=()=>{if(ae)return;ae=u("div","tvw-clear-chat-tooltip"),ae.textContent=O;let He=u("div");He.className="tvw-clear-chat-tooltip-arrow",ae.appendChild(He);let Ye=v.getBoundingClientRect();ae.style.position="fixed",ae.style.left=`${Ye.left+Ye.width/2}px`,ae.style.top=`${Ye.top-8}px`,ae.style.transform="translate(-50%, -100%)",document.body.appendChild(ae)},Qe=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};I.addEventListener("mouseenter",Je),I.addEventListener("mouseleave",Qe),v.addEventListener("focus",Je),v.addEventListener("blur",Qe),I._cleanupTooltip=()=>{Qe(),I.removeEventListener("mouseenter",Je),I.removeEventListener("mouseleave",Qe),v.removeEventListener("focus",Je),v.removeEventListener("blur",Qe)}}return a!=="top-right"&&t.appendChild(I),{header:t,iconHolder:f,headerTitle:g,headerSubtitle:w,closeButton:v,closeButtonWrapper:I,clearChatButton:y,clearChatButtonWrapper:S}},Zt=(e,n,o)=>{var i,a,d,p;let t=(i=o==null?void 0:o.launcher)!=null?i:{},r=(a=t.closeButtonPlacement)!=null?a:"inline",s=(p=(d=t.clearChat)==null?void 0:d.placement)!=null?p:"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 ms=e=>qt({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),hs=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=u("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=u("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=u("div",""),p=u("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");p.style.height=a,p.style.width=a,p.type="button",p.setAttribute("aria-label","Close chat"),p.style.display=o?"":"none";let f=(y=r.closeButtonIconName)!=null?y:"x",m=re(f,"20px",r.closeButtonColor||"",2);m?p.appendChild(m):p.textContent="\xD7",t&&p.addEventListener("click",t),d.appendChild(p),s.appendChild(d);let g=u("div");g.style.display="none";let w=u("span");return w.style.display="none",{header:s,iconHolder:g,headerTitle:i,headerSubtitle:w,closeButton:p,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},fs=e=>{var v,O,C,k,K,J,U,j;let{config:n,showClose:o=!0,onClose:t,onClearChat:r}=e,s=(v=n==null?void 0:n.launcher)!=null?v:{},i=u("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=u("div","tvw-flex tvw-items-center tvw-gap-3"),d=(O=s.headerIconSize)!=null?O:"56px",p=u("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");p.style.height=d,p.style.width=d;let f=s.headerIconName;if(f){let D=parseFloat(d)||24,Y=re(f,D*.5,"#ffffff",2);Y?p.replaceChildren(Y):p.textContent=(C=s.agentIconText)!=null?C:"\u{1F4AC}"}else if(s.iconUrl){let D=u("img");D.src=s.iconUrl,D.alt="",D.className="tvw-rounded-xl tvw-object-cover",D.style.height=d,D.style.width=d,p.replaceChildren(D)}else p.textContent=(k=s.agentIconText)!=null?k:"\u{1F4AC}";let m=u("div","tvw-flex tvw-flex-col tvw-flex-1"),g=u("span","tvw-text-lg tvw-font-semibold");g.textContent=(K=s.title)!=null?K:"Chat Assistant";let w=u("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(J=s.subtitle)!=null?J:"Here to help you get answers fast",m.append(g,w),a.append(p,m);let h=(U=s.closeButtonSize)!=null?U:"32px",R=u("div",""),M=u("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=(j=s.closeButtonIconName)!=null?j:"x",S=re(y,"20px",s.closeButtonColor||"",2);S?M.appendChild(S):M.textContent="\xD7",t&&M.addEventListener("click",t),R.appendChild(M),a.appendChild(R),i.appendChild(a);let I=u("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:p,headerTitle:g,headerSubtitle:w,closeButton:M,closeButtonWrapper:R,clearChatButton:null,clearChatButtonWrapper:null}},Xn={default:ms,minimal:hs,expanded:fs},ws=e=>{var n;return(n=Xn[e])!=null?n:Xn.default},sn=(e,n,o)=>{var i,a,d;if(n!=null&&n.render){let p=n.render({config:e,onClose:o==null?void 0:o.onClose,onClearChat:o==null?void 0:o.onClearChat}),f=u("div");f.style.display="none";let m=u("span"),g=u("span"),w=u("button");w.style.display="none";let h=u("div");return h.style.display="none",{header:p,iconHolder:f,headerTitle:m,headerSubtitle:g,closeButton:w,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let t=(i=n==null?void 0:n.layout)!=null?i:"default",s=ws(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 qi=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'}},on=e=>{var q,we,dt,ct,Ue,ut,$t,Pt,Ht,F,Oe,me,nt,he,st,Te,xt,St,ae,Je,Qe,He,Ye,kt,ft,ot,$,wt,yt,At;let{config:n}=e,o=u("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),t=u("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),r=u("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=u("textarea");s.placeholder=(we=(q=n==null?void 0:n.copy)==null?void 0:q.inputPlaceholder)!=null?we:"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=(ct=(dt=n==null?void 0:n.theme)==null?void 0:dt.inputFontFamily)!=null?ct:"sans-serif",a=(ut=(Ue=n==null?void 0:n.theme)==null?void 0:Ue.inputFontWeight)!=null?ut:"400";s.style.fontFamily=qi(i),s.style.fontWeight=a;let f=3*20;s.style.maxHeight=`${f}px`,s.style.overflowY="auto";let m=()=>{s.style.height="auto";let te=Math.min(s.scrollHeight,f);s.style.height=`${te}px`};s.addEventListener("input",m),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 g=($t=n==null?void 0:n.sendButton)!=null?$t:{},w=(Pt=g.useIcon)!=null?Pt:!1,h=(Ht=g.iconText)!=null?Ht:"\u2191",R=g.iconName,M=(F=g.tooltipText)!=null?F:"Send message",y=(Oe=g.showTooltip)!=null?Oe:!1,S=(me=g.size)!=null?me:"40px",I=g.backgroundColor,v=g.textColor,O=u("div","tvw-send-button-wrapper"),C=u("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="",R){let te=parseFloat(S)||24,ye=v&&typeof v=="string"&&v.trim()?v.trim():"currentColor",Re=re(R,te,ye,2);Re?(C.appendChild(Re),C.style.color=ye):(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=(he=(nt=n==null?void 0:n.copy)==null?void 0:nt.sendButtonLabel)!=null?he:"Send",v?C.style.color=v:C.classList.add("tvw-text-white");if(g.borderWidth&&(C.style.borderWidth=g.borderWidth,C.style.borderStyle="solid"),g.borderColor&&(C.style.borderColor=g.borderColor),g.paddingX?(C.style.paddingLeft=g.paddingX,C.style.paddingRight=g.paddingX):(C.style.paddingLeft="",C.style.paddingRight=""),g.paddingY?(C.style.paddingTop=g.paddingY,C.style.paddingBottom=g.paddingY):(C.style.paddingTop="",C.style.paddingBottom=""),y&&M){let te=u("div","tvw-send-button-tooltip");te.textContent=M,O.appendChild(te)}O.appendChild(C);let k=(st=n==null?void 0:n.voiceRecognition)!=null?st:{},K=k.enabled===!0,J=null,U=null,j=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(K&&j){U=u("div","tvw-send-button-wrapper"),J=u("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=(Te=k.iconName)!=null?Te:"mic",ye=(xt=k.iconSize)!=null?xt:S,Re=parseFloat(ye)||24,vt=(St=k.backgroundColor)!=null?St:I,Ze=(ae=k.iconColor)!=null?ae:v;J.style.width=ye,J.style.height=ye,J.style.minWidth=ye,J.style.minHeight=ye,J.style.fontSize="18px",J.style.lineHeight="1";let Bt=Ze||"currentColor",It=re(te,Re,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"),Ze?J.style.color=Ze:!Ze&&!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),U.appendChild(J);let Nt=(Je=k.tooltipText)!=null?Je:"Start voice recognition";if(((Qe=k.showTooltip)!=null?Qe:!1)&&Nt){let Ot=u("div","tvw-send-button-tooltip");Ot.textContent=Nt,U.appendChild(Ot)}}let D=(He=n==null?void 0:n.attachments)!=null?He:{},Y=D.enabled===!0,H=null,X=null,Pe=null,V=null;if(Y){V=u("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),V.style.display="none",Pe=u("input"),Pe.type="file",Pe.accept=((Ye=D.allowedTypes)!=null?Ye:Jt).join(","),Pe.multiple=((kt=D.maxFiles)!=null?kt:4)>1,Pe.style.display="none",Pe.setAttribute("aria-label","Attach files"),X=u("div","tvw-send-button-wrapper"),H=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),H.type="button",H.setAttribute("aria-label",(ft=D.buttonTooltipText)!=null?ft:"Attach file");let te=(ot=D.buttonIconName)!=null?ot:"paperclip",ye=S,Re=parseFloat(ye)||40,vt=Math.round(Re*.6);H.style.width=ye,H.style.height=ye,H.style.minWidth=ye,H.style.minHeight=ye,H.style.fontSize="18px",H.style.lineHeight="1",H.style.backgroundColor="transparent",H.style.color="var(--cw-primary, #111827)",H.style.border="none",H.style.borderRadius="6px",H.style.transition="background-color 0.15s ease",H.addEventListener("mouseenter",()=>{H.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),H.addEventListener("mouseleave",()=>{H.style.backgroundColor="transparent"});let Ze=re(te,vt,"currentColor",1.5);Ze?H.appendChild(Ze):H.textContent="\u{1F4CE}",H.addEventListener("click",Nt=>{Nt.preventDefault(),Pe==null||Pe.click()}),X.appendChild(H);let Bt=($=D.buttonTooltipText)!=null?$:"Attach file",It=u("div","tvw-send-button-tooltip");It.textContent=Bt,X.appendChild(It)}r.addEventListener("click",te=>{te.target!==C&&te.target!==O&&te.target!==J&&te.target!==U&&te.target!==H&&te.target!==X&&s.focus()}),V&&(V.style.gap="8px",r.append(V)),Pe&&r.append(Pe),r.append(s);let _=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),tt=u("div","tvw-flex tvw-items-center tvw-gap-2");X&&tt.append(X);let at=u("div","tvw-flex tvw-items-center tvw-gap-1");U&&at.append(U),at.append(O),_.append(tt,at),r.append(_);let lt=u("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 lt.style.display=Ft?"":"none",lt.textContent=(At=Lt.idleText)!=null?At:"Online",o.append(t,r,lt),{footer:o,suggestions:t,composerForm:r,textarea:s,sendButton:C,sendButtonWrapper:O,micButton:J,micButtonWrapper:U,statusText:lt,attachmentButton:H,attachmentButtonWrapper:X,attachmentInput:Pe,attachmentPreviewsContainer:V,actionsRow:_,leftActions:tt,rightActions:at}};var Qr=e=>{var d,p,f,m,g,w,h;if(!((p=(d=e==null?void 0:e.launcher)==null?void 0:d.enabled)!=null?p:!0)){let R=u("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),M=u("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),y=(m=(f=e==null?void 0:e.launcher)==null?void 0:f.width)!=null?m:"100%";return R.style.width=y,M.style.width="100%",R.appendChild(M),{wrapper:R,panel:M}}let o=(g=e==null?void 0:e.launcher)!=null?g:{},t=o.position&&Wt[o.position]?Wt[o.position]:Wt["bottom-right"],r=u("div",`tvw-widget-wrapper tvw-fixed ${t} tvw-z-50 tvw-transition`),s=u("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}},Zr=(e,n=!0)=>{var w,h,R,M,y,S,I;let o=u("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?sn(e,t,{showClose:n}):qt({config:e,showClose:n}),i=u("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=u("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=u("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 p=u("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");p.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,p);let f=u("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,f);let m=on({config:e}),g=((I=e==null?void 0:e.layout)==null?void 0:I.showFooter)!==!1;return r?Zt(o,s,e):(s.header.style.display="none",Zt(o,s,e)),o.append(i),g||(m.footer.style.display="none"),o.append(m.footer),{container:o,body:i,messagesWrapper:f,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:p,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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Tn=()=>{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},zi=(e,n)=>{let o=u("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=u("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},ei=(e,n)=>{let o=u("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},Ui=(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},ys=(e,n,o)=>{var h,R,M,y,S,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=(S=n.align)!=null?S:"right",d=(I=n.layout)!=null?I:"pill-inside",p={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],m=u("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${p} ${f} ${i==="hover"?"tvw-message-actions-hover":""}`);m.id=`actions-${e.id}`,m.setAttribute("data-actions-for",e.id);let g=null,w=(v,O,C,k)=>{let K=document.createElement("button");K.className="tvw-message-action-btn",K.setAttribute("aria-label",O),K.setAttribute("title",O),k&&K.setAttribute("data-action",k);let J=re(v,14,"currentColor",2);return J&&K.appendChild(J),K.addEventListener("click",U=>{U.preventDefault(),U.stopPropagation(),C()}),K};if(t){let v=w("copy","Copy message",()=>{let O=e.content||"";navigator.clipboard.writeText(O).then(()=>{v.classList.add("tvw-message-action-success");let C=re("check",14,"currentColor",2);C&&(v.innerHTML="",v.appendChild(C)),setTimeout(()=>{v.classList.remove("tvw-message-action-success");let k=re("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");m.appendChild(v)}if(r){let v=w("thumbs-up","Upvote",()=>{if(g==="upvote")g=null,v.classList.remove("tvw-message-action-active");else{let C=m.querySelector('[data-action="downvote"]');C&&C.classList.remove("tvw-message-action-active"),g="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");m.appendChild(v)}if(s){let v=w("thumbs-down","Downvote",()=>{if(g==="downvote")g=null,v.classList.remove("tvw-message-action-active");else{let C=m.querySelector('[data-action="upvote"]');C&&C.classList.remove("tvw-message-action-active"),g="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");m.appendChild(v)}return m},rn=(e,n,o,t,r)=>{var I,v,O,C,k;let s=o!=null?o:{},i=(I=s.layout)!=null?I:"bubble",a=s.avatar,d=s.timestamp,p=(v=a==null?void 0:a.show)!=null?v:!1,f=(O=d==null?void 0:d.show)!=null?O:!1,m=(C=a==null?void 0:a.position)!=null?C:"left",g=(k=d==null?void 0:d.position)!=null?k:"below",w=Ui(e.role,i),h=u("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&&g==="inline"&&e.createdAt){let K=ei(e,d);K.classList.add("tvw-ml-2","tvw-inline"),R.appendChild(K)}if(h.appendChild(R),f&&g==="below"&&e.createdAt){let K=ei(e,d);K.classList.add("tvw-mt-1"),h.appendChild(K)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let K=Tn();h.appendChild(K)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(t==null?void 0:t.enabled)!==!1&&t){let K=ys(e,t,r);h.appendChild(K)}if(!p||e.role==="system")return h;let y=u("div",`tvw-flex tvw-gap-2 ${e.role==="user"?"tvw-flex-row-reverse":""}`),S=zi(a,e.role);return m==="right"||m==="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},ti=(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}):rn(e,n,o,t,r)};var an=new Set,ni=(e,n)=>{let o=an.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=re(o?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=o?"Hide":"Show"}r.style.display=o?"":"none"},vs=e=>{let n=e.reasoning,o=u("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=an.has(e.id),r=u("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=u("div","tvw-flex tvw-flex-col tvw-text-left"),i=u("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=u("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Hr(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let d=u("div","tvw-flex tvw-items-center"),f=re(t?"chevron-up":"chevron-down",16,"currentColor",2);f?d.appendChild(f):d.textContent=t?"Hide":"Show";let m=u("div","tvw-flex tvw-items-center tvw-ml-auto");m.append(d),r.append(s,m);let g=u("div","tvw-border-t tvw-border-gray-200 tvw-bg-gray-50 tvw-px-4 tvw-py-3");g.style.display=t?"":"none";let w=n.chunks.join(""),h=u("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"),g.appendChild(h),(()=>{r.setAttribute("aria-expanded",t?"true":"false"),d.innerHTML="";let y=re(t?"chevron-up":"chevron-down",16,"currentColor",2);y?d.appendChild(y):d.textContent=t?"Hide":"Show",g.style.display=t?"":"none"})(),o.append(r,g),o};var ln=new Set,si=(e,n,o)=>{var p;let t=ln.has(e),r=(p=o==null?void 0:o.toolCall)!=null?p:{},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",m=re(t?"chevron-up":"chevron-down",16,f,2);m?d.appendChild(m):d.textContent=t?"Hide":"Show"}i.style.display=t?"":"none"},bs=(e,n)=>{var R;let o=e.toolCall,t=(R=n==null?void 0:n.toolCall)!=null?R:{},r=u("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=ln.has(e.id),i=u("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=u("div","tvw-flex tvw-flex-col tvw-text-left"),d=u("span","tvw-text-xs tvw-text-cw-primary");t.headerTextColor&&(d.style.color=t.headerTextColor),d.textContent=Br(o),a.appendChild(d);let p=u("div","tvw-flex tvw-items-center"),f=t.toggleTextColor||t.headerTextColor||"currentColor",m=re(s?"chevron-up":"chevron-down",16,f,2);m?p.appendChild(m):p.textContent=s?"Hide":"Show";let g=u("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");g.append(p),i.append(a,g);let w=u("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=u("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=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Arguments";let S=u("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=ps(o.args),M.append(y,S),w.appendChild(M)}if(o.chunks&&o.chunks.length){let M=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Activity";let S=u("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
+ `),M.append(y,S),w.appendChild(M)}if(o.status==="complete"&&o.result!==void 0){let M=u("div","tvw-space-y-1"),y=u("div","tvw-text-xs tvw-text-cw-muted");t.labelTextColor&&(y.style.color=t.labelTextColor),y.textContent="Result";let S=u("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=ps(o.result),M.append(y,S),w.appendChild(M)}if(o.status==="complete"&&typeof o.duration=="number"){let M=u("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"),p.innerHTML="";let M=t.toggleTextColor||t.headerTextColor||"currentColor",y=re(s?"chevron-up":"chevron-down",16,M,2);y?p.appendChild(y):p.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),r.append(i,w),r};var oi=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(),m=r?r.isStreaming():!1,g=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=u("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=m,a!=null&&a.fontFamily&&(h.style.fontFamily=g(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 ri={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"}},Cs=(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=ri[i])!=null?R:ri.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=u("div","tvw-space-y-1"),p=u("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(p.textContent=a.title,d.appendChild(p),a.description){let y=u("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=u("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");S.htmlFor=`${n.id}-${i}-${y.name}`;let I=u("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");I.textContent=y.label,S.appendChild(I);let v=(C=y.type)!=null?C:"text",O;v==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=v),O.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",O.id=`${n.id}-${i}-${y.name}`,O.name=y.name,O.placeholder=(k=y.placeholder)!=null?k:"",y.required&&(O.required=!0),S.appendChild(O),f.appendChild(S)});let m=u("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),g=u("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=u("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",m.appendChild(g),m.appendChild(w),f.appendChild(m),s.replaceChildren(d,f),f.addEventListener("submit",async y=>{var O,C;y.preventDefault();let S=(O=o.formEndpoint)!=null?O:"/form",I=new FormData(f),v={};I.forEach((k,K)=>{v[K]=k}),v.type=i,w.disabled=!0,g.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();g.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){g.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var xs=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()}},En=new xs;var Ss={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"},As={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:Ss,darkTheme:As,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 Vn(e){var n,o,t,r,s,i,a,d,p,f,m,g,w,h,R,M,y,S,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:{...(p=(d=Be.layout)==null?void 0:d.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(w=(g=Be.layout)==null?void 0:g.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:{...(S=Be.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Be.messageActions,...e.messageActions}}:Be}var ii=()=>{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 Ji=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Yi=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},Mn=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Ji(e),o=Yi(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}},Ts=e=>typeof e=="string"?e:e==null?"":String(e),en={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Ts(e.payload.text)},messageAndClick:(e,n)=>{var r;if(e.type!=="message_and_click")return;let o=e.payload,t=Ts(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:Ts(o.text)}}},ai=e=>Array.isArray(e)?e.map(n=>String(n)):[],kn=e=>{let n=new Set(ai(e.getSessionMetadata().processedActionMessageIds)),o=()=>{n=new Set(ai(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((p,f)=>p||(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 p of e.handlers)if(p)try{let f=p(a,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef});if(!f)continue;if(f.handled){let m=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:m}}}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",f)}return{text:"",persist:!0}},syncFromMetadata:o}};var Ki=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}},Xi=e=>e.map(n=>({...n,streaming:!1})),Gn=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let o=n();return o?Ki(o.getItem(e)):null},save:o=>{let t=n();if(t)try{let r={...o,messages:o.messages?Xi(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 Es=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)})}},dn=new Es;var cn=require("partial-json");function Vi(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Gi(e,n){if(!Vi(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 Qn(){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,cn.parse)(o,cn.STR|cn.OBJ),s=Gi(r,o);s&&(e=s)}catch{}return n=o.length,e},reset:()=>{e=null,n=0}}}function li(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Zn(e,n){let{config:o,message:t,onPropsUpdate:r}=n,s=dn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let i={message:t,config: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 di(){let e=Qn();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function es(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 ts(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 Qi=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ns(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:p=Qi}=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 m=null,g=document.createElement("div");g.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),g.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":""}: ${p[C-1]}`),k.title=p[C-1],k.dataset.rating=String(C),k.innerHTML=`
17
+ <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
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
+ </svg>
20
+ `,k.addEventListener("click",()=>{m=C,y.forEach((K,J)=>{let U=J<C;K.classList.toggle("selected",U),K.setAttribute("aria-checked",J===C-1?"true":"false")})}),y.push(k),M.appendChild(k)}g.appendChild(M);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),g.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 O=document.createElement("button");return O.type="button",O.className="tvw-feedback-btn tvw-feedback-btn-submit",O.textContent=i,O.addEventListener("click",async()=>{if(m===null){M.classList.add("tvw-feedback-shake"),setTimeout(()=>M.classList.remove("tvw-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let C=(S==null?void 0:S.value.trim())||void 0;await n(m,C),f.remove()}catch(C){O.disabled=!1,O.textContent=i,console.error("[CSAT Feedback] Failed to submit:",C)}}),I.appendChild(v),I.appendChild(O),g.appendChild(I),f.appendChild(g),f}function ss(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:p="Not likely",highLabel:f="Very likely"}=e,m=document.createElement("div");m.className="tvw-feedback-container tvw-feedback-nps",m.setAttribute("role","dialog"),m.setAttribute("aria-label","Net Promoter Score feedback");let g=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 S=document.createElement("div");S.className="tvw-feedback-labels";let I=document.createElement("span");I.className="tvw-feedback-label-low",I.textContent=p;let v=document.createElement("span");v.className="tvw-feedback-label-high",v.textContent=f,S.appendChild(I),S.appendChild(v);let O=document.createElement("div");O.className="tvw-feedback-numbers";let C=[];for(let j=0;j<=10;j++){let D=document.createElement("button");D.type="button",D.className="tvw-feedback-rating-btn tvw-feedback-number-btn",D.setAttribute("role","radio"),D.setAttribute("aria-checked","false"),D.setAttribute("aria-label",`Rating ${j} out of 10`),D.textContent=String(j),D.dataset.rating=String(j),j<=6?D.classList.add("tvw-feedback-detractor"):j<=8?D.classList.add("tvw-feedback-passive"):D.classList.add("tvw-feedback-promoter"),D.addEventListener("click",()=>{g=j,C.forEach((Y,H)=>{Y.classList.toggle("selected",H===j),Y.setAttribute("aria-checked",H===j?"true":"false")})}),C.push(D),O.appendChild(D)}y.appendChild(S),y.appendChild(O),w.appendChild(y);let k=null;if(d){let j=document.createElement("div");j.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"),j.appendChild(k),w.appendChild(j)}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(),m.remove()});let U=document.createElement("button");return U.type="button",U.className="tvw-feedback-btn tvw-feedback-btn-submit",U.textContent=i,U.addEventListener("click",async()=>{if(g===null){O.classList.add("tvw-feedback-shake"),setTimeout(()=>O.classList.remove("tvw-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let j=(k==null?void 0:k.value.trim())||void 0;await n(g,j),m.remove()}catch(j){U.disabled=!1,U.textContent=i,console.error("[NPS Feedback] Failed to submit:",j)}}),K.appendChild(J),K.appendChild(U),w.appendChild(K),m.appendChild(w),m}var un="persona-chat-history",Zi=30*1e3,Ms=e=>!e||typeof e!="object"?{}:{...e},ci=e=>e.map(n=>({...n,streaming:!1})),ui=(e,n)=>{let o=e!=null&&e.markdown?Sn(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 p=n.process({text:r,raw:s!=null?s:r,message:t.message,streaming:t.streaming});p!==null&&(r=p.text,p.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):Fn(r)}},os=(e,n,o)=>{var Bs,Is,Rs,Fs,$s,Ns,Os,Ds,_s,js,qs,zs,Us,Js,Ys,Ks,Xs;(!e.id||e.id!=="persona-root")&&(e.id="persona-root");let t=Vn(n),r=En.getForInstance(t.plugins);t.components&&dn.registerAll(t.components);let s=ii(),i=(Bs=t.storageAdapter)!=null?Bs:Gn(),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=Ms(c.metadata)),(Is=c.messages)!=null&&Is.length&&(t={...t,initialMessages:c.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}let p=()=>a,f=l=>{var A;a=(A=l({...a}))!=null?A:{},mn()},m=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Mn],g=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick],w=kn({parsers:m,handlers:g,getSessionMetadata:p,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null});w.syncFromMetadata();let h=(Fs=(Rs=t.launcher)==null?void 0:Rs.enabled)!=null?Fs:!0,R=(Ns=($s=t.launcher)==null?void 0:$s.autoExpand)!=null?Ns:!1,M=R,y=h,S=(Ds=(Os=t.layout)==null?void 0:Os.header)==null?void 0:Ds.layout,I=h?R:!0,v=ui(t,w),O=(js=(_s=t.features)==null?void 0:_s.showReasoning)!=null?js:!0,C=(zs=(qs=t.features)==null?void 0:qs.showToolCalls)!=null?zs:!0,k={onCopy:l=>{var c,A;s.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.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),$!=null&&$.isClientTokenMode()&&$.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=(Us=t.statusIndicator)!=null?Us:{},J=l=>{var c,A,P,b;return l==="idle"?(c=K.idleText)!=null?c:gt.idle:l==="connecting"?(A=K.connectingText)!=null?A:gt.connecting:l==="connected"?(P=K.connectedText)!=null?P:gt.connected:l==="error"?(b=K.errorText)!=null?b:gt.error:gt[l]},{wrapper:U,panel:j}=Qr(t),D=Zr(t,h),{container:Y,body:H,messagesWrapper:X,suggestions:Pe,textarea:V,sendButton:_,sendButtonWrapper:tt,composerForm:at,statusText:lt,introTitle:Lt,introSubtitle:Ft,closeButton:q,iconHolder:we,headerTitle:dt,headerSubtitle:ct,header:Ue,footer:ut,actionsRow:$t,leftActions:Pt,rightActions:Ht}=D,F=D.micButton,Oe=D.micButtonWrapper,me=D.attachmentButton,nt=D.attachmentButtonWrapper,he=D.attachmentInput,st=D.attachmentPreviewsContainer,Te=null;(Js=t.attachments)!=null&&Js.enabled&&he&&st&&(Te=Qt.fromConfig(t.attachments),Te.setPreviewsContainer(st),he.addEventListener("change",l=>{let c=l.target;Te==null||Te.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:()=>W(!1,"user")});if(l){let c=Y.querySelector(".tvw-border-b-cw-divider");c&&(c.replaceWith(l),Ue=l)}}let St=r.find(l=>l.renderComposer);if(St!=null&&St.renderComposer){let l=St.renderComposer({config:t,defaultRenderer:()=>on({config:t}).footer,onSubmit:c=>{$&&!$.isStreaming()&&$.sendMessage(c)},disabled:!1});l&&(ut.replaceWith(l),ut=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 X;case"footer-top":return Pe;case"composer":return at;case"footer-bottom":return lt;default:return null}},A=(Q,ue)=>{var T;switch(Q){case"header-left":case"header-center":case"header-right":if(Q==="header-left")Ue.insertBefore(ue,Ue.firstChild);else if(Q==="header-right")Ue.appendChild(ue);else{let G=Ue.querySelector(".tvw-flex-col");G?(T=G.parentNode)==null||T.insertBefore(ue,G.nextSibling):Ue.appendChild(ue)}break;case"body-top":let ee=H.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ee?ee.replaceWith(ue):H.insertBefore(ue,H.firstChild);break;case"body-bottom":H.appendChild(ue);break;case"footer-top":Pe.replaceWith(ue);break;case"footer-bottom":lt.replaceWith(ue);break;default:break}};for(let[Q,ue]of Object.entries(l))if(ue)try{let T=ue({config:t,defaultContent:()=>c(Q)});T&&A(Q,T)}catch(T){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${Q}":`,T)}})();let Je=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"?(an.has(b)?an.delete(b):an.add(b),ni(b,P)):Q==="tool"&&(ln.has(b)?ln.delete(b):ln.add(b),si(b,P,t))};X.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),X.addEventListener("keydown",l=>{let c=l.target;(l.key==="Enter"||l.key===" ")&&c.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),j.appendChild(Y),e.appendChild(U);let Qe=()=>{var pe,je,qe,rt,Tt,Z,Me,Kt,Xt,Pn,Hn,cs,ze,Bn,hn,fn;let l=(je=(pe=t.launcher)==null?void 0:pe.sidebarMode)!=null?je:!1,c=l||((rt=(qe=t.launcher)==null?void 0:qe.fullHeight)!=null?rt:!1),A=(Tt=t.theme)!=null?Tt:{},P=(Me=(Z=t.launcher)==null?void 0:Z.position)!=null?Me:"bottom-left",b=P==="bottom-left"||P==="top-left",Q=l?"none":"1px solid var(--tvw-cw-border)",ue=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)",T=l?"0":"16px",ee=(Kt=A.panelBorder)!=null?Kt:Q,G=(Xt=A.panelShadow)!=null?Xt:ue,ve=(Pn=A.panelBorderRadius)!=null?Pn:T;e.style.cssText="",U.style.cssText="",j.style.cssText="",Y.style.cssText="",H.style.cssText="",ut.style.cssText="";let N=(cs=(Hn=t==null?void 0:t.launcher)==null?void 0:Hn.width)!=null?cs:t==null?void 0:t.launcherWidth,Fe=N!=null?N:"min(400px, calc(100vw - 24px))";l||(j.style.width=Fe,j.style.maxWidth=Fe),j.style.boxShadow=G,j.style.borderRadius=ve,Y.style.border=ee,Y.style.borderRadius=ve;let Ae=((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",U.style.display="flex",U.style.flexDirection="column",U.style.flex="1 1 0%",U.style.minHeight="0",U.style.maxHeight="100%",U.style.height="100%",Ae&&(U.style.overflow="hidden"),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%",j.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",H.style.flex="1 1 0%",H.style.minHeight="0",H.style.overflowY="auto",ut.style.flexShrink="0"),U.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!Ae&&((Bn=Wt[P])!=null?Bn:Wt["bottom-right"]).split(" ").forEach(wn=>U.classList.add(wn)),l){let Ut=(fn=(hn=t.launcher)==null?void 0:hn.sidebarWidth)!=null?fn:"420px";U.style.cssText=`
21
+ position: fixed !important;
22
+ top: 0 !important;
23
+ bottom: 0 !important;
24
+ width: ${Ut} !important;
25
+ height: 100vh !important;
26
+ max-height: 100vh !important;
27
+ margin: 0 !important;
28
+ padding: 0 !important;
29
+ display: flex !important;
30
+ flex-direction: column !important;
31
+ ${b?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,j.style.cssText=`
33
+ position: relative !important;
34
+ display: flex !important;
35
+ flex-direction: column !important;
36
+ flex: 1 1 0% !important;
37
+ width: 100% !important;
38
+ max-width: 100% !important;
39
+ height: 100% !important;
40
+ min-height: 0 !important;
41
+ margin: 0 !important;
42
+ padding: 0 !important;
43
+ box-shadow: ${G} !important;
44
+ border-radius: ${ve} !important;
45
+ `,j.style.setProperty("width","100%","important"),j.style.setProperty("max-width","100%","important"),Y.style.cssText=`
46
+ display: flex !important;
47
+ flex-direction: column !important;
48
+ flex: 1 1 0% !important;
49
+ width: 100% !important;
50
+ height: 100% !important;
51
+ min-height: 0 !important;
52
+ max-height: 100% !important;
53
+ overflow: hidden !important;
54
+ border-radius: ${ve} !important;
55
+ border: ${ee} !important;
56
+ `,ut.style.cssText=`
57
+ flex-shrink: 0 !important;
58
+ border-top: none !important;
59
+ padding: 8px 16px 12px 16px !important;
60
+ `}if(!Ae){let Ut="max-height: -moz-available !important; max-height: stretch !important;",wn=l?"":"padding-top: 1.25em !important;";U.style.cssText+=Ut+wn}};Qe(),Kn(e,t);let He=[],Ye=null,kt=()=>{Ye&&(Ye(),Ye=null),t.colorScheme==="auto"&&(Ye=Xr(()=>{Kn(e,t)}))};kt(),He.push(()=>{Ye&&(Ye(),Ye=null)});let ft=oi(Pe),ot=null,$,wt=!1,yt=!0,At=0,te=0,ye=null,Re=!1,vt=0,Ze=!1,Bt=125,It=2e3,Nt=5,tn=50,Ot=new Map,We={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1},pn=(Ks=(Ys=t.voiceRecognition)==null?void 0:Ys.autoResume)!=null?Ks:!1,gn=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}}))},Wn=()=>{var P,b;if(((P=t.voiceRecognition)==null?void 0:P.enabled)===!1)return;let l=Ms(a.voiceState),c=!!l.active,A=Number((b=l.timestamp)!=null?b:0);We.manuallyDeactivated=!!l.manuallyDeactivated,c&&Date.now()-A<Zi&&setTimeout(()=>{We.active||(We.manuallyDeactivated=!1,_e("restore"))},1e3)},Ln=()=>$?ci($.getMessages()).filter(l=>!l.__skipPersist):[];function mn(l){if(!(i!=null&&i.save))return;let A={messages:l?ci(l):$?Ln():[],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();Re&&c<vt&&!l||(Re&&c>=vt&&(Re=!1),!(!l&&!wt)&&(c-te<Bt||(te=c,ye&&cancelAnimationFrame(ye),ye=requestAnimationFrame(()=>{Re||!yt||(Ze=!0,H.scrollTop=H.scrollHeight,At=H.scrollTop,requestAnimationFrame(()=>{Ze=!1}),ye=null)}))))},L=null,le=()=>U.querySelector("#persona-scroll-container")||H,Se=(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 T=performance.now(),ee=ve=>1-Math.pow(1-ve,3),G=ve=>{let N=l.scrollHeight;N!==b&&(b=N,Q=b-A);let Fe=ve-T,Ae=Math.min(Fe/c,1),pe=ee(Ae),je=A+Q*pe;l.scrollTop=je,Ae<1?L=requestAnimationFrame(G):(l.scrollTop=l.scrollHeight,L=null)};L=requestAnimationFrame(G)},De=l=>{let c=new Map;l.forEach(A=>{let P=Ot.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)}),Ot.clear(),c.forEach((A,P)=>{Ot.set(P,A)})},Ke=(l,c,A)=>{let P=document.createElement("div");c.forEach(T=>{var Fe,Ae;let ee=null,G=r.find(pe=>!!(T.variant==="reasoning"&&pe.renderReasoning||T.variant==="tool"&&pe.renderToolCall||!T.variant&&pe.renderMessage)),ve=(Fe=t.layout)==null?void 0:Fe.messages;if(G)if(T.variant==="reasoning"&&T.reasoning&&G.renderReasoning){if(!O)return;ee=G.renderReasoning({message:T,defaultRenderer:()=>vs(T),config:t})}else if(T.variant==="tool"&&T.toolCall&&G.renderToolCall){if(!C)return;ee=G.renderToolCall({message:T,defaultRenderer:()=>bs(T,t),config:t})}else G.renderMessage&&(ee=G.renderMessage({message:T,defaultRenderer:()=>{let pe=rn(T,A,ve,t.messageActions,k);return T.role!=="user"&&Cs(pe,T,t,$),pe},config:t}));if(!ee&&T.role==="assistant"&&!T.variant&&t.enableComponentStreaming!==!1&&es(T)){let je=ts(T);if(je){let qe=Zn(je,{config:t,message:T,transform:A});if(qe){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-${T.id}`,rt.setAttribute("data-message-id",T.id),T.content&&T.content.trim()){let Tt=document.createElement("div");Tt.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",Tt.innerHTML=A({text:T.content,message:T,streaming:!!T.streaming,raw:T.rawContent}),rt.appendChild(Tt)}rt.appendChild(qe),ee=rt}}}if(!ee)if(T.variant==="reasoning"&&T.reasoning){if(!O)return;ee=vs(T)}else if(T.variant==="tool"&&T.toolCall){if(!C)return;ee=bs(T,t)}else{let pe=(Ae=t.layout)==null?void 0:Ae.messages;pe!=null&&pe.renderUserMessage&&T.role==="user"?ee=pe.renderUserMessage({message:T,config:t,streaming:!!T.streaming}):pe!=null&&pe.renderAssistantMessage&&T.role==="assistant"?ee=pe.renderAssistantMessage({message:T,config:t,streaming:!!T.streaming}):ee=rn(T,A,pe,t.messageActions,k),T.role!=="user"&&ee&&Cs(ee,T,t,$)}let N=document.createElement("div");N.className="tvw-flex",N.id=`wrapper-${T.id}`,N.setAttribute("data-wrapper-id",T.id),T.role==="user"&&N.classList.add("tvw-justify-end"),N.appendChild(ee),P.appendChild(N)});let b=c.some(T=>T.role==="assistant"&&T.streaming),Q=c[c.length-1],ue=(Q==null?void 0:Q.role)==="assistant"&&!Q.streaming;if(wt&&c.some(T=>T.role==="user")&&!b&&!ue){let T=Tn(),ee=document.createElement("div");ee.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(" "),ee.setAttribute("data-typing-indicator","true"),ee.appendChild(T);let G=document.createElement("div");G.className="tvw-flex",G.id="wrapper-typing-indicator",G.setAttribute("data-wrapper-id","typing-indicator"),G.appendChild(ee),P.appendChild(G)}Gr(l,P),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let T=le();Se(T)})})},Le=()=>{h&&(I?(U.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),j.classList.remove("tvw-scale-95","tvw-opacity-0"),j.classList.add("tvw-scale-100","tvw-opacity-100"),se?se.element.style.display="none":de&&(de.style.display="none")):(U.classList.add("tvw-pointer-events-none","tvw-opacity-0"),j.classList.remove("tvw-scale-100","tvw-opacity-100"),j.classList.add("tvw-scale-95","tvw-opacity-0"),se?se.element.style.display="":de&&(de.style.display="")))},W=(l,c="user")=>{if(!h||I===l)return;let A=I;I=l,Le(),I&&(mt(),Yt(!0));let P={open:I,source:c,timestamp:Date.now()};I&&!A?s.emit("widget:opened",P):!I&&A&&s.emit("widget:closed",P),s.emit("widget:state",{open:I,launcherEnabled:h,voiceActive:We.active,streaming:$.isStreaming()})},bt=l=>{_.disabled=l,F&&(F.disabled=l),ft.buttons.forEach(c=>{c.disabled=l})},oe=()=>{var b,Q,ue,T,ee,G,ve,N,Fe,Ae,pe,je,qe,rt;Lt.textContent=(Q=(b=t.copy)==null?void 0:b.welcomeTitle)!=null?Q:"Hello \u{1F44B}",Ft.textContent=(T=(ue=t.copy)==null?void 0:ue.welcomeSubtitle)!=null?T:"Ask anything about your account or products.",V.placeholder=(G=(ee=t.copy)==null?void 0:ee.inputPlaceholder)!=null?G:"How can I help...",((N=(ve=t.sendButton)==null?void 0:ve.useIcon)!=null?N:!1)||(_.textContent=(Ae=(Fe=t.copy)==null?void 0:Fe.sendButtonLabel)!=null?Ae:"Send");let c=(je=(pe=t.theme)==null?void 0:pe.inputFontFamily)!=null?je:"sans-serif",A=(rt=(qe=t.theme)==null?void 0:qe.inputFontWeight)!=null?rt:"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'}};V.style.fontFamily=P(c),V.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}))}}),$=new nn(t,{onMessagesChanged(l){Ke(X,l,v),$&&(l.some(P=>P.role==="user")?ft.render([],$,V,l):ft.render(t.suggestionChips,$,V,l,t.suggestionChipsConfig)),Yt(!wt),De(l);let c=[...l].reverse().find(A=>A.role==="user");We.lastUserMessageWasVoice=!!(c!=null&&c.viaVoice),mn(l)},onStatusChanged(l){var P;let c=(P=t.statusIndicator)!=null?P:{},A=b=>{var Q,ue,T,ee;return b==="idle"?(Q=c.idleText)!=null?Q:gt.idle:b==="connecting"?(ue=c.connectingText)!=null?ue:gt.connecting:b==="connected"?(T=c.connectedText)!=null?T:gt.connected:b==="error"?(ee=c.errorText)!=null?ee:gt.error:gt[b]};lt.textContent=A(l)},onStreamingChanged(l){wt=l,bt(l),$&&Ke(X,$.getMessages(),v),l||Yt(!0)}}),d&&d.then(l=>{var c;l&&(l.metadata&&(a=Ms(l.metadata),w.syncFromMetadata()),(c=l.messages)!=null&&c.length&&$.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let B=l=>{var b;l.preventDefault();let c=V.value.trim(),A=(b=Te==null?void 0:Te.hasAttachments())!=null?b:!1;if(!c&&!A)return;let P;A&&(P=[],P.push(...Te.getContentParts()),c&&P.push(Un(c))),V.value="",V.style.height="auto",$.sendMessage(c,{contentParts:P}),A&&Te.clearAttachments()},E=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),_.click())},z=null,fe=!1,Ee=null,Xe=null,Ie=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,_e=(l="user")=>{var Q,ue,T,ee;if(fe||$.isStreaming())return;let c=Ie();if(!c)return;z=new c;let P=(ue=((Q=t.voiceRecognition)!=null?Q:{}).pauseDuration)!=null?ue:2e3;z.continuous=!0,z.interimResults=!0,z.lang="en-US";let b=V.value;z.onresult=G=>{let ve="",N="";for(let Ae=0;Ae<G.results.length;Ae++){let pe=G.results[Ae],je=pe[0].transcript;pe.isFinal?ve+=je+" ":N=je}let Fe=b+ve+N;V.value=Fe,Ee&&clearTimeout(Ee),(ve||N)&&(Ee=window.setTimeout(()=>{let Ae=V.value.trim();Ae&&z&&fe&&(ke(),V.value="",V.style.height="auto",$.sendMessage(Ae,{viaVoice:!0}))},P))},z.onerror=G=>{G.error!=="no-speech"&&ke()},z.onend=()=>{if(fe){let G=V.value.trim();G&&G!==b.trim()&&(V.value="",V.style.height="auto",$.sendMessage(G,{viaVoice:!0})),ke()}};try{if(z.start(),fe=!0,We.active=!0,l!=="system"&&(We.manuallyDeactivated=!1),gn(l),Dt(),F){Xe={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let G=(T=t.voiceRecognition)!=null?T:{},ve=(ee=G.recordingBackgroundColor)!=null?ee:"#ef4444",N=G.recordingIconColor,Fe=G.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=ve,N){F.style.color=N;let Ae=F.querySelector("svg");Ae&&Ae.setAttribute("stroke",N)}Fe&&(F.style.borderColor=Fe),F.setAttribute("aria-label","Stop voice recognition")}}catch{ke("system")}},ke=(l="user")=>{if(fe){if(fe=!1,Ee&&(clearTimeout(Ee),Ee=null),z){try{z.stop()}catch{}z=null}if(We.active=!1,gn(l),Dt(),F){if(F.classList.remove("tvw-voice-recording"),Xe){F.style.backgroundColor=Xe.backgroundColor,F.style.color=Xe.color,F.style.borderColor=Xe.borderColor;let c=F.querySelector("svg");c&&c.setAttribute("stroke",Xe.color||"currentColor"),Xe=null}F.setAttribute("aria-label","Start voice recognition")}}},Ce=(l,c)=>{var je,qe,rt,Tt,Z,Me,Kt;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let P=u("div","tvw-send-button-wrapper"),b=u("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=(je=l==null?void 0:l.iconName)!=null?je:"mic",ue=(qe=c==null?void 0:c.size)!=null?qe:"40px",T=(rt=l==null?void 0:l.iconSize)!=null?rt:ue,ee=parseFloat(T)||24,G=(Tt=l==null?void 0:l.backgroundColor)!=null?Tt:c==null?void 0:c.backgroundColor,ve=(Z=l==null?void 0:l.iconColor)!=null?Z:c==null?void 0:c.textColor;b.style.width=T,b.style.height=T,b.style.minWidth=T,b.style.minHeight=T,b.style.fontSize="18px",b.style.lineHeight="1";let N=ve||"currentColor",Fe=re(Q,ee,N,1.5);Fe?(b.appendChild(Fe),b.style.color=N):(b.textContent="\u{1F3A4}",b.style.color=N),G?b.style.backgroundColor=G:b.classList.add("tvw-bg-cw-primary"),ve?b.style.color=ve:!ve&&!(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 Ae=(Me=l==null?void 0:l.tooltipText)!=null?Me:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&Ae){let Xt=u("div","tvw-send-button-tooltip");Xt.textContent=Ae,P.appendChild(Xt)}return{micButton:b,micButtonWrapper:P}},xe=()=>{if(fe){let l=V.value.trim();We.manuallyDeactivated=!0,Dt(),ke("user"),l&&(V.value="",V.style.height="auto",$.sendMessage(l))}else We.manuallyDeactivated=!1,Dt(),_e("user")};F&&(F.addEventListener("click",xe),He.push(()=>{ke("system"),F&&F.removeEventListener("click",xe)}));let Ve=s.on("assistant:complete",()=>{pn&&(We.active||We.manuallyDeactivated||pn==="assistant"&&!We.lastUserMessageWasVoice||setTimeout(()=>{!We.active&&!We.manuallyDeactivated&&_e("auto")},600))});He.push(Ve);let ce=()=>{W(!I,"user")},se=null,de=null;if(h){let l=r.find(c=>c.renderLauncher);if(l!=null&&l.renderLauncher){let c=l.renderLauncher({config:t,defaultRenderer:()=>An(t,ce).element,onToggle:ce});c&&(de=c)}de||(se=An(t,ce))}se?e.appendChild(se.element):de&&e.appendChild(de),Le(),ft.render(t.suggestionChips,$,V,void 0,t.suggestionChipsConfig),oe(),bt($.isStreaming()),Yt(!0),Wn();let mt=()=>{var A,P,b,Q,ue,T,ee,G;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){j.style.height="",j.style.width="";return}if(!l){let ve=(T=(ue=t==null?void 0:t.launcher)==null?void 0:ue.width)!=null?T:t==null?void 0:t.launcherWidth,N=ve!=null?ve:"min(400px, calc(100vw - 24px))";j.style.width=N,j.style.maxWidth=N}if(!c){let ve=window.innerHeight,N=64,Fe=(G=(ee=t.launcher)==null?void 0:ee.heightOffset)!=null?G:0,Ae=Math.max(200,ve-N),pe=Math.min(640,Ae),je=Math.max(200,pe-Fe);j.style.height=`${je}px`}};mt(),window.addEventListener("resize",mt),He.push(()=>window.removeEventListener("resize",mt)),At=H.scrollTop;let Ps=()=>{let l=H.scrollTop,c=H.scrollHeight,A=H.clientHeight,P=c-l-A,b=Math.abs(l-At);if(At=l,!Ze&&!(b<=Nt)){if(!yt&&P<tn){Re=!1,yt=!0;return}yt&&P>tn&&(Re=!0,vt=Date.now()+It,yt=!1)}};H.addEventListener("scroll",Ps,{passive:!0}),He.push(()=>H.removeEventListener("scroll",Ps)),He.push(()=>{ye&&cancelAnimationFrame(ye)});let Hs=()=>{q&&(ot&&(q.removeEventListener("click",ot),ot=null),h?(q.style.display="",ot=()=>{I=!1,Le()},q.addEventListener("click",ot)):q.style.display="none")};Hs(),(()=>{let{clearChatButton:l}=D;l&&l.addEventListener("click",()=>{$.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(A){console.error("[AgentWidget] Failed to clear default localStorage:",A)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)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()})})(),at.addEventListener("submit",B),V.addEventListener("keydown",E),He.push(()=>{at.removeEventListener("submit",B),V.removeEventListener("keydown",E)}),He.push(()=>{$.cancel()}),se?He.push(()=>{se==null||se.destroy()}):de&&He.push(()=>{de==null||de.remove()});let _t={update(l){var Vs,Gs,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,Eo,Mo,ko,Wo,Lo,Po,Ho,Bo,Io,Ro,Fo,$o,No,Oo,Do,_o,jo,qo,zo,Uo,Jo,Yo,Ko,Xo,Vo,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;let c=t.toolCall,A=t.colorScheme;t={...t,...l},Qe(),Kn(e,t),t.colorScheme!==A&&kt();let P=En.getForInstance(t.plugins);if(r.length=0,r.push(...P),h=(Gs=(Vs=t.launcher)==null?void 0:Vs.enabled)!=null?Gs:!0,R=(Zs=(Qs=t.launcher)==null?void 0:Qs.autoExpand)!=null?Zs:!1,O=(to=(eo=t.features)==null?void 0:eo.showReasoning)!=null?to:!0,C=(so=(no=t.features)==null?void 0:no.showToolCalls)!=null?so:!0,((oo=t.launcher)==null?void 0:oo.enabled)===!1&&se&&(se.destroy(),se=null),((ro=t.launcher)==null?void 0:ro.enabled)===!1&&de&&(de.remove(),de=null),((io=t.launcher)==null?void 0:io.enabled)!==!1&&!se&&!de){let x=r.find(ge=>ge.renderLauncher);if(x!=null&&x.renderLauncher){let ge=x.renderLauncher({config:t,defaultRenderer:()=>An(t,ce).element,onToggle:ce});ge&&(de=ge,e.appendChild(de))}de||(se=An(t,ce),e.appendChild(se.element))}se&&se.update(t),dt&&((ao=t.launcher)==null?void 0:ao.title)!==void 0&&(dt.textContent=t.launcher.title),ct&&((lo=t.launcher)==null?void 0:lo.subtitle)!==void 0&&(ct.textContent=t.launcher.subtitle);let b=(co=t.layout)==null?void 0:co.header;if((b==null?void 0:b.layout)!==S&&Ue){let x=b?sn(t,b,{showClose:h,onClose:()=>W(!1,"user")}):qt({config:t,showClose:h,onClose:()=>W(!1,"user")});Ue.replaceWith(x.header),Ue=x.header,we=x.iconHolder,dt=x.headerTitle,ct=x.headerSubtitle,q=x.closeButton,S=b==null?void 0:b.layout}else if(b&&(we&&(we.style.display=b.showIcon===!1?"none":""),dt&&(dt.style.display=b.showTitle===!1?"none":""),ct&&(ct.style.display=b.showSubtitle===!1?"none":""),q&&(q.style.display=b.showCloseButton===!1?"none":""),D.clearChatButtonWrapper)){let x=b.showClearChat;if(x!==void 0){D.clearChatButtonWrapper.style.display=x?"":"none";let{closeButtonWrapper:ge}=D;ge&&!ge.classList.contains("tvw-absolute")&&(x?ge.classList.remove("tvw-ml-auto"):ge.classList.add("tvw-ml-auto"))}}let ue=((uo=t.layout)==null?void 0:uo.showHeader)!==!1;Ue&&(Ue.style.display=ue?"":"none");let T=((po=t.layout)==null?void 0:po.showFooter)!==!1;ut&&(ut.style.display=T?"":"none"),h!==y?h?W(R,"auto"):(I=!0,Le()):R!==M&&W(R,"auto"),M=R,y=h,mt(),Hs(),JSON.stringify(l.toolCall)!==JSON.stringify(c)&&$&&Ke(X,$.getMessages(),v);let N=(go=t.launcher)!=null?go:{},Fe=(mo=N.headerIconHidden)!=null?mo:!1,Ae=(fo=(ho=t.layout)==null?void 0:ho.header)==null?void 0:fo.showIcon,pe=Fe||Ae===!1,je=N.headerIconName,qe=(wo=N.headerIconSize)!=null?wo:"48px";if(we){let x=Y.querySelector(".tvw-border-b-cw-divider"),ge=x==null?void 0:x.querySelector(".tvw-flex-col");if(pe)we.style.display="none",x&&ge&&!x.contains(ge)&&x.insertBefore(ge,x.firstChild);else{if(we.style.display="",we.style.height=qe,we.style.width=qe,x&&ge&&(x.contains(we)?we.nextSibling!==ge&&(we.remove(),x.insertBefore(we,ge)):x.insertBefore(we,ge)),je){let ne=parseFloat(qe)||24,be=re(je,ne*.6,"#ffffff",2);be?we.replaceChildren(be):we.textContent=(yo=N.agentIconText)!=null?yo:"\u{1F4AC}"}else if(N.iconUrl){let ne=we.querySelector("img");if(ne)ne.src=N.iconUrl,ne.style.height=qe,ne.style.width=qe;else{let be=document.createElement("img");be.src=N.iconUrl,be.alt="",be.className="tvw-rounded-xl tvw-object-cover",be.style.height=qe,be.style.width=qe,we.replaceChildren(be)}}else{let ne=we.querySelector("svg"),be=we.querySelector("img");(ne||be)&&we.replaceChildren(),we.textContent=(vo=N.agentIconText)!=null?vo:"\u{1F4AC}"}let $e=we.querySelector("img");$e&&($e.style.height=qe,$e.style.width=qe)}}let rt=(Co=(bo=t.layout)==null?void 0:bo.header)==null?void 0:Co.showTitle,Tt=(So=(xo=t.layout)==null?void 0:xo.header)==null?void 0:So.showSubtitle;if(dt&&(dt.style.display=rt===!1?"none":""),ct&&(ct.style.display=Tt===!1?"none":""),q){((To=(Ao=t.layout)==null?void 0:Ao.header)==null?void 0:To.showCloseButton)===!1?q.style.display="none":q.style.display="";let ge=(Eo=N.closeButtonSize)!=null?Eo:"32px",$e=(Mo=N.closeButtonPlacement)!=null?Mo:"inline";q.style.height=ge,q.style.width=ge;let{closeButtonWrapper:ne}=D,be=$e==="top-right",pt=ne==null?void 0:ne.classList.contains("tvw-absolute");if(ne&&be!==pt)if(ne.remove(),be)ne.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Y.style.position="relative",Y.appendChild(ne);else{let ie=(Wo=(ko=N.clearChat)==null?void 0:ko.placement)!=null?Wo:"inline",Ge=(Po=(Lo=N.clearChat)==null?void 0:Lo.enabled)!=null?Po:!0;ne.className=Ge&&ie==="inline"?"":"tvw-ml-auto";let Ct=Y.querySelector(".tvw-border-b-cw-divider");Ct&&Ct.appendChild(ne)}if(N.closeButtonColor?(q.style.color=N.closeButtonColor,q.classList.remove("tvw-text-cw-muted")):(q.style.color="",q.classList.add("tvw-text-cw-muted")),N.closeButtonBackgroundColor?(q.style.backgroundColor=N.closeButtonBackgroundColor,q.classList.remove("hover:tvw-bg-gray-100")):(q.style.backgroundColor="",q.classList.add("hover:tvw-bg-gray-100")),N.closeButtonBorderWidth||N.closeButtonBorderColor){let ie=N.closeButtonBorderWidth||"0px",Ge=N.closeButtonBorderColor||"transparent";q.style.border=`${ie} solid ${Ge}`,q.classList.remove("tvw-border-none")}else q.style.border="",q.classList.add("tvw-border-none");N.closeButtonBorderRadius?(q.style.borderRadius=N.closeButtonBorderRadius,q.classList.remove("tvw-rounded-full")):(q.style.borderRadius="",q.classList.add("tvw-rounded-full")),N.closeButtonPaddingX?(q.style.paddingLeft=N.closeButtonPaddingX,q.style.paddingRight=N.closeButtonPaddingX):(q.style.paddingLeft="",q.style.paddingRight=""),N.closeButtonPaddingY?(q.style.paddingTop=N.closeButtonPaddingY,q.style.paddingBottom=N.closeButtonPaddingY):(q.style.paddingTop="",q.style.paddingBottom="");let it=(Ho=N.closeButtonIconName)!=null?Ho:"x",Et=(Bo=N.closeButtonIconText)!=null?Bo:"\xD7";q.innerHTML="";let ht=re(it,"20px",N.closeButtonColor||"",2);ht?q.appendChild(ht):q.textContent=Et;let Ne=(Io=N.closeButtonTooltipText)!=null?Io:"Close chat",Mt=(Ro=N.closeButtonShowTooltip)!=null?Ro:!0;if(q.setAttribute("aria-label",Ne),ne&&(ne._cleanupTooltip&&(ne._cleanupTooltip(),delete ne._cleanupTooltip),Mt&&Ne)){let ie=null,Ge=()=>{if(ie||!q)return;ie=u("div","tvw-clear-chat-tooltip"),ie.textContent=Ne;let Cn=u("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=q.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};ne.addEventListener("mouseenter",Ge),ne.addEventListener("mouseleave",Ct),q.addEventListener("focus",Ge),q.addEventListener("blur",Ct),ne._cleanupTooltip=()=>{Ct(),ne&&(ne.removeEventListener("mouseenter",Ge),ne.removeEventListener("mouseleave",Ct)),q&&(q.removeEventListener("focus",Ge),q.removeEventListener("blur",Ct))}}}let{clearChatButton:Z,clearChatButtonWrapper:Me}=D;if(Z){let x=(Fo=N.clearChat)!=null?Fo:{},ge=($o=x.enabled)!=null?$o:!0,$e=(Oo=(No=t.layout)==null?void 0:No.header)==null?void 0:Oo.showClearChat,ne=$e!==void 0?$e:ge,be=(Do=x.placement)!=null?Do:"inline";if(Me){Me.style.display=ne?"":"none";let{closeButtonWrapper:pt}=D;pt&&!pt.classList.contains("tvw-absolute")&&(ne?pt.classList.remove("tvw-ml-auto"):pt.classList.add("tvw-ml-auto"));let it=be==="top-right",Et=Me.classList.contains("tvw-absolute");if(it!==Et&&ne){if(Me.remove(),it)Me.className="tvw-absolute tvw-top-4 tvw-z-50",Me.style.right="48px",Y.style.position="relative",Y.appendChild(Me);else{Me.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Me.style.right="";let Ne=Y.querySelector(".tvw-border-b-cw-divider"),Mt=D.closeButtonWrapper;Ne&&Mt&&Mt.parentElement===Ne?Ne.insertBefore(Me,Mt):Ne&&Ne.appendChild(Me)}let ht=D.closeButtonWrapper;ht&&!ht.classList.contains("tvw-absolute")&&(it?ht.classList.add("tvw-ml-auto"):ht.classList.remove("tvw-ml-auto"))}}if(ne){let pt=(_o=x.size)!=null?_o:"32px";Z.style.height=pt,Z.style.width=pt;let it=(jo=x.iconName)!=null?jo:"refresh-cw",Et=(qo=x.iconColor)!=null?qo:"";Z.innerHTML="";let ht=re(it,"20px",Et||"",2);if(ht&&Z.appendChild(ht),Et?(Z.style.color=Et,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),x.backgroundColor?(Z.style.backgroundColor=x.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),x.borderWidth||x.borderColor){let ie=x.borderWidth||"0px",Ge=x.borderColor||"transparent";Z.style.border=`${ie} solid ${Ge}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");x.borderRadius?(Z.style.borderRadius=x.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),x.paddingX?(Z.style.paddingLeft=x.paddingX,Z.style.paddingRight=x.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),x.paddingY?(Z.style.paddingTop=x.paddingY,Z.style.paddingBottom=x.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let Ne=(zo=x.tooltipText)!=null?zo:"Clear chat",Mt=(Uo=x.showTooltip)!=null?Uo:!0;if(Z.setAttribute("aria-label",Ne),Me&&(Me._cleanupTooltip&&(Me._cleanupTooltip(),delete Me._cleanupTooltip),Mt&&Ne)){let ie=null,Ge=()=>{if(ie||!Z)return;ie=u("div","tvw-clear-chat-tooltip"),ie.textContent=Ne;let Cn=u("div");Cn.className="tvw-clear-chat-tooltip-arrow",ie.appendChild(Cn);let Vt=Z.getBoundingClientRect();ie.style.position="fixed",ie.style.left=`${Vt.left+Vt.width/2}px`,ie.style.top=`${Vt.top-8}px`,ie.style.transform="translate(-50%, -100%)",document.body.appendChild(ie)},Ct=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};Me.addEventListener("mouseenter",Ge),Me.addEventListener("mouseleave",Ct),Z.addEventListener("focus",Ge),Z.addEventListener("blur",Ct),Me._cleanupTooltip=()=>{Ct(),Me&&(Me.removeEventListener("mouseenter",Ge),Me.removeEventListener("mouseleave",Ct)),Z&&(Z.removeEventListener("focus",Ge),Z.removeEventListener("blur",Ct))}}}}let Kt=t.actionParsers&&t.actionParsers.length?t.actionParsers:[Mn],Xt=t.actionHandlers&&t.actionHandlers.length?t.actionHandlers:[en.message,en.messageAndClick];w=kn({parsers:Kt,handlers:Xt,getSessionMetadata:p,updateSessionMetadata:f,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),v=ui(t,w),$.updateConfig(t),Ke(X,$.getMessages(),v),ft.render(t.suggestionChips,$,V,void 0,t.suggestionChipsConfig),oe(),bt($.isStreaming());let Pn=((Jo=t.voiceRecognition)==null?void 0:Jo.enabled)===!0,Hn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(Pn&&Hn)if(!F||!Oe){let x=Ce(t.voiceRecognition,t.sendButton);x&&(F=x.micButton,Oe=x.micButtonWrapper,Ht.insertBefore(Oe,tt),F.addEventListener("click",xe),F.disabled=$.isStreaming())}else{let x=(Yo=t.voiceRecognition)!=null?Yo:{},ge=(Ko=t.sendButton)!=null?Ko:{},$e=(Xo=x.iconName)!=null?Xo:"mic",ne=(Vo=ge.size)!=null?Vo:"40px",be=(Go=x.iconSize)!=null?Go:ne,pt=parseFloat(be)||24;F.style.width=be,F.style.height=be,F.style.minWidth=be,F.style.minHeight=be;let it=(Zo=(Qo=x.iconColor)!=null?Qo:ge.textColor)!=null?Zo:"currentColor";F.innerHTML="";let Et=re($e,pt,it,2);Et?F.appendChild(Et):F.textContent="\u{1F3A4}";let ht=(er=x.backgroundColor)!=null?er:ge.backgroundColor;ht?(F.style.backgroundColor=ht,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&&!ge.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 Ne=Oe==null?void 0:Oe.querySelector(".tvw-send-button-tooltip"),Mt=(tr=x.tooltipText)!=null?tr:"Start voice recognition";if(((nr=x.showTooltip)!=null?nr:!1)&&Mt)if(Ne)Ne.textContent=Mt,Ne.style.display="";else{let Ge=document.createElement("div");Ge.className="tvw-send-button-tooltip",Ge.textContent=Mt,Oe==null||Oe.insertBefore(Ge,F)}else Ne&&(Ne.style.display="none");Oe.style.display="",F.disabled=$.isStreaming()}else F&&Oe&&(Oe.style.display="none",fe&&ke());if(((sr=t.attachments)==null?void 0:sr.enabled)===!0)if(!nt||!me){let x=(or=t.attachments)!=null?or:{},$e=(ir=((rr=t.sendButton)!=null?rr:{}).size)!=null?ir:"40px";st||(st=u("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),st.style.display="none",at.insertBefore(st,V)),he||(he=document.createElement("input"),he.type="file",he.accept=((ar=x.allowedTypes)!=null?ar:Jt).join(","),he.multiple=((lr=x.maxFiles)!=null?lr:4)>1,he.style.display="none",he.setAttribute("aria-label","Attach files"),at.insertBefore(he,V)),nt=u("div","tvw-send-button-wrapper"),me=u("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),me.type="button",me.setAttribute("aria-label",(dr=x.buttonTooltipText)!=null?dr:"Attach file");let ne=(cr=x.buttonIconName)!=null?cr:"paperclip",be=$e,pt=parseFloat(be)||40,it=Math.round(pt*.6);me.style.width=be,me.style.height=be,me.style.minWidth=be,me.style.minHeight=be,me.style.fontSize="18px",me.style.lineHeight="1",me.style.backgroundColor="transparent",me.style.color="var(--cw-primary, #111827)",me.style.border="none",me.style.borderRadius="6px",me.style.transition="background-color 0.15s ease",me.addEventListener("mouseenter",()=>{me.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),me.addEventListener("mouseleave",()=>{me.style.backgroundColor="transparent"});let Et=re(ne,it,"currentColor",1.5);Et?me.appendChild(Et):me.textContent="\u{1F4CE}",me.addEventListener("click",Mt=>{Mt.preventDefault(),he==null||he.click()}),nt.appendChild(me);let ht=(ur=x.buttonTooltipText)!=null?ur:"Attach file",Ne=u("div","tvw-send-button-tooltip");Ne.textContent=ht,nt.appendChild(Ne),Pt.append(nt),!Te&&he&&st&&(Te=Qt.fromConfig(x),Te.setPreviewsContainer(st),he.addEventListener("change",async()=>{Te&&(he!=null&&he.files)&&(await Te.handleFileSelect(he.files),he.value="")}))}else{nt.style.display="";let x=(pr=t.attachments)!=null?pr:{};he&&(he.accept=((gr=x.allowedTypes)!=null?gr:Jt).join(","),he.multiple=((mr=x.maxFiles)!=null?mr:4)>1),Te&&Te.updateConfig({allowedTypes:x.allowedTypes,maxFileSize:x.maxFileSize,maxFiles:x.maxFiles})}else nt&&(nt.style.display="none"),Te&&Te.clearAttachments();let ze=(hr=t.sendButton)!=null?hr:{},Bn=(fr=ze.useIcon)!=null?fr:!1,hn=(wr=ze.iconText)!=null?wr:"\u2191",fn=ze.iconName,Ut=(yr=ze.tooltipText)!=null?yr:"Send message",wn=(vr=ze.showTooltip)!=null?vr:!1,yn=(br=ze.size)!=null?br:"40px",In=ze.backgroundColor,Rt=ze.textColor;if(Bn){if(_.style.width=yn,_.style.height=yn,_.style.minWidth=yn,_.style.minHeight=yn,_.style.fontSize="18px",_.style.lineHeight="1",_.innerHTML="",fn){let x=parseFloat(yn)||24,ge=Rt&&typeof Rt=="string"&&Rt.trim()?Rt.trim():"currentColor",$e=re(fn,x,ge,2);$e?(_.appendChild($e),_.style.color=ge):(_.textContent=hn,Rt?_.style.color=Rt:_.classList.add("tvw-text-white"))}else _.textContent=hn,Rt?_.style.color=Rt:_.classList.add("tvw-text-white");_.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",In?(_.style.backgroundColor=In,_.classList.remove("tvw-bg-cw-primary")):_.classList.add("tvw-bg-cw-primary")}else _.textContent=(xr=(Cr=t.copy)==null?void 0:Cr.sendButtonLabel)!=null?xr:"Send",_.style.width="",_.style.height="",_.style.minWidth="",_.style.minHeight="",_.style.fontSize="",_.style.lineHeight="",_.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",In?(_.style.backgroundColor=In,_.classList.remove("tvw-bg-cw-accent")):_.classList.add("tvw-bg-cw-accent"),Rt?_.style.color=Rt:_.classList.add("tvw-text-white");ze.borderWidth?(_.style.borderWidth=ze.borderWidth,_.style.borderStyle="solid"):(_.style.borderWidth="",_.style.borderStyle=""),ze.borderColor?_.style.borderColor=ze.borderColor:_.style.borderColor="",ze.paddingX?(_.style.paddingLeft=ze.paddingX,_.style.paddingRight=ze.paddingX):(_.style.paddingLeft="",_.style.paddingRight=""),ze.paddingY?(_.style.paddingTop=ze.paddingY,_.style.paddingBottom=ze.paddingY):(_.style.paddingTop="",_.style.paddingBottom="");let vn=tt==null?void 0:tt.querySelector(".tvw-send-button-tooltip");if(wn&&Ut)if(vn)vn.textContent=Ut,vn.style.display="";else{let x=document.createElement("div");x.className="tvw-send-button-tooltip",x.textContent=Ut,tt==null||tt.insertBefore(x,_)}else vn&&(vn.style.display="none");let bn=(Sr=t.statusIndicator)!=null?Sr:{},vi=(Ar=bn.visible)!=null?Ar:!0;if(lt.style.display=vi?"":"none",$){let x=$.getStatus(),ge=$e=>{var ne,be,pt,it;return $e==="idle"?(ne=bn.idleText)!=null?ne:gt.idle:$e==="connecting"?(be=bn.connectingText)!=null?be:gt.connecting:$e==="connected"?(pt=bn.connectedText)!=null?pt:gt.connected:$e==="error"?(it=bn.errorText)!=null?it:gt.error:gt[$e]};lt.textContent=ge(x)}},open(){h&&W(!0,"api")},close(){h&&W(!1,"api")},toggle(){h&&W(!I,"api")},clearChat(){$.clearMessages();try{localStorage.removeItem(un),t.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${un}`)}catch(c){console.error("[AgentWidget] Failed to clear default localStorage:",c)}if(t.clearChatHistoryStorageKey&&t.clearChatHistoryStorageKey!==un)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!V||$.isStreaming()?!1:(!I&&h&&W(!0,"system"),V.value=l,V.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let c=(l==null?void 0:l.trim())||V.value.trim();return c?(!I&&h&&W(!0,"system"),V.value="",V.style.height="auto",$.sendMessage(c),!0):!1},startVoiceRecognition(){return fe||$.isStreaming()||!Ie()?!1:(!I&&h&&W(!0,"system"),We.manuallyDeactivated=!1,Dt(),_e("user"),!0)},stopVoiceRecognition(){return fe?(We.manuallyDeactivated=!0,Dt(),ke("user"),!0):!1},injectTestMessage(l){!I&&h&&W(!0,"system"),$.injectTestEvent(l)},getMessages(){return $.getMessages()},getStatus(){return $.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:$.isStreaming()}},showCSATFeedback(l){!I&&h&&W(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ns({onSubmit:async(P,b)=>{var Q;$.isClientTokenMode()&&await $.submitCSATFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&h&&W(!0,"system");let c=X.querySelector(".tvw-feedback-container");c&&c.remove();let A=ss({onSubmit:async(P,b)=>{var Q;$.isClientTokenMode()&&await $.submitNPSFeedback(P,b),(Q=l==null?void 0:l.onSubmit)==null||Q.call(l,P,b)},onDismiss:l==null?void 0:l.onDismiss,...l});X.appendChild(A),A.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,c){return $.submitCSATFeedback(l,c)},async submitNPSFeedback(l,c){return $.submitNPSFeedback(l,c)},destroy(){He.forEach(l=>l()),U.remove(),se==null||se.destroy(),de==null||de.remove(),ot&&q.removeEventListener("click",ot)}};if((((Xs=o==null?void 0:o.debugTools)!=null?Xs:!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:A=>A?_t.startVoiceRecognition():_t.stopVoiceRecognition()};window.AgentWidgetBrowser=c,He.push(()=>{window.AgentWidgetBrowser===c&&(window.AgentWidgetBrowser=l)})}return _t};var ks={},ea=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},ta=()=>{try{if(typeof ks!="undefined"&&ks.url)return new URL("../widget.css",ks.url).href}catch{}return null},pi=e=>{let n=ta(),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)}},Ws=e=>{var p,f,m,g;let n=ea(e.target),o=document.createElement("div");o.className="persona-host";let t=(m=(f=(p=e.config)==null?void 0:p.launcher)==null?void 0:f.enabled)!=null?m:!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),pi(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),pi(o);let a=os(s,e.config,{debugTools:e.debugTools});(g=e.onReady)==null||g.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};function zt(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function na(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 gi=`({ text, message }: any) => {
61
+ const jsonSource = (message as any).rawContent || text || message.content;
62
+ if (!jsonSource || typeof jsonSource !== 'string') return null;
63
+ let cleanJson = jsonSource
64
+ .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
65
+ .replace(/\\n?\`\`\`\\s*$/, '')
66
+ .trim();
67
+ if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
68
+ try {
69
+ const parsed = JSON.parse(cleanJson);
70
+ if (parsed.action) return { type: parsed.action, payload: parsed };
71
+ } catch (e) { return null; }
72
+ return null;
73
+ }`,mi=`function(ctx) {
74
+ var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
+ if (!jsonSource || typeof jsonSource !== 'string') return null;
76
+ var cleanJson = jsonSource
77
+ .replace(/^\`\`\`(?:json)?\\s*\\n?/, '')
78
+ .replace(/\\n?\`\`\`\\s*$/, '')
79
+ .trim();
80
+ if (!cleanJson.startsWith('{') || !cleanJson.endsWith('}')) return null;
81
+ try {
82
+ var parsed = JSON.parse(cleanJson);
83
+ if (parsed.action) return { type: parsed.action, payload: parsed };
84
+ } catch (e) { return null; }
85
+ return null;
86
+ }`,hi=`(action: any, context: any) => {
87
+ if (action.type !== 'nav_then_click') return;
88
+ const payload = action.payload || action.raw || {};
89
+ const url = payload?.page;
90
+ const text = payload?.on_load_text || 'Navigating...';
91
+ if (!url) return { handled: true, displayText: text };
92
+ const messageId = context.message?.id;
93
+ const processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
94
+ const actionKey = \`nav_\${messageId}_\${url}\`;
95
+ if (processedActions.includes(actionKey)) {
96
+ return { handled: true, displayText: text };
97
+ }
98
+ processedActions.push(actionKey);
99
+ localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
100
+ const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
+ window.location.href = targetUrl;
102
+ return { handled: true, displayText: text };
103
+ }`,fi=`function(action, context) {
104
+ if (action.type !== 'nav_then_click') return;
105
+ var payload = action.payload || action.raw || {};
106
+ var url = payload.page;
107
+ var text = payload.on_load_text || 'Navigating...';
108
+ if (!url) return { handled: true, displayText: text };
109
+ var messageId = context.message ? context.message.id : null;
110
+ var processedActions = JSON.parse(localStorage.getItem(PROCESSED_ACTIONS_KEY) || '[]');
111
+ var actionKey = 'nav_' + messageId + '_' + url;
112
+ if (processedActions.includes(actionKey)) {
113
+ return { handled: true, displayText: text };
114
+ }
115
+ processedActions.push(actionKey);
116
+ localStorage.setItem(PROCESSED_ACTIONS_KEY, JSON.stringify(processedActions));
117
+ var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
+ window.location.href = targetUrl;
119
+ return { handled: true, displayText: text };
120
+ }`,sa=`(parsed: any) => {
121
+ if (!parsed || typeof parsed !== 'object') return null;
122
+ if (parsed.action === 'nav_then_click') return 'Navigating...';
123
+ if (parsed.action === 'message') return parsed.text || '';
124
+ if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
+ return parsed.text || null;
126
+ }`,oa=`function(parsed) {
127
+ if (!parsed || typeof parsed !== 'object') return null;
128
+ if (parsed.action === 'nav_then_click') return 'Navigating...';
129
+ if (parsed.action === 'message') return parsed.text || '';
130
+ if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
+ return parsed.text || null;
132
+ }`;function ra(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 rs(e){var n,o;return(o=(n=e.parserType)!=null?n:ra(e.streamParser))!=null?o:"plain"}function is(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 as(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 ls(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 ds(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,p])=>{d!=="format"&&(typeof p=="string"?o.push(`${n} ${d}: "${p}",`):typeof p=="boolean"&&o.push(`${n} ${d}: ${p},`))}),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 Ls(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 wi(e,n="esm",o){let t={...e};delete t.postprocessMessage,delete t.initialMessages;let r=o?{...o,hooks:na(o.hooks)}:void 0;return n==="esm"?ia(t,r):n==="script-installer"?da(t):n==="script-advanced"?ua(t,r):n==="react-component"?aa(t,r):n==="react-advanced"?la(t,r):ca(t,r)}function ia(e,n){let o=n==null?void 0:n.hooks,t=rs(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(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(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 aa(e,n){let o=n==null?void 0:n.hooks,t=rs(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(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(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 la(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(...is(e," ")),t.push(...as(e," ",o)),t.push(...ls(e," ")),t.push(...ds(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(${sa}),`)),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(` ${gi}`),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(` ${gi}`),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(` ${hi}`),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(` ${hi}`),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 yi(e){var r;let n=rs(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 p={};Object.entries(d).forEach(([f,m])=>{f!=="format"&&(typeof m=="string"||typeof m=="boolean")&&(p[f]=m)}),Object.keys(p).length>0&&(i.timestamp=p)}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 da(e){let n=yi(e);return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/install.global.js" data-config='${JSON.stringify(n,null,0).replace(/'/g,"&#39;")}'></script>`}function ca(e,n){let o=n==null?void 0:n.hooks,t=rs(e),r=t!=="plain",s=["<!-- Load CSS -->",'<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/dist/widget.css" />',"","<!-- Load JavaScript -->",'<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/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(...is(e," ")),s.push(...as(e," ",o)),s.push(...ls(e," ")),s.push(...ds(e," ")),s.push(...Ls(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 ua(e,n){let o=n==null?void 0:n.hooks,t=yi(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(t,null,2).split(`
137
+ `).map((i,a)=>a===0?i:" "+i).join(`
138
+ `)};`,""," // Constants"," var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@latest/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(${oa});`),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(` ${mi}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${mi}`),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(` ${fi}`),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(` ${fi}`),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 pa=Ws;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,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
+ //# sourceMappingURL=index.cjs.map