@runtypelabs/persona 1.47.0 → 1.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -1,10 +1,10 @@
1
- "use strict";var $a=Object.create;var Ks=Object.defineProperty;var Oa=Object.getOwnPropertyDescriptor;var Na=Object.getOwnPropertyNames;var Da=Object.getPrototypeOf,ja=Object.prototype.hasOwnProperty;var _a=(n,t)=>{for(var r in t)Ks(n,r,{get:t[r],enumerable:!0})},ji=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Na(t))!ja.call(n,o)&&o!==r&&Ks(n,o,{get:()=>t[o],enumerable:!(e=Oa(t,o))||e.enumerable});return n};var Va=(n,t,r)=>(r=n!=null?$a(Da(n)):{},ji(t||!n||!n.__esModule?Ks(r,"default",{value:n,enumerable:!0}):r,n)),Ua=n=>ji(Ks({},"__esModule",{value:!0}),n);var Xl={};_a(Xl,{AgentWidgetClient:()=>Ln,AgentWidgetSession:()=>Kn,AttachmentManager:()=>Hn,DEFAULT_DARK_THEME:()=>zr,DEFAULT_LIGHT_THEME:()=>qr,DEFAULT_WIDGET_CONFIG:()=>rt,VERSION:()=>On,attachHeaderToContainer:()=>Bn,buildComposer:()=>Xn,buildDefaultHeader:()=>Rr,buildExpandedHeader:()=>Br,buildHeader:()=>mn,buildHeaderWithLayout:()=>Yn,buildMinimalHeader:()=>Hr,componentRegistry:()=>ts,createActionManager:()=>Hs,createAgentExperience:()=>wr,createBestAvailableVoiceProvider:()=>or,createBubbleWithLayout:()=>ha,createCSATFeedback:()=>hr,createComponentMiddleware:()=>Aa,createComponentStreamParser:()=>ur,createDirectivePostprocessor:()=>zi,createFlexibleJsonStreamParser:()=>Xi,createImagePart:()=>na,createJsonStreamParser:()=>er,createLocalStorageAdapter:()=>dr,createMarkdownProcessor:()=>As,createMarkdownProcessorFromConfig:()=>Es,createMessageActions:()=>Or,createNPSFeedback:()=>fr,createPlainTextParser:()=>Zs,createRegexJsonParser:()=>Qs,createStandardBubble:()=>Gn,createTextPart:()=>sr,createTypingIndicator:()=>Fn,createVoiceProvider:()=>Rn,createXmlParser:()=>tr,default:()=>Yl,defaultActionHandlers:()=>$n,defaultJsonActionParser:()=>Rs,directivePostprocessor:()=>Ji,escapeHtml:()=>Ys,extractComponentDirectiveFromMessage:()=>mr,fileToImagePart:()=>sa,generateAssistantMessageId:()=>Wn,generateCodeSnippet:()=>Ra,generateMessageId:()=>Gi,generateUserMessageId:()=>Jn,getDisplayText:()=>Qi,getHeaderLayout:()=>Fr,getImageParts:()=>ta,hasComponentDirective:()=>gr,hasImages:()=>ea,headerLayouts:()=>lr,initAgentWidget:()=>Gr,isComponentDirectiveType:()=>Sa,isVoiceSupported:()=>ks,markdownPostprocessor:()=>Ir,mergeWithDefaults:()=>cr,normalizeContent:()=>Zi,pluginRegistry:()=>Ps,renderComponentDirective:()=>pr,renderLoadingIndicatorWithFallback:()=>$r,validateImageFile:()=>ra});module.exports=Ua(Xl);var Vi=require("marked"),qa=n=>{if(n)return n},As=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new Vi.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=qa(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},Es=n=>n?As({markedOptions:n.options,renderer:n.renderer}):As(),za=As(),Ir=n=>za(n),Ys=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ui=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),_i=n=>`%%FORM_PLACEHOLDER_${n}%%`,qi=(n,t)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=_i(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=_i(t.length);return t.push({token:s,type:o}),s}),r},zi=n=>{let t=Es(n);return r=>{let e=[],o=qi(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let u=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Ui(a)}"></div>`;s=s.replace(u,v)}),s}},Ji=n=>{let t=[],r=qi(n,t),e=Ir(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Ui(s)}"></div>`;e=e.replace(i,u)}),e};var gn=require("partial-json"),Xs=n=>n.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ts=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Ja=n=>{var i,a;let t=(i=n.completedAt)!=null?i:Date.now(),r=(a=n.startedAt)!=null?a:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ki=n=>n.status==="complete"?Ja(n):n.status==="pending"?"Waiting":"",Ka=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Yi=n=>n.status==="complete"?Ka(n):"Using tool...",Ya=()=>{let n=null,t=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
1
+ "use strict";var qa=Object.create;var Ks=Object.defineProperty;var Va=Object.getOwnPropertyDescriptor;var za=Object.getOwnPropertyNames;var Ja=Object.getPrototypeOf,Ka=Object.prototype.hasOwnProperty;var Ya=(n,t)=>{for(var r in t)Ks(n,r,{get:t[r],enumerable:!0})},Ki=(n,t,r,e)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of za(t))!Ka.call(n,o)&&o!==r&&Ks(n,o,{get:()=>t[o],enumerable:!(e=Va(t,o))||e.enumerable});return n};var Xa=(n,t,r)=>(r=n!=null?qa(Ja(n)):{},Ki(t||!n||!n.__esModule?Ks(r,"default",{value:n,enumerable:!0}):r,n)),Ga=n=>Ki(Ks({},"__esModule",{value:!0}),n);var sc={};Ya(sc,{AgentWidgetClient:()=>Wn,AgentWidgetSession:()=>Gn,AttachmentManager:()=>Bn,DEFAULT_DARK_THEME:()=>Kr,DEFAULT_LIGHT_THEME:()=>Jr,DEFAULT_WIDGET_CONFIG:()=>it,VERSION:()=>On,attachHeaderToContainer:()=>Fn,buildComposer:()=>Qn,buildDefaultHeader:()=>Br,buildExpandedHeader:()=>$r,buildHeader:()=>mn,buildHeaderWithLayout:()=>Zn,buildMinimalHeader:()=>Fr,componentRegistry:()=>rs,createActionManager:()=>Ps,createAgentExperience:()=>yr,createBestAvailableVoiceProvider:()=>ar,createBubbleWithLayout:()=>xa,createCSATFeedback:()=>vr,createComponentMiddleware:()=>Wa,createComponentStreamParser:()=>gr,createDirectivePostprocessor:()=>Qi,createFlexibleJsonStreamParser:()=>sa,createImagePart:()=>ca,createJsonStreamParser:()=>er,createLocalStorageAdapter:()=>pr,createMarkdownProcessor:()=>xs,createMarkdownProcessorFromConfig:()=>Ss,createMessageActions:()=>Dr,createNPSFeedback:()=>wr,createPlainTextParser:()=>Zs,createRegexJsonParser:()=>Qs,createStandardBubble:()=>es,createTextPart:()=>sr,createTypingIndicator:()=>$n,createVoiceProvider:()=>Hn,createXmlParser:()=>tr,default:()=>nc,defaultActionHandlers:()=>Nn,defaultJsonActionParser:()=>Ws,directivePostprocessor:()=>ea,escapeHtml:()=>Ys,extractComponentDirectiveFromMessage:()=>fr,fileToImagePart:()=>da,generateAssistantMessageId:()=>Pn,generateCodeSnippet:()=>Da,generateMessageId:()=>ra,generateUserMessageId:()=>Xn,getDisplayText:()=>ia,getHeaderLayout:()=>Nr,getImageParts:()=>la,hasComponentDirective:()=>mr,hasImages:()=>aa,headerLayouts:()=>dr,initAgentWidget:()=>Qr,isComponentDirectiveType:()=>La,isVoiceSupported:()=>Ts,markdownPostprocessor:()=>Wr,mergeWithDefaults:()=>ur,normalizeContent:()=>oa,pluginRegistry:()=>Ls,renderComponentDirective:()=>hr,renderLoadingIndicatorWithFallback:()=>Or,validateImageFile:()=>ua});module.exports=Ga(sc);var Xi=require("marked"),Za=n=>{if(n)return n},xs=n=>{var o,s;let t=n==null?void 0:n.markedOptions,r=new Xi.Marked({gfm:(o=t==null?void 0:t.gfm)!=null?o:!0,breaks:(s=t==null?void 0:t.breaks)!=null?s:!0,pedantic:t==null?void 0:t.pedantic,silent:t==null?void 0:t.silent}),e=Za(n==null?void 0:n.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},Ss=n=>n?xs({markedOptions:n.options,renderer:n.renderer}):xs(),Qa=xs(),Wr=n=>Qa(n),Ys=n=>n.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Gi=n=>n.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Yi=n=>`%%FORM_PLACEHOLDER_${n}%%`,Zi=(n,t)=>{let r=n;return r=r.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(e,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let i=Yi(t.length);return t.push({token:i,type:String(s.type)}),i}}catch{return e}return e}),r=r.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(e,o)=>{let s=Yi(t.length);return t.push({token:s,type:o}),s}),r},Qi=n=>{let t=Ss(n);return r=>{let e=[],o=Zi(r,e),s=t(o);return e.forEach(({token:i,type:a})=>{let d=new RegExp(i.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),v=`<div class="tvw-form-directive" data-tv-form="${Gi(a)}"></div>`;s=s.replace(d,v)}),s}},ea=n=>{let t=[],r=Zi(n,t),e=Wr(r);return t.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="tvw-form-directive" data-tv-form="${Gi(s)}"></div>`;e=e.replace(i,d)}),e};var hn=require("partial-json"),Xs=n=>n.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),As=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},el=n=>{var i,a;let t=(i=n.completedAt)!=null?i:Date.now(),r=(a=n.startedAt)!=null?a:t,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,t-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},ta=n=>n.status==="complete"?el(n):n.status==="pending"?"Waiting":"",tl=n=>{var o,s,i;let r=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((i=(s=n.startedAt)!=null?s:n.completedAt)!=null?i:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var na=n=>n.status==="complete"?tl(n):"Using tool...",nl=()=>{let n=null,t=0,r=e=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=e.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
3
3
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let i=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,a=e.match(i);if(a&&a[1])try{return a[1].replace(/\\n/g,`
4
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Gs=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zs=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Qs=()=>{var t;let n=Ya();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},er=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=(0,gn.parse)(r,gn.STR|gn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Xs(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Xs(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},Xi=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Xs(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Xs(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let a=(0,gn.parse)(s,gn.STR|gn.OBJ),u=o(a);u!==null&&(t=u)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},tr=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var Xa="https://api.runtype.com/v1/dispatch",Lr="https://api.runtype.com",Wr=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function Ga(n){switch(n){case"json":return er;case"regex-json":return Qs;case"xml":return tr;default:return Zs}}var Ln=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:Xa,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:Ga(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Lr;return t==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(r=(t=this.config).onSessionInit)==null||r.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let t=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Lr}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,i,a;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let c=await this.buildPayload(t.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,d={sessionId:u.sessionId,messages:t.messages.filter(Wr).map(w=>{var b,y,S;return{id:w.id,role:w.role,content:(S=(y=(b=w.contentParts)!=null?b:w.llmContent)!=null?y:w.rawContent)!=null?S:w.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:e.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let b=new Error(w.error||"Failed to send message");throw r({type:"error",error:b}),b}if(!m.body){let w=new Error("No response body received");throw r({type:"error",error:w}),w}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let u=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:u}),u}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Lr}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Wr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),e={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}return e}async buildPayload(t){let e={messages:t.slice().filter(Wr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(t,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let a=()=>{if(e.current)return e.current;let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return e.current=u,o(u),u};if(i.text!==void 0){let u=a();u.content+=i.text,o(u)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,e){var ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke,ce,D,Se,et,tt,Yt,Gt,Ye,Zt,fn,wn,sn,M,vn,an,Cn,rs,ln,cn,Nn,Dn,Bs,Fs,$s,os,jn,Ee,is,Qt,Ut,Os,Ns,as,xn,dn,Ds,js,_s,Sr,Sn,An,nt,_n,Vn,ls,cs,ds,us,Ft,qt,un,kt,ps,En,en,Vs,Tn,Mn,Un,Us,qs,pn,Xe,Ge,yn,gs,ms,Ar,It,Er,$t,hs,fs,ws,vs,ys;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=V=>{let Ie=V.reasoning?{...V.reasoning,chunks:[...V.reasoning.chunks]}:void 0,De=V.toolCall?{...V.toolCall,chunks:V.toolCall.chunks?[...V.toolCall.chunks]:void 0}:void 0,lt=V.tools?V.tools.map(mt=>({...mt,chunks:mt.chunks?[...mt.chunks]:void 0})):void 0;return{...V,reasoning:Ie,toolCall:De,tools:lt}},d=V=>{r({type:"message",message:v(V)})},m=null,w={current:null},b=new Map,y=new Map,S={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=V=>{if(V==null)return null;try{return String(V)}catch{return null}},J=V=>{var Ie,De,lt,mt,At;return k((At=(mt=(lt=(De=(Ie=V.stepId)!=null?Ie:V.step_id)!=null?De:V.step)!=null?lt:V.parentId)!=null?mt:V.flowStepId)!=null?At:V.flow_step_id)},E=V=>{var Ie,De,lt,mt,At,ot,h;return k((h=(ot=(At=(mt=(lt=(De=(Ie=V.callId)!=null?Ie:V.call_id)!=null?De:V.requestId)!=null?lt:V.request_id)!=null?mt:V.toolCallId)!=null?At:V.tool_call_id)!=null?ot:V.stepId)!=null?h:V.step_id)},I=()=>m||(m={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(m),m),T=(V,Ie)=>{S.lastId=Ie,V&&S.byStep.set(V,Ie)},B=(V,Ie)=>{var At;let De=(At=V.reasoningId)!=null?At:V.id,lt=J(V);if(De){let ot=String(De);return T(lt,ot),ot}if(lt){let ot=S.byStep.get(lt);if(ot)return S.lastId=ot,ot}if(S.lastId&&!Ie)return S.lastId;if(!Ie)return null;let mt=`reason-${c()}`;return T(lt,mt),mt},le=V=>{let Ie=b.get(V);if(Ie)return Ie;let De={id:`reason-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:V,status:"streaming",chunks:[]}};return b.set(V,De),d(De),De},z=(V,Ie)=>{x.lastId=Ie,V&&x.byCall.set(V,Ie)},U=(V,Ie)=>{var At;let De=(At=V.toolId)!=null?At:V.id,lt=E(V);if(De){let ot=String(De);return z(lt,ot),ot}if(lt){let ot=x.byCall.get(lt);if(ot)return x.lastId=ot,ot}if(x.lastId&&!Ie)return x.lastId;if(!Ie)return null;let mt=`tool-${c()}`;return z(lt,mt),mt},K=V=>{let Ie=y.get(V);if(Ie)return Ie;let De={id:`tool-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:V,status:"pending"}};return y.set(V,De),d(De),De},j=V=>{if(typeof V=="number"&&Number.isFinite(V))return V;if(typeof V=="string"){let Ie=Number(V);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let De=Date.parse(V);if(!Number.isNaN(De))return De}return Date.now()},ye=V=>{if(typeof V=="string")return V;if(V==null)return"";try{return JSON.stringify(V)}catch{return String(V)}},se=new Map,Y=new Map,_=null,O=new Map,Q=(ue=this.config.iterationDisplay)!=null?ue:"separate";for(;;){let{done:V,value:Ie}=await o.read();if(V)break;i+=s.decode(Ie,{stream:!0});let De=i.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}return null};return{getExtractedText:()=>n,processChunk:async e=>{if(e.length<=t)return n!==null?{text:n,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(n=s),t=e.length,n!==null?{text:n,raw:e}:null},close:async()=>{}}},Gs=n=>{try{let t=JSON.parse(n);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Zs=()=>{let n={processChunk:t=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Qs=()=>{var t;let n=nl();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:n.processChunk(r)},getExtractedText:n.getExtractedText.bind(n),close:(t=n.close)==null?void 0:t.bind(n)}},er=()=>{let n=null,t=0;return{getExtractedText:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n!==null||n===""?{text:n||"",raw:r}:null;try{let o=(0,hn.parse)(r,hn.STR|hn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Xs(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Xs(o.text)))}catch{}return t=r.length,n!==null?{text:n,raw:r}:null},close:()=>{}}},sa=n=>{let t=null,r=0,o=n||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Xs(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Xs(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:()=>t,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return t!==null?{text:t,raw:s}:null;try{let a=(0,hn.parse)(s,hn.STR|hn.OBJ),d=o(a);d!==null&&(t=d)}catch{}return r=s.length,{text:t||"",raw:s}},close:()=>{}}},tr=()=>{let n=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let e=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(n=e[1],{text:n,raw:t}):null},getExtractedText:()=>n}};var sl="https://api.runtype.com/v1/dispatch",Pr="https://api.runtype.com",Rr=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function rl(n){switch(n){case"json":return er;case"regex-json":return Qs;case"xml":return tr;default:return Zs}}var Wn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=t.apiUrl)!=null?r:sl,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(e=t.streamParser)!=null?e:rl(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr;return t==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(r=(t=this.config).onSessionInit)==null||r.call(t,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let t=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},e=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!e.ok){let a=await e.json().catch(()=>({error:"Session initialization failed"}));throw e.status===401?new Error(`Invalid client token: ${a.hint||a.error}`):e.status===403?new Error(`Origin not allowed: ${a.hint||a.error}`):new Error(a.error||"Failed to initialize session")}let o=await e.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr}/v1/client/feedback`}async sendFeedback(t){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(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isAgentMode()?this.dispatchAgent(t,r):this.isClientTokenMode()?this.dispatchClientToken(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var o,s,i,a;let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let c=await this.buildPayload(t.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Rr).map(w=>{var C,y,A;return{id:w.id,role:w.role,content:(A=(y=(C=w.contentParts)!=null?C:w.llmContent)!=null?y:w.rawContent)!=null?A:w.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let m=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:e.signal});if(!m.ok){let w=await m.json().catch(()=>({error:"Chat request failed"}));if(m.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}if(m.status===429){let y=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:y}),y}let C=new Error(w.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!m.body){let w=new Error("No response body received");throw r({type:"error",error:w}),w}r({type:"status",status:"connected"});try{await this.streamResponse(m.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&r({type:"error",error:c}),c}}async dispatchProxy(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Chat backend request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let e=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal},o)}catch(a){let d=a instanceof Error?a:new Error(String(a));throw r({type:"error",error:d}),d}else i=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:e.signal});if(!i.ok||!i.body){let a=new Error(`Agent execution request failed: ${i.status} ${i.statusText}`);throw r({type:"error",error:a}),a}r({type:"status",status:"connected"});try{await this.streamResponse(i.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Pr}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Rr).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),e={agent:this.config.agent,messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}return e}async buildPayload(t){let e={messages:t.slice().filter(Rr).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:t,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...e},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return e}async handleCustomSSEEvent(t,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let a=()=>{if(e.current)return e.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 e.current=d,o(d),d};if(i.text!==void 0){let d=a();d.content+=i.text,o(d)}return i.done&&(e.current&&(e.current.streaming=!1,o(e.current)),r({type:"status",status:"idle"})),i.error&&r({type:"error",error:new Error(i.error)}),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,e){var fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge,pe,D,Ee,st,rt,Yt,Qt,Ze,en,vn,wn,rn,T,yn,ln,Sn,as,cn,dn,Dn,jn,Rs,Hs,Bs,ls,_n,Ae,cs,Xt,Dt,Fs,$s,ds,An,un,Ns,Os,Ds,Er,En,Tn,ot,Un,qn,us,ps,gs,hs,Ft,Vt,pn,ke,ms,Mn,tn,js,Vn,zn,kn,bn,_s,Us,Gt,Jn,qs,Vs,gn,Qe,et,Cn,fs,vs,Tr,Lt,Mr,$t;let o=t.getReader(),s=new TextDecoder,i="",a=Date.now(),d=0,c=()=>a+d++,v=q=>{let We=q.reasoning?{...q.reasoning,chunks:[...q.reasoning.chunks]}:void 0,_e=q.toolCall?{...q.toolCall,chunks:q.toolCall.chunks?[...q.toolCall.chunks]:void 0}:void 0,dt=q.tools?q.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...q,reasoning:We,toolCall:_e,tools:dt}},p=q=>{r({type:"message",message:v(q)})},m=null,w={current:null},C=new Map,y=new Map,A={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},H=q=>{if(q==null)return null;try{return String(q)}catch{return null}},Y=q=>{var We,_e,dt,vt,Tt;return H((Tt=(vt=(dt=(_e=(We=q.stepId)!=null?We:q.step_id)!=null?_e:q.step)!=null?dt:q.parentId)!=null?vt:q.flowStepId)!=null?Tt:q.flow_step_id)},k=q=>{var We,_e,dt,vt,Tt,at,f;return H((f=(at=(Tt=(vt=(dt=(_e=(We=q.callId)!=null?We:q.call_id)!=null?_e:q.requestId)!=null?dt:q.request_id)!=null?vt:q.toolCallId)!=null?Tt:q.tool_call_id)!=null?at:q.stepId)!=null?f:q.step_id)},P=()=>m||(m={id:e!=null?e:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(m),m),L=(q,We)=>{A.lastId=We,q&&A.byStep.set(q,We)},F=(q,We)=>{var Tt;let _e=(Tt=q.reasoningId)!=null?Tt:q.id,dt=Y(q);if(_e){let at=String(_e);return L(dt,at),at}if(dt){let at=A.byStep.get(dt);if(at)return A.lastId=at,at}if(A.lastId&&!We)return A.lastId;if(!We)return null;let vt=`reason-${c()}`;return L(dt,vt),vt},ue=q=>{let We=C.get(q);if(We)return We;let _e={id:`reason-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:q,status:"streaming",chunks:[]}};return C.set(q,_e),p(_e),_e},z=(q,We)=>{x.lastId=We,q&&x.byCall.set(q,We)},V=(q,We)=>{var Tt;let _e=(Tt=q.toolId)!=null?Tt:q.id,dt=k(q);if(_e){let at=String(_e);return z(dt,at),at}if(dt){let at=x.byCall.get(dt);if(at)return x.lastId=at,at}if(x.lastId&&!We)return x.lastId;if(!We)return null;let vt=`tool-${c()}`;return z(dt,vt),vt},X=q=>{let We=y.get(q);if(We)return We;let _e={id:`tool-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:q,status:"pending"}};return y.set(q,_e),p(_e),_e},_=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){let We=Number(q);if(!Number.isNaN(We)&&Number.isFinite(We))return We;let _e=Date.parse(q);if(!Number.isNaN(_e))return _e}return Date.now()},Ce=q=>{if(typeof q=="string")return q;if(q==null)return"";try{return JSON.stringify(q)}catch{return String(q)}},se=new Map,G=new Map,U=null,N=new Map,ee=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:q,value:We}=await o.read();if(q)break;i+=s.decode(We,{stream:!0});let _e=i.split(`
5
5
 
6
- `);i=(Be=De.pop())!=null?Be:"";for(let lt of De){let mt=lt.split(`
7
- `),At="message",ot="";for(let $ of mt)$.startsWith("event:")?At=$.replace("event:","").trim():$.startsWith("data:")&&(ot+=$.replace("data:","").trim());if(!ot)continue;let h;try{h=JSON.parse(ot)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(Et=h.type)!=null?Et:"message";if((dt=this.onSSEEvent)==null||dt.call(this,We,h),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(h,r,w,d,c);if(w.current&&!m&&(m=w.current),$)continue}if(We==="reason_start"){let $=(gt=B(h,!0))!=null?gt:`reason-${c()}`,C=le($);C.reasoning=(Ht=C.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(ne=C.reasoning.startedAt)!=null?ne:j((Ne=h.startedAt)!=null?Ne:h.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(We==="reason_delta"||We==="reason_chunk"){let $=(Re=(be=B(h,!1))!=null?be:B(h,!0))!=null?Re:`reason-${c()}`,C=le($);C.reasoning=(Fe=C.reasoning)!=null?Fe:{id:$,status:"streaming",chunks:[]},C.reasoning.startedAt=(Nt=C.reasoning.startedAt)!=null?Nt:j((Ue=h.startedAt)!=null?Ue:h.timestamp);let L=(at=(X=(de=h.reasoningText)!=null?de:h.text)!=null?X:h.delta)!=null?at:"";if(L&&h.hidden!==!0&&C.reasoning.chunks.push(String(L)),C.reasoning.status=h.done?"complete":"streaming",h.done){C.reasoning.completedAt=j((vt=h.completedAt)!=null?vt:h.timestamp);let ae=(Tt=C.reasoning.startedAt)!=null?Tt:Date.now();C.reasoning.durationMs=Math.max(0,((yt=C.reasoning.completedAt)!=null?yt:Date.now())-ae)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(We==="reason_complete"){let $=(ee=(Kt=B(h,!1))!=null?Kt:B(h,!0))!=null?ee:`reason-${c()}`,C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j((Le=h.completedAt)!=null?Le:h.timestamp);let ae=(bt=C.reasoning.startedAt)!=null?bt:Date.now();C.reasoning.durationMs=Math.max(0,((pe=C.reasoning.completedAt)!=null?pe:Date.now())-ae),C.streaming=!1,d(C)}let L=J(h);L&&S.byStep.delete(L)}else if(We==="tool_start"){let $=(Ce=U(h,!0))!=null?Ce:`tool-${c()}`,C=K($),L=(qe=C.toolCall)!=null?qe:{id:$,status:"pending"};L.name=(Bt=h.toolName)!=null?Bt:L.name,L.status="running",h.args!==void 0?L.args=h.args:h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=(Vt=L.startedAt)!=null?Vt:j((Mt=h.startedAt)!=null?Mt:h.timestamp),L.completedAt=void 0,L.durationMs=void 0,C.toolCall=L,C.streaming=!0;let ae=h.agentContext;(ae||h.executionId)&&(C.agentMetadata={executionId:(F=ae==null?void 0:ae.executionId)!=null?F:h.executionId,iteration:(Qe=ae==null?void 0:ae.iteration)!=null?Qe:h.iteration}),d(C)}else if(We==="tool_chunk"||We==="tool_delta"){let $=(G=(N=U(h,!1))!=null?N:U(h,!0))!=null?G:`tool-${c()}`,C=K($),L=(re=C.toolCall)!=null?re:{id:$,status:"running"};L.startedAt=(oe=L.startedAt)!=null?oe:j(($e=h.startedAt)!=null?$e:h.timestamp);let ae=(ce=(Ke=(Je=h.text)!=null?Je:h.delta)!=null?Ke:h.message)!=null?ce:"";ae&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(ae))),L.status="running",C.toolCall=L,C.streaming=!0;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(tt=C.agentMetadata)!=null?tt:{executionId:(Se=Ae==null?void 0:Ae.executionId)!=null?Se:h.executionId,iteration:(et=Ae==null?void 0:Ae.iteration)!=null?et:h.iteration}),d(C)}else if(We==="tool_complete"){let $=(Gt=(Yt=U(h,!1))!=null?Yt:U(h,!0))!=null?Gt:`tool-${c()}`,C=K($),L=(Ye=C.toolCall)!=null?Ye:{id:$,status:"running"};L.status="complete",h.result!==void 0&&(L.result=h.result),typeof h.duration=="number"&&(L.duration=h.duration),L.completedAt=j((Zt=h.completedAt)!=null?Zt:h.timestamp);let ae=(fn=h.duration)!=null?fn:h.executionTime;if(typeof ae=="number")L.durationMs=ae;else{let Lt=(wn=L.startedAt)!=null?wn:Date.now();L.durationMs=Math.max(0,((sn=L.completedAt)!=null?sn:Date.now())-Lt)}C.toolCall=L,C.streaming=!1;let Ae=h.agentContext;(Ae||h.executionId)&&(C.agentMetadata=(an=C.agentMetadata)!=null?an:{executionId:(M=Ae==null?void 0:Ae.executionId)!=null?M:h.executionId,iteration:(vn=Ae==null?void 0:Ae.iteration)!=null?vn:h.iteration}),d(C);let ze=E(h);ze&&x.byCall.delete(ze)}else if(We==="step_chunk"||We==="step_delta"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=I(),ae=(cn=(ln=(rs=(Cn=h.text)!=null?Cn:h.delta)!=null?rs:h.content)!=null?ln:h.chunk)!=null?cn:"";if(ae){let ze=((Nn=Y.get(L.id))!=null?Nn:"")+ae;L.rawContent=ze,se.has(L.id)||se.set(L.id,this.createStreamParser());let Lt=se.get(L.id),it=ze.trim().startsWith("{")||ze.trim().startsWith("[");if(it&&Y.set(L.id,ze),Lt.__isPlainTextParser===!0){L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L);continue}let ht=Lt.processChunk(ze);if(ht instanceof Promise)ht.then(Oe=>{var ut;let _e=typeof Oe=="string"?Oe:(ut=Oe==null?void 0:Oe.text)!=null?ut:null;if(_e!==null&&_e.trim()!==""){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content=_e,d(Ve))}else if(!it&&!ze.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===L.id&&(Ve.content+=ae,Y.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,d(Ve))}}).catch(()=>{L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L)});else{let Oe=typeof ht=="string"?ht:(Dn=ht==null?void 0:ht.text)!=null?Dn:null;Oe!==null&&Oe.trim()!==""?(L.content=Oe,d(L)):!it&&!ze.trim().startsWith("<")&&(L.content+=ae,Y.delete(L.id),se.delete(L.id),L.rawContent=void 0,d(L))}}if(h.isComplete){let Ae=(Fs=(Bs=h.result)==null?void 0:Bs.response)!=null?Fs:L.content;if(Ae){let ze=Y.get(L.id),Lt=ze!=null?ze:ye(Ae);L.rawContent=Lt;let it=se.get(L.id),Ct=null,ht=!1;if(it&&(Ct=it.getExtractedText(),Ct===null&&(Ct=Gs(Lt)),Ct===null)){let Oe=it.processChunk(Lt);Oe instanceof Promise?(ht=!0,Oe.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===L.id&&(xt.content=ut,xt.streaming=!1,se.delete(xt.id),Y.delete(xt.id),d(xt))}})):Ct=typeof Oe=="string"?Oe:($s=Oe==null?void 0:Oe.text)!=null?$s:null}if(!ht){Ct!==null&&Ct.trim()!==""?L.content=Ct:Y.has(L.id)||(L.content=ye(Ae));let Oe=se.get(L.id);if(Oe){let _e=(os=Oe.close)==null?void 0:os.call(Oe);_e instanceof Promise&&_e.catch(()=>{}),se.delete(L.id)}Y.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let $=h.stepType,C=h.executionType;if($==="tool"||C==="context")continue;let L=(jn=h.result)==null?void 0:jn.response,ae=I();if(L!=null){let Ae=se.get(ae.id),ze=!1,Lt=!1;if(Ae){let it=Ae.getExtractedText(),Ct=Y.get(ae.id),ht=Ct!=null?Ct:ye(L);if(ae.rawContent=ht,it!==null&&it.trim()!=="")ae.content=it,ze=!0;else{let Oe=Gs(ht);if(Oe!==null)ae.content=Oe,ze=!0;else{let _e=Ae.processChunk(ht);if(_e instanceof Promise)Lt=!0,_e.then(ut=>{var xt;let Ve=typeof ut=="string"?ut:(xt=ut==null?void 0:ut.text)!=null?xt:null;if(Ve!==null&&Ve.trim()!==""){let Dt=m;Dt&&Dt.id===ae.id&&(Dt.content=Ve,Dt.streaming=!1,se.delete(Dt.id),Y.delete(Dt.id),d(Dt))}else{let Dt=Ae.getExtractedText(),Xt=m;Xt&&Xt.id===ae.id&&(Dt!==null&&Dt.trim()!==""?Xt.content=Dt:Y.has(Xt.id)||(Xt.content=ye(L)),Xt.streaming=!1,se.delete(Xt.id),Y.delete(Xt.id),d(Xt))}});else{let ut=typeof _e=="string"?_e:(Ee=_e==null?void 0:_e.text)!=null?Ee:null;if(ut!==null&&ut.trim()!=="")ae.content=ut,ze=!0;else{let Ve=Ae.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,ze=!0)}}}}}if(!Lt){if(!ae.rawContent){let it=Y.get(ae.id);ae.rawContent=it!=null?it:ye(L)}if(!ze&&!Y.has(ae.id)&&(ae.content=ye(L)),Ae){let it=(is=Ae.close)==null?void 0:is.call(Ae);it instanceof Promise&&it.catch(()=>{})}se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}}else se.delete(ae.id),Y.delete(ae.id),ae.streaming=!1,d(ae)}else if(We==="flow_complete"){let $=(Qt=h.result)==null?void 0:Qt.response;if($!=null){let C=I(),L=Y.get(C.id),ae=L!=null?L:ye($);C.rawContent=ae;let Ae=ye($),ze=se.get(C.id);if(ze){let Ct=Gs(ae);if(Ct!==null)Ae=Ct;else{let ht=ze.processChunk(ae);ht instanceof Promise&&ht.then(_e=>{var Ve;let ut=typeof _e=="string"?_e:(Ve=_e==null?void 0:_e.text)!=null?Ve:null;if(ut!==null){let xt=m;xt&&xt.id===C.id&&(xt.content=ut,xt.streaming=!1,d(xt))}});let Oe=ze.getExtractedText();Oe!==null&&(Ae=Oe)}}se.delete(C.id),Y.delete(C.id);let Lt=Ae!==C.content,it=C.streaming!==!1;Lt&&(C.content=Ae),C.streaming=!1,(Lt||it)&&d(C)}else if(m!==null){let C=m;se.delete(C.id),Y.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}r({type:"status",status:"idle"})}else if(We==="agent_start")_={executionId:h.executionId,agentId:(Ut=h.agentId)!=null?Ut:"virtual",agentName:(Os=h.agentName)!=null?Os:"",status:"running",currentIteration:0,maxIterations:(Ns=h.maxIterations)!=null?Ns:1,startedAt:j(h.startedAt)};else if(We==="agent_iteration_start"){if(_&&(_.currentIteration=h.iteration),Q==="separate"&&h.iteration>1){let $=m;$&&($.streaming=!1,d($),O.set(h.iteration-1,$),m=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(h.contentType==="text"){let $=I();$.content+=(as=h.delta)!=null?as:"",$.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId,agentName:_==null?void 0:_.agentName},d($)}else if(h.contentType==="thinking"){let $=(xn=h.turnId)!=null?xn:`agent-think-${h.iteration}`,C=le($);C.reasoning=(dn=C.reasoning)!=null?dn:{id:$,status:"streaming",chunks:[]},C.reasoning.chunks.push((Ds=h.delta)!=null?Ds:""),C.agentMetadata={executionId:h.executionId,iteration:h.iteration,turnId:h.turnId},d(C)}else if(h.contentType==="tool_input"){let $=(js=h.toolCallId)!=null?js:x.lastId;if($){let C=y.get($);C!=null&&C.toolCall&&(C.toolCall.chunks=(_s=C.toolCall.chunks)!=null?_s:[],C.toolCall.chunks.push((Sr=h.delta)!=null?Sr:""),d(C))}}}else if(We==="agent_turn_complete"){let $=h.turnId;if($){let C=b.get($);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=j(h.completedAt);let L=(Sn=C.reasoning.startedAt)!=null?Sn:Date.now();C.reasoning.durationMs=Math.max(0,((An=C.reasoning.completedAt)!=null?An:Date.now())-L),C.streaming=!1,d(C)}}}else if(We==="agent_tool_start"){let $=(nt=h.toolCallId)!=null?nt:`agent-tool-${c()}`;z(E(h),$);let C=K($),L=(_n=C.toolCall)!=null?_n:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};L.name=(Vn=h.toolName)!=null?Vn:L.name,L.status="running",h.parameters!==void 0&&(L.args=h.parameters),L.startedAt=j((ls=h.startedAt)!=null?ls:h.timestamp),C.toolCall=L,C.streaming=!0,C.agentMetadata={executionId:h.executionId,iteration:h.iteration},d(C)}else if(We==="agent_tool_delta"){let $=(cs=h.toolCallId)!=null?cs:x.lastId;if($){let C=(ds=y.get($))!=null?ds:K($);C.toolCall&&(C.toolCall.chunks=(us=C.toolCall.chunks)!=null?us:[],C.toolCall.chunks.push((Ft=h.delta)!=null?Ft:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(We==="agent_tool_complete"){let $=(qt=h.toolCallId)!=null?qt:x.lastId;if($){let C=(un=y.get($))!=null?un:K($);if(C.toolCall){C.toolCall.status="complete",h.result!==void 0&&(C.toolCall.result=h.result),typeof h.executionTime=="number"&&(C.toolCall.durationMs=h.executionTime),C.toolCall.completedAt=j((kt=h.completedAt)!=null?kt:h.timestamp),C.streaming=!1,d(C);let L=E(h);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let $=`agent-reflection-${h.executionId}-${h.iteration}`,C={id:$,role:"assistant",content:(ps=h.reflection)!=null?ps:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(En=h.reflection)!=null?En:""]},agentMetadata:{executionId:h.executionId,iteration:h.iteration}};d(C)}else if(We==="agent_complete"){_&&(_.status=h.success?"complete":"error",_.completedAt=j(h.completedAt),_.stopReason=h.stopReason);let $=m;$&&($.streaming=!1,d($)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let $=typeof h.error=="string"?h.error:(Vs=(en=h.error)==null?void 0:en.message)!=null?Vs:"Agent execution error";h.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let $=(Tn=h.approvalId)!=null?Tn:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(Mn=_==null?void 0:_.agentId)!=null?Mn:"virtual",executionId:(Us=(Un=h.executionId)!=null?Un:_==null?void 0:_.executionId)!=null?Us:"",toolName:(qs=h.toolName)!=null?qs:"",toolType:h.toolType,description:(Xe=h.description)!=null?Xe:`Execute ${(pn=h.toolName)!=null?pn:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="step_await"&&h.awaitReason==="approval_required"){let $=(Ge=h.approvalId)!=null?Ge:`approval-${c()}`,C={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(yn=_==null?void 0:_.agentId)!=null?yn:"virtual",executionId:(ms=(gs=h.executionId)!=null?gs:_==null?void 0:_.executionId)!=null?ms:"",toolName:(Ar=h.toolName)!=null?Ar:"",toolType:h.toolType,description:(Er=h.description)!=null?Er:`Execute ${(It=h.toolName)!=null?It:"tool"}`,parameters:h.parameters}};d(C)}else if(We==="agent_approval_complete"){let $=h.approvalId;if($){let L={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:($t=h.decision)!=null?$t:"approved",agentId:(hs=_==null?void 0:_.agentId)!=null?hs:"virtual",executionId:(ws=(fs=h.executionId)!=null?fs:_==null?void 0:_.executionId)!=null?ws:"",toolName:(vs=h.toolName)!=null?vs:"",description:(ys=h.description)!=null?ys:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&h.error&&r({type:"error",error:h.error instanceof Error?h.error:new Error(String(h.error))})}}}}}};function Gi(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function Jn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Wn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var nr="[Image]";function Zi(n){return typeof n=="string"?[{type:"text",text:n}]:n}function Qi(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function ea(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function ta(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function sr(n){return{type:"text",text:n}}function na(n,t){return{type:"image",image:n,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function sa(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;t({type:"image",image:o,mimeType:n.type,alt:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function ra(n,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var oa=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Za=["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"],bn=[...oa,...Za];function Qa(n){return oa.includes(n)||n.startsWith("image/")}function rr(n){return Qa(n.type)}async function ia(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;rr(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function aa(n,t=bn,r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function el(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function la(n,t){let r=el(t).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"}[n]||r||"FILE"}var Ms=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.analyserNode=null;this.mediaStream=null;this.silenceCheckInterval=null;this.silenceStart=null}async connect(){var t,r,e;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",i=(t=this.config)==null?void 0:t.host,a=(r=this.config)==null?void 0:r.agentId,u=(e=this.config)==null?void 0:e.clientToken;if(!a||!u)throw new Error("agentId and clientToken are required");if(!i)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${i}/ws/agents/${a}/voice?token=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,w)=>{if(!this.ws)return w(new Error("WebSocket not created"));let b=!1,y=x=>{b||(b=!0,clearTimeout(S),w(new Error(x)))},S=setTimeout(()=>y("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{b||(b=!0,clearTimeout(S),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!b){let k=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+k+"."+d)}},{once:!0})})}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.onmessage=t=>{try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(e=>e(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r;switch(t.type){case"voice_response":(r=t.response.audio)!=null&&r.base64&&this.playAudio(t.response.audio).catch(e=>this.errorCallbacks.forEach(o=>o(e instanceof Error?e:new Error(String(e))))),this.resultCallbacks.forEach(e=>e({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),this.isProcessing=!1,this.statusCallbacks.forEach(e=>e("idle"));break;case"error":this.errorCallbacks.forEach(e=>e(new Error(t.error))),this.statusCallbacks.forEach(e=>e("error")),this.isProcessing=!1;break;case"pong":break}}async startListening(){var t,r,e,o;try{if(this.isProcessing)throw new Error("Already processing audio");let s=await navigator.mediaDevices.getUserMedia({audio:!0});this.mediaStream=s;let i=this.w;this.audioContext=new(i.AudioContext||i.webkitAudioContext);let a=this.audioContext,u=a.createMediaStreamSource(s);this.analyserNode=a.createAnalyser(),this.analyserNode.fftSize=2048,u.connect(this.analyserNode);let c=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,v=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.silenceStart=null;let d=new Float32Array(this.analyserNode.fftSize);this.silenceCheckInterval=setInterval(()=>{if(!this.analyserNode)return;this.analyserNode.getFloatTimeDomainData(d);let m=0;for(let b=0;b<d.length;b++)m+=d[b]*d[b];Math.sqrt(m/d.length)<v?this.silenceStart===null?this.silenceStart=Date.now():Date.now()-this.silenceStart>=c&&this.stopListening():this.silenceStart=null},100),this.mediaRecorder=new MediaRecorder(s),this.audioChunks=[],this.mediaRecorder.ondataavailable=m=>{m.data.size>0&&this.audioChunks.push(m.data)},this.mediaRecorder.onstop=async()=>{var m;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let w=((m=this.mediaRecorder)==null?void 0:m.mimeType)||"audio/webm",b=new Blob(this.audioChunks,{type:w});await this.sendAudio(b),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(m=>m("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.silenceCheckInterval&&(clearInterval(this.silenceCheckInterval),this.silenceCheckInterval=null),this.analyserNode=null,this.silenceStart=null,this.mediaRecorder&&(this.mediaRecorder.stop(),this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.statusCallbacks.forEach(t=>t("idle"))}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(e=>e(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(e=>e("error"));return}try{let e=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type);this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId}))}catch(e){this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,e)=>{let o=new FileReader;o.onload=()=>{let i=o.result.split(",")[1];r(i)},o.onerror=e,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),e=new Uint8Array(r.length);for(let c=0;c<r.length;c++)e[c]=r.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,i=new Blob([e],{type:s}),a=URL.createObjectURL(i),u=new Audio(a);u.onended=()=>URL.revokeObjectURL(a),await u.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(await this.stopListening(),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Pn=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var a;let s=Array.from(o.results).map(u=>u[0]).map(u=>u.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({text:s,confidence:i?.8:.5,provider:"browser"})),i&&!((a=this.config)!=null&&a.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Rn(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(n.runtype);case"browser":if(!Pn.isSupported())throw new Error("Browser speech recognition not supported");return new Pn(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function or(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Rn({type:"runtype",runtype:n.runtype});if(Pn.isSupported())return Rn({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ks(n){try{return or(n),!0}catch{return!1}}var Kn=class n{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,e,o,s,i,a,u;t.type==="message"?(this.upsertMessage(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(e=t.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(u=(a=this.callbacks).onError)==null||u.call(a,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Ln(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return ks((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",u=(o=i.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let v=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=v.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var v,d,m,w,b,y,S;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){if(this.pendingVoiceUserMessageId&&((v=c.transcript)!=null&&v.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(w=c.text)!=null&&w.trim()&&this.injectAssistantMessage({content:c.text.trim()}),(b=c.audio)!=null&&b.base64){let x=(S=this.pendingVoiceAssistantMessageId)!=null?S:(y=[...this.messages].reverse().find(k=>k.role==="assistant"))==null?void 0:y.id;x&&this.ttsSpokenMessageIds.add(x)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var v,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(v=this.callbacks).onVoiceStatusChanged)==null||d.call(v,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,e,o,s,i,a,u,c,v;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((e=t.runtype)==null?void 0:e.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(i=t.runtype)==null?void 0:i.voiceId,pauseDuration:(a=t.runtype)==null?void 0:a.pauseDuration,silenceThreshold:(u=t.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(v=t.browser)==null?void 0:v.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(t=this.callbacks).onError)==null||r.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Ln(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?Jn():r==="assistant"?Wn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...v!==void 0&&{voiceProcessing:v}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let e of t){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,w={id:u!=null?u:o==="user"?Jn():o==="assistant"?Wn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(t,r){var c,v,d,m,w;let e=t.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=Jn(),s=Wn(),i={id:o,role:"user",content:e||nr,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let u=[...this.messages];try{await this.client.dispatch({messages:u,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(b){let y=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!y){let S={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(S)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(b instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,b):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(b))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Wn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(c){let v={id:t,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(u=(a=this.callbacks).onError)==null||u.call(a,new Error(String(c)))}}async connectStream(t,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(t,r){var u,c,v;let e=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let d;if(a?d=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):d=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),d){let m=null;if(d instanceof Response){if(!d.ok){let w=await d.json().catch(()=>null);throw new Error((u=w==null?void 0:w.error)!=null?u:`Approval request failed: ${d.status}`)}m=d.body}else d instanceof ReadableStream&&(m=d);m?await this.connectStream(m):r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(v=(c=this.callbacks).onError)==null||v.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let e=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!e)return;if(this.ttsSpokenMessageIds.has(e.id)){this.ttsSpokenMessageIds.delete(e.id);return}let o=e.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let e=window.speechSynthesis;e.cancel();let o=new SpeechSynthesisUtterance(t),s=e.getVoices();if(r.voice){let i=s.find(a=>a.name===r.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):n.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>e.speak(o),50)}static pickBestVoice(t){var e;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=t.find(i=>i.name===o);if(s)return s}return(e=t.find(o=>o.lang.startsWith("en")))!=null?e:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,e)=>{var u,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(u=r.sequence)!=null?u:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(n,t)=>{let r=document.createElement(n);return t&&(r.className=t),r};var tl=Va(require("lucide"),1),ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=tl[o];return s?nl(s,t,r,e):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function nl(n,t,r,e){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let i=s[0],a=s[1];if(a){let u=document.createElementNS("http://www.w3.org/2000/svg",i);Object.entries(a).forEach(([c,v])=>{c!=="stroke"&&u.setAttribute(c,String(v))}),o.appendChild(u)}}}),o}var ir={allowedTypes:bn,maxFileSize:10*1024*1024,maxFiles:4};function sl(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function rl(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-json":"file"}var Hn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:ir.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:ir.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:ir.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:ir.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,e,o,s,i,a,u;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=aa(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let d=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,d);continue}try{let d=await ia(c),m=rr(c)?URL.createObjectURL(c):null,w={id:sl(),file:c,previewUrl:m,contentPart:d};this.attachments.push(w),this.renderPreview(w)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(u=>u.id===t);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var t,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=rr(t.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",t.id),e.style.width="48px",e.style.height="48px",r&&t.previewUrl){let i=g("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=rl(t.file.type),u=ie(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=g("span");c.textContent=la(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Pr=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},ol=n=>{var s,i,a;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",r=(i=n==null?void 0:n.theme)!=null?i:{},e=(a=n==null?void 0:n.darkTheme)!=null?a:r;return t==="light"?r:t==="dark"||Pr()==="dark"?e:r},ca=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(Pr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Pr());r.addEventListener?(r.addEventListener("change",e),t.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),t.push(()=>r.removeListener(e)))}return()=>{t.forEach(r=>r())}},ar=(n,t)=>{let r=ol(t);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(o))})};var da=require("idiomorph"),ua=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;da.Idiomorph.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var nn={"bottom-right":"tvw-bottom-6 tvw-right-6","bottom-left":"tvw-bottom-6 tvw-left-6","top-right":"tvw-top-6 tvw-right-6","top-left":"tvw-top-6 tvw-left-6"};var Is=(n,t)=>{let r=g("button");r.type="button",r.innerHTML=`
6
+ `);i=(Fe=_e.pop())!=null?Fe:"";for(let dt of _e){let vt=dt.split(`
7
+ `),Tt="message",at="";for(let $ of vt)$.startsWith("event:")?Tt=$.replace("event:","").trim():$.startsWith("data:")&&(at+=$.replace("data:","").trim());if(!at)continue;let f;try{f=JSON.parse(at)}catch($){r({type:"error",error:$ instanceof Error?$:new Error("Failed to parse chat stream payload")});continue}let Re=Tt!=="message"?Tt:(Mt=f.type)!=null?Mt:"message";if((gt=this.onSSEEvent)==null||gt.call(this,Re,f),this.parseSSEEvent){w.current=m;let $=await this.handleCustomSSEEvent(f,r,w,p,c);if(w.current&&!m&&(m=w.current),$)continue}if(Re==="reason_start"){let $=(ft=F(f,!0))!=null?ft:`reason-${c()}`,b=ue($);b.reasoning=(Ht=b.reasoning)!=null?Ht:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(ne=b.reasoning.startedAt)!=null?ne:_((je=f.startedAt)!=null?je:f.timestamp),b.reasoning.completedAt=void 0,b.reasoning.durationMs=void 0,b.streaming=!0,b.reasoning.status="streaming",p(b)}else if(Re==="reason_delta"||Re==="reason_chunk"){let $=(He=(xe=F(f,!1))!=null?xe:F(f,!0))!=null?He:`reason-${c()}`,b=ue($);b.reasoning=($e=b.reasoning)!=null?$e:{id:$,status:"streaming",chunks:[]},b.reasoning.startedAt=(Ot=b.reasoning.startedAt)!=null?Ot:_((ze=f.startedAt)!=null?ze:f.timestamp);let R=(ct=(Z=(he=f.reasoningText)!=null?he:f.text)!=null?Z:f.delta)!=null?ct:"";if(R&&f.hidden!==!0&&b.reasoning.chunks.push(String(R)),b.reasoning.status=f.done?"complete":"streaming",f.done){b.reasoning.completedAt=_((bt=f.completedAt)!=null?bt:f.timestamp);let ae=(kt=b.reasoning.startedAt)!=null?kt:Date.now();b.reasoning.durationMs=Math.max(0,((Ct=b.reasoning.completedAt)!=null?Ct:Date.now())-ae)}b.streaming=b.reasoning.status!=="complete",p(b)}else if(Re==="reason_complete"){let $=(te=(Kt=F(f,!1))!=null?Kt:F(f,!0))!=null?te:`reason-${c()}`,b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_((Pe=f.completedAt)!=null?Pe:f.timestamp);let ae=(xt=b.reasoning.startedAt)!=null?xt:Date.now();b.reasoning.durationMs=Math.max(0,((ve=b.reasoning.completedAt)!=null?ve:Date.now())-ae),b.streaming=!1,p(b)}let R=Y(f);R&&A.byStep.delete(R)}else if(Re==="tool_start"){let $=(Se=V(f,!0))!=null?Se:`tool-${c()}`,b=X($),R=(Je=b.toolCall)!=null?Je:{id:$,status:"pending"};R.name=(Bt=f.toolName)!=null?Bt:R.name,R.status="running",f.args!==void 0?R.args=f.args:f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=(qt=R.startedAt)!=null?qt:_((It=f.startedAt)!=null?It:f.timestamp),R.completedAt=void 0,R.durationMs=void 0,b.toolCall=R,b.streaming=!0;let ae=f.agentContext;(ae||f.executionId)&&(b.agentMetadata={executionId:(I=ae==null?void 0:ae.executionId)!=null?I:f.executionId,iteration:(nt=ae==null?void 0:ae.iteration)!=null?nt:f.iteration}),p(b)}else if(Re==="tool_chunk"||Re==="tool_delta"){let $=(Q=(O=V(f,!1))!=null?O:V(f,!0))!=null?Q:`tool-${c()}`,b=X($),R=(re=b.toolCall)!=null?re:{id:$,status:"running"};R.startedAt=(oe=R.startedAt)!=null?oe:_((Ne=f.startedAt)!=null?Ne:f.timestamp);let ae=(pe=(Ge=(Xe=f.text)!=null?Xe:f.delta)!=null?Ge:f.message)!=null?pe:"";ae&&(R.chunks=(D=R.chunks)!=null?D:[],R.chunks.push(String(ae))),R.status="running",b.toolCall=R,b.streaming=!0;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(rt=b.agentMetadata)!=null?rt:{executionId:(Ee=Te==null?void 0:Te.executionId)!=null?Ee:f.executionId,iteration:(st=Te==null?void 0:Te.iteration)!=null?st:f.iteration}),p(b)}else if(Re==="tool_complete"){let $=(Qt=(Yt=V(f,!1))!=null?Yt:V(f,!0))!=null?Qt:`tool-${c()}`,b=X($),R=(Ze=b.toolCall)!=null?Ze:{id:$,status:"running"};R.status="complete",f.result!==void 0&&(R.result=f.result),typeof f.duration=="number"&&(R.duration=f.duration),R.completedAt=_((en=f.completedAt)!=null?en:f.timestamp);let ae=(vn=f.duration)!=null?vn:f.executionTime;if(typeof ae=="number")R.durationMs=ae;else{let Wt=(wn=R.startedAt)!=null?wn:Date.now();R.durationMs=Math.max(0,((rn=R.completedAt)!=null?rn:Date.now())-Wt)}b.toolCall=R,b.streaming=!1;let Te=f.agentContext;(Te||f.executionId)&&(b.agentMetadata=(ln=b.agentMetadata)!=null?ln:{executionId:(T=Te==null?void 0:Te.executionId)!=null?T:f.executionId,iteration:(yn=Te==null?void 0:Te.iteration)!=null?yn:f.iteration}),p(b);let Ke=k(f);Ke&&x.byCall.delete(Ke)}else if(Re==="step_chunk"||Re==="step_delta"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=P(),ae=(dn=(cn=(as=(Sn=f.text)!=null?Sn:f.delta)!=null?as:f.content)!=null?cn:f.chunk)!=null?dn:"";if(ae){let Ke=((Dn=G.get(R.id))!=null?Dn:"")+ae;R.rawContent=Ke,se.has(R.id)||se.set(R.id,this.createStreamParser());let Wt=se.get(R.id),lt=Ke.trim().startsWith("{")||Ke.trim().startsWith("[");if(lt&&G.set(R.id,Ke),Wt.__isPlainTextParser===!0){R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R);continue}let wt=Wt.processChunk(Ke);if(wt instanceof Promise)wt.then(De=>{var ht;let qe=typeof De=="string"?De:(ht=De==null?void 0:De.text)!=null?ht:null;if(qe!==null&&qe.trim()!==""){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content=qe,p(Ve))}else if(!lt&&!Ke.trim().startsWith("<")){let Ve=m;Ve&&Ve.id===R.id&&(Ve.content+=ae,G.delete(Ve.id),se.delete(Ve.id),Ve.rawContent=void 0,p(Ve))}}).catch(()=>{R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R)});else{let De=typeof wt=="string"?wt:(jn=wt==null?void 0:wt.text)!=null?jn:null;De!==null&&De.trim()!==""?(R.content=De,p(R)):!lt&&!Ke.trim().startsWith("<")&&(R.content+=ae,G.delete(R.id),se.delete(R.id),R.rawContent=void 0,p(R))}}if(f.isComplete){let Te=(Hs=(Rs=f.result)==null?void 0:Rs.response)!=null?Hs:R.content;if(Te){let Ke=G.get(R.id),Wt=Ke!=null?Ke:Ce(Te);R.rawContent=Wt;let lt=se.get(R.id),St=null,wt=!1;if(lt&&(St=lt.getExtractedText(),St===null&&(St=Gs(Wt)),St===null)){let De=lt.processChunk(Wt);De instanceof Promise?(wt=!0,De.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===R.id&&(At.content=ht,At.streaming=!1,se.delete(At.id),G.delete(At.id),p(At))}})):St=typeof De=="string"?De:(Bs=De==null?void 0:De.text)!=null?Bs:null}if(!wt){St!==null&&St.trim()!==""?R.content=St:G.has(R.id)||(R.content=Ce(Te));let De=se.get(R.id);if(De){let qe=(ls=De.close)==null?void 0:ls.call(De);qe instanceof Promise&&qe.catch(()=>{}),se.delete(R.id)}G.delete(R.id),R.streaming=!1,p(R)}}}}else if(Re==="step_complete"){let $=f.stepType,b=f.executionType;if($==="tool"||b==="context")continue;let R=(_n=f.result)==null?void 0:_n.response,ae=P();if(R!=null){let Te=se.get(ae.id),Ke=!1,Wt=!1;if(Te){let lt=Te.getExtractedText(),St=G.get(ae.id),wt=St!=null?St:Ce(R);if(ae.rawContent=wt,lt!==null&&lt.trim()!=="")ae.content=lt,Ke=!0;else{let De=Gs(wt);if(De!==null)ae.content=De,Ke=!0;else{let qe=Te.processChunk(wt);if(qe instanceof Promise)Wt=!0,qe.then(ht=>{var At;let Ve=typeof ht=="string"?ht:(At=ht==null?void 0:ht.text)!=null?At:null;if(Ve!==null&&Ve.trim()!==""){let jt=m;jt&&jt.id===ae.id&&(jt.content=Ve,jt.streaming=!1,se.delete(jt.id),G.delete(jt.id),p(jt))}else{let jt=Te.getExtractedText(),Zt=m;Zt&&Zt.id===ae.id&&(jt!==null&&jt.trim()!==""?Zt.content=jt:G.has(Zt.id)||(Zt.content=Ce(R)),Zt.streaming=!1,se.delete(Zt.id),G.delete(Zt.id),p(Zt))}});else{let ht=typeof qe=="string"?qe:(Ae=qe==null?void 0:qe.text)!=null?Ae:null;if(ht!==null&&ht.trim()!=="")ae.content=ht,Ke=!0;else{let Ve=Te.getExtractedText();Ve!==null&&Ve.trim()!==""&&(ae.content=Ve,Ke=!0)}}}}}if(!Wt){if(!ae.rawContent){let lt=G.get(ae.id);ae.rawContent=lt!=null?lt:Ce(R)}if(!Ke&&!G.has(ae.id)&&(ae.content=Ce(R)),Te){let lt=(cs=Te.close)==null?void 0:cs.call(Te);lt instanceof Promise&&lt.catch(()=>{})}se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}}else se.delete(ae.id),G.delete(ae.id),ae.streaming=!1,p(ae)}else if(Re==="flow_complete"){let $=(Xt=f.result)==null?void 0:Xt.response;if($!=null){let b=P(),R=G.get(b.id),ae=R!=null?R:Ce($);b.rawContent=ae;let Te=Ce($),Ke=se.get(b.id);if(Ke){let St=Gs(ae);if(St!==null)Te=St;else{let wt=Ke.processChunk(ae);wt instanceof Promise&&wt.then(qe=>{var Ve;let ht=typeof qe=="string"?qe:(Ve=qe==null?void 0:qe.text)!=null?Ve:null;if(ht!==null){let At=m;At&&At.id===b.id&&(At.content=ht,At.streaming=!1,p(At))}});let De=Ke.getExtractedText();De!==null&&(Te=De)}}se.delete(b.id),G.delete(b.id);let Wt=Te!==b.content,lt=b.streaming!==!1;Wt&&(b.content=Te),b.streaming=!1,(Wt||lt)&&p(b)}else if(m!==null){let b=m;se.delete(b.id),G.delete(b.id),b.streaming!==!1&&(b.streaming=!1,p(b))}r({type:"status",status:"idle"})}else if(Re==="agent_start")U={executionId:f.executionId,agentId:(Dt=f.agentId)!=null?Dt:"virtual",agentName:(Fs=f.agentName)!=null?Fs:"",status:"running",currentIteration:0,maxIterations:($s=f.maxIterations)!=null?$s:1,startedAt:_(f.startedAt)};else if(Re==="agent_iteration_start"){if(U&&(U.currentIteration=f.iteration),ee==="separate"&&f.iteration>1){let $=m;$&&($.streaming=!1,p($),N.set(f.iteration-1,$),m=null)}}else if(Re!=="agent_turn_start"){if(Re==="agent_turn_delta"){if(f.contentType==="text"){let $=P();$.content+=(ds=f.delta)!=null?ds:"",$.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId,agentName:U==null?void 0:U.agentName},p($)}else if(f.contentType==="thinking"){let $=(An=f.turnId)!=null?An:`agent-think-${f.iteration}`,b=ue($);b.reasoning=(un=b.reasoning)!=null?un:{id:$,status:"streaming",chunks:[]},b.reasoning.chunks.push((Ns=f.delta)!=null?Ns:""),b.agentMetadata={executionId:f.executionId,iteration:f.iteration,turnId:f.turnId},p(b)}else if(f.contentType==="tool_input"){let $=(Os=f.toolCallId)!=null?Os:x.lastId;if($){let b=y.get($);b!=null&&b.toolCall&&(b.toolCall.chunks=(Ds=b.toolCall.chunks)!=null?Ds:[],b.toolCall.chunks.push((Er=f.delta)!=null?Er:""),p(b))}}}else if(Re==="agent_turn_complete"){let $=f.turnId;if($){let b=C.get($);if(b!=null&&b.reasoning){b.reasoning.status="complete",b.reasoning.completedAt=_(f.completedAt);let R=(En=b.reasoning.startedAt)!=null?En:Date.now();b.reasoning.durationMs=Math.max(0,((Tn=b.reasoning.completedAt)!=null?Tn:Date.now())-R),b.streaming=!1,p(b)}}}else if(Re==="agent_tool_start"){let $=(ot=f.toolCallId)!=null?ot:`agent-tool-${c()}`;z(k(f),$);let b=X($),R=(Un=b.toolCall)!=null?Un:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};R.name=(qn=f.toolName)!=null?qn:R.name,R.status="running",f.parameters!==void 0&&(R.args=f.parameters),R.startedAt=_((us=f.startedAt)!=null?us:f.timestamp),b.toolCall=R,b.streaming=!0,b.agentMetadata={executionId:f.executionId,iteration:f.iteration},p(b)}else if(Re==="agent_tool_delta"){let $=(ps=f.toolCallId)!=null?ps:x.lastId;if($){let b=(gs=y.get($))!=null?gs:X($);b.toolCall&&(b.toolCall.chunks=(hs=b.toolCall.chunks)!=null?hs:[],b.toolCall.chunks.push((Ft=f.delta)!=null?Ft:""),b.toolCall.status="running",b.streaming=!0,p(b))}}else if(Re==="agent_tool_complete"){let $=(Vt=f.toolCallId)!=null?Vt:x.lastId;if($){let b=(pn=y.get($))!=null?pn:X($);if(b.toolCall){b.toolCall.status="complete",f.result!==void 0&&(b.toolCall.result=f.result),typeof f.executionTime=="number"&&(b.toolCall.durationMs=f.executionTime),b.toolCall.completedAt=_((ke=f.completedAt)!=null?ke:f.timestamp),b.streaming=!1,p(b);let R=k(f);R&&x.byCall.delete(R)}}}else if(Re!=="agent_iteration_complete"){if(Re==="agent_reflection"||Re==="agent_reflect"){let $=`agent-reflection-${f.executionId}-${f.iteration}`,b={id:$,role:"assistant",content:(ms=f.reflection)!=null?ms:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:$,status:"complete",chunks:[(Mn=f.reflection)!=null?Mn:""]},agentMetadata:{executionId:f.executionId,iteration:f.iteration}};p(b)}else if(Re==="agent_complete"){U&&(U.status=f.success?"complete":"error",U.completedAt=_(f.completedAt),U.stopReason=f.stopReason);let $=m;$&&($.streaming=!1,p($)),r({type:"status",status:"idle"})}else if(Re==="agent_error"){let $=typeof f.error=="string"?f.error:(js=(tn=f.error)==null?void 0:tn.message)!=null?js:"Agent execution error";f.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):r({type:"error",error:new Error($)})}else if(Re!=="agent_ping")if(Re==="agent_approval_start"){let $=(Vn=f.approvalId)!=null?Vn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(zn=U==null?void 0:U.agentId)!=null?zn:"virtual",executionId:(bn=(kn=f.executionId)!=null?kn:U==null?void 0:U.executionId)!=null?bn:"",toolName:(_s=f.toolName)!=null?_s:"",toolType:f.toolType,description:(Gt=f.description)!=null?Gt:`Execute ${(Us=f.toolName)!=null?Us:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="step_await"&&f.awaitReason==="approval_required"){let $=(Jn=f.approvalId)!=null?Jn:`approval-${c()}`,b={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:"pending",agentId:(qs=U==null?void 0:U.agentId)!=null?qs:"virtual",executionId:(gn=(Vs=f.executionId)!=null?Vs:U==null?void 0:U.executionId)!=null?gn:"",toolName:(Qe=f.toolName)!=null?Qe:"",toolType:f.toolType,description:(Cn=f.description)!=null?Cn:`Execute ${(et=f.toolName)!=null?et:"tool"}`,parameters:f.parameters}};p(b)}else if(Re==="agent_approval_complete"){let $=f.approvalId;if($){let R={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:$,status:(fs=f.decision)!=null?fs:"approved",agentId:(vs=U==null?void 0:U.agentId)!=null?vs:"virtual",executionId:(Lt=(Tr=f.executionId)!=null?Tr:U==null?void 0:U.executionId)!=null?Lt:"",toolName:(Mr=f.toolName)!=null?Mr:"",description:($t=f.description)!=null?$t:"",resolvedAt:Date.now()}};p(R)}}else Re==="error"&&f.error&&r({type:"error",error:f.error instanceof Error?f.error:new Error(String(f.error))})}}}}}};function ra(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${n}_${t}`}function Xn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${n}_${t}`}function Pn(){let n=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${n}_${t}`}var nr="[Image]";function oa(n){return typeof n=="string"?[{type:"text",text:n}]:n}function ia(n){return typeof n=="string"?n:n.filter(t=>t.type==="text").map(t=>t.text).join("")}function aa(n){return typeof n=="string"?!1:n.some(t=>t.type==="image")}function la(n){return typeof n=="string"?[]:n.filter(t=>t.type==="image")}function sr(n){return{type:"text",text:n}}function ca(n,t){return{type:"image",image:n,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function da(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;t({type:"image",image:o,mimeType:n.type,alt:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function ua(n,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var pa=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ol=["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"],xn=[...pa,...ol];function il(n){return pa.includes(n)||n.startsWith("image/")}function rr(n){return il(n.type)}async function ga(n){return new Promise((t,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;rr(n)?t({type:"image",image:o,mimeType:n.type,alt:n.name}):t({type:"file",data:o,mimeType:n.type,filename:n.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(n)})}function ha(n,t=xn,r=10*1024*1024){return t.includes(n.type)?n.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${t.join(", ")}`}}function al(n){let t=n.split(".");return t.length>1?t.pop().toLowerCase():""}function ma(n,t){let r=al(t).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"}[n]||r||"FILE"}var or=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let e=r.AudioContext||r.webkitAudioContext;this.ctx=new e({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),r=d,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let e=this.ensureContext(),o=this.pcmToFloat32(r),s=e.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let i=e.createBufferSource();i.buffer=s,i.connect(e.destination);let a=e.currentTime;this.nextStartTime<a&&(this.nextStartTime=a),i.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(i),this.pendingCount++,this.playing=!0,i.onended=()=>{let d=this.activeSources.indexOf(i);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),e=new Float32Array(r),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<r;s++){let i=o.getInt16(s*2,!0);e[s]=i/32768}return e}};var ir=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,r,e,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(r),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let i=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(i);let a=0;for(let v=0;v<i.length;v++)a+=i[v]*i[v];let d=Math.sqrt(a/i.length);(e==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Es=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new ir;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,r,e;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",i=(t=this.config)==null?void 0:t.host,a=(r=this.config)==null?void 0:r.agentId,d=(e=this.config)==null?void 0:e.clientToken;if(!a||!d)throw new Error("agentId and clientToken are required");if(!i)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${i}/ws/agents/${a}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let v=`${s}//${i}/ws/agents/${a}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((m,w)=>{if(!this.ws)return w(new Error("WebSocket not created"));let C=!1,y=x=>{C||(C=!0,clearTimeout(A),w(new Error(x)))},A=setTimeout(()=>y("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(A),m())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+v+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let H=x.code!==1006?` (code ${x.code})`:"";y("WebSocket connection failed"+H+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(r=>r(new Error("WebSocket error"))),this.statusCallbacks.forEach(r=>r("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let r=JSON.parse(t.data);this.handleWebSocketMessage(r)}catch{this.errorCallbacks.forEach(e=>e(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var r,e;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(r=t.response.audio)!=null&&r.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(e=t.response.audio)!=null&&e.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new or(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(r=>r("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(r=>r("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,r,e,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let i=this.audioContext,a=(r=(t=this.config)==null?void 0:t.pauseDuration)!=null?r:2e3,d=(o=(e=this.config)==null?void 0:e.silenceThreshold)!=null?o:.01;this.vad.start(i,this.mediaStream,"silence",{threshold:d,duration:a},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(m=>m("processing")),this.processingStartCallbacks.forEach(m=>m());let v=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:v});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(s){throw this.errorCallbacks.forEach(i=>i(s)),this.statusCallbacks.forEach(i=>i("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,i;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let r=this.audioContext,e=(i=(s=this.config)==null?void 0:s.silenceThreshold)!=null?i:.01;this.vad.start(r,this.mediaStream,"speech",{threshold:e,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(r=>r(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var r;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(e=>e(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(e=>e("error"));return}try{let e=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:e,format:o,sampleRate:16e3,voiceId:(r=this.config)==null?void 0:r.voiceId,requestId:s}))}catch(e){this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((r,e)=>{let o=new FileReader;o.onload=()=>{let i=o.result.split(",")[1];r(i)},o.onerror=e,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let r=atob(t.base64),e=new Uint8Array(r.length);for(let c=0;c<r.length;c++)e[c]=r.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,i=new Blob([e],{type:s}),a=URL.createObjectURL(i),d=new Audio(a);this.currentAudio=d,this.currentAudioUrl=a,d.onended=()=>{URL.revokeObjectURL(a),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Rn=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let e=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!e)throw new Error("Browser speech recognition not supported");this.recognition=new e,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var a;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),i=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:i?.8:.5,provider:"browser"})),i&&!((a=this.config)!=null&&a.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(e){throw this.errorCallbacks.forEach(o=>o(e)),this.statusCallbacks.forEach(o=>o("error")),e}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Hn(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Es(n.runtype);case"browser":if(!Rn.isSupported())throw new Error("Browser speech recognition not supported");return new Rn(n.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function ar(n){if((n==null?void 0:n.type)==="runtype"&&n.runtype)return Hn({type:"runtype",runtype:n.runtype});if(Rn.isSupported())return Hn({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(n){try{return ar(n),!0}catch{return!1}}var Gn=class n{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var r,e,o,s,i,a,d;t.type==="message"?(this.upsertMessage(t.message),(r=t.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(e=t.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.type==="error"&&(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((i=this.agentExecution)==null?void 0:i.status)==="running"&&(this.agentExecution.status="error"),(d=(a=this.callbacks).onError)==null||d.call(a,t.error))};var e;this.messages=[...(e=t.initialMessages)!=null?e:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Wn(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,e;return(e=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?e:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var r,e,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=Hn(s);let i=(r=this.config.voiceRecognition)!=null?r:{},a=(e=i.processingText)!=null?e:"\u{1F3A4} Processing voice...",d=(o=i.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:a,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let v=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=v.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var v,p,m,w,C,y;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((v=c.transcript)!=null&&v.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((m=c.text)!=null&&m.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(w=c.text)!=null&&w.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let A=(y=this.pendingVoiceAssistantMessageId)!=null?y:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;A&&this.ttsSpokenMessageIds.add(A)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var v,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(v=this.callbacks).onVoiceStatusChanged)==null||p.call(v,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,e,o,s,i,a,d,c,v;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((e=t.runtype)==null?void 0:e.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(i=t.runtype)==null?void 0:i.voiceId,pauseDuration:(a=t.runtype)==null?void 0:a.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(v=t.browser)==null?void 0:v.continuous}};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(t=this.callbacks).onError)==null||r.call(t,e instanceof Error?e:new Error(String(e))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new Wn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:d,streaming:c=!1,voiceProcessing:v}=t,m={id:i!=null?i:r==="user"?Xn():r==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:e,createdAt:a!=null?a:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...v!==void 0&&{voiceProcessing:v}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let e of t){let{role:o,content:s,llmContent:i,contentParts:a,id:d,createdAt:c,sequence:v,streaming:p=!1}=e,w={id:d!=null?d:o==="user"?Xn():o==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:p,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(t,r){var c,v,p,m,w;let e=t.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=Xn(),s=Pn(),i={id:o,role:"user",content:e||nr,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(i),this.setStreaming(!0);let a=new AbortController;this.abortController=a;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:a.signal,assistantMessageId:s},this.handleEvent)}catch(C){let y=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!y){let A={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(A)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,y||(C instanceof Error?(p=(v=this.callbacks).onError)==null||p.call(v,C):(w=(m=this.callbacks).onError)==null||w.call(m,new Error(String(C))))}}async continueConversation(){var o,s,i,a,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=Pn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let e=[...this.messages];try{await this.client.dispatch({messages:e,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(c){let v={id:t,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(v),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(i=(s=this.callbacks).onError)==null||i.call(s,c):(d=(a=this.callbacks).onError)==null||d.call(a,new Error(String(c)))}}async connectStream(t,r){var o,s,i;if(this.streaming)return;(o=this.abortController)==null||o.abort();let e=!1;for(let a of this.messages)a.streaming&&(a.streaming=!1,e=!0);e&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(a){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(i=(s=this.callbacks).onError)==null||i.call(s,a instanceof Error?a:new Error(String(a)))}}async resolveApproval(t,r){var d,c,v;let e=`approval-${t.id}`,o={...t,status:r,resolvedAt:Date.now()},s={id:e,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let i=this.config.approval,a=i&&typeof i=="object"?i.onDecision:void 0;try{let p;if(a?p=await a({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),p){let m=null;if(p instanceof Response){if(!p.ok){let w=await p.json().catch(()=>null);throw new Error((d=w==null?void 0:w.error)!=null?d:`Approval request failed: ${p.status}`)}m=p.body}else p instanceof ReadableStream&&(m=p);m?await this.connectStream(m):r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(v=(c=this.callbacks).onError)==null||v.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(e=>{var o;return{...e,streaming:!1,sequence:(o=e.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let e=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!e)return;if(this.ttsSpokenMessageIds.has(e.id)){this.ttsSpokenMessageIds.delete(e.id);return}let o=e.content;o.trim()&&this.speak(o,t)}speak(t,r){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let e=window.speechSynthesis;e.cancel();let o=new SpeechSynthesisUtterance(t),s=e.getVoices();if(r.voice){let i=s.find(a=>a.name===r.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=r.pickVoice?r.pickVoice(s):n.pickBestVoice(s));r.rate!==void 0&&(o.rate=r.rate),r.pitch!==void 0&&(o.pitch=r.pitch),setTimeout(()=>e.speak(o),50)}static pickBestVoice(t){var e;let r=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of r){let s=t.find(i=>i.name===o);if(s)return s}return(e=t.find(o=>o.lang.startsWith("en")))!=null?e:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),e=this.messages.findIndex(o=>o.id===r.id);if(e===-1){this.appendMessage(r);return}this.messages=this.messages.map((o,s)=>s===e?{...o,...r}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,e)=>{var d,c;let o=new Date(r.createdAt).getTime(),s=new Date(e.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let i=(d=r.sequence)!=null?d:0,a=(c=e.sequence)!=null?c:0;return i!==a?i-a:r.id.localeCompare(e.id)})}};var g=(n,t)=>{let r=document.createElement(n);return t&&(r.className=t),r};var ll=Xa(require("lucide"),1),ie=(n,t=24,r="currentColor",e=2)=>{try{let o=n.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=ll[o];return s?cl(s,t,r,e):(console.warn(`Lucide icon "${n}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${n}":`,o),null}};function cl(n,t,r,e){if(!n||!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.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(([c,v])=>{c!=="stroke"&&d.setAttribute(c,String(v))}),o.appendChild(d)}}}),o}var lr={allowedTypes:xn,maxFileSize:10*1024*1024,maxFiles:4};function dl(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ul(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-json":"file"}var Bn=class n{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:lr.allowedTypes,maxFileSize:(e=t.maxFileSize)!=null?e:lr.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:lr.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:lr.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,e,o,s,i,a,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=ha(c,this.config.allowedTypes,this.config.maxFileSize);if(!v.valid){let p=(o=v.error)!=null&&o.includes("type")?"type":"size";(i=(s=this.config).onFileRejected)==null||i.call(s,c,p);continue}try{let p=await ga(c),m=rr(c)?URL.createObjectURL(c):null,w={id:dl(),file:c,previewUrl:m,contentPart:p};this.attachments.push(w),this.renderPreview(w)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(a=this.config).onAttachmentsChange)==null||d.call(a,this.getAttachments())}}removeAttachment(t){var s,i,a;let r=this.attachments.findIndex(d=>d.id===t);if(r===-1)return;let e=this.attachments[r];e.previewUrl&&URL.revokeObjectURL(e.previewUrl),this.attachments.splice(r,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var t,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=rr(t.file),e=g("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",t.id),e.style.width="48px",e.style.height="48px",r&&t.previewUrl){let i=g("img");i.src=t.previewUrl,i.alt=t.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",e.appendChild(i)}else{let i=g("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=ul(t.file.type),d=ie(a,20,"var(--cw-muted, #6b7280)",1.5);d&&i.appendChild(d);let c=g("span");c.textContent=ma(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--cw-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",i.appendChild(c),e.appendChild(i)}let o=g("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ie("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(t.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new n({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Hr=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},pl=n=>{var s,i,a;let t=(s=n==null?void 0:n.colorScheme)!=null?s:"light",r=(i=n==null?void 0:n.theme)!=null?i:{},e=(a=n==null?void 0:n.darkTheme)!=null?a:r;return t==="light"?r:t==="dark"||Hr()==="dark"?e:r},fa=n=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{n(Hr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>n(Hr());r.addEventListener?(r.addEventListener("change",e),t.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),t.push(()=>r.removeListener(e)))}return()=>{t.forEach(r=>r())}},cr=(n,t)=>{let r=pl(t);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);n.style.setProperty(`--cw-${s}`,String(o))})};var va=require("idiomorph"),wa=(n,t,r={})=>{let{preserveTypingAnimation:e=!0}=r;va.Idiomorph.morph(n,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&e&&(o.classList.contains("tvw-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};var Rt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var sn={"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 Ms=(n,t)=>{let r=g("button");r.type="button",r.innerHTML=`
8
8
  <span class="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-bg-cw-primary tvw-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="tvw-rounded-full tvw-object-cover" alt="" style="display:none" />
10
10
  <span class="tvw-flex tvw-flex-col tvw-items-start tvw-text-left">
@@ -12,23 +12,23 @@
12
12
  <span class="tvw-text-xs tvw-text-cw-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="tvw-ml-2 tvw-grid tvw-place-items-center tvw-rounded-full tvw-bg-cw-primary tvw-text-cw-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,r.addEventListener("click",t);let e=s=>{var x,k,J,E,I,T,B,le,z,U,K,j;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(k=i.title)!=null?k:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(J=i.subtitle)!=null?J:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let ye=(E=i.agentIconSize)!=null?E:"40px";if(v.style.height=ye,v.style.width=ye,v.innerHTML="",i.agentIconName){let se=parseFloat(ye)||24,Y=ie(i.agentIconName,se*.6,"#ffffff",2);Y?(v.appendChild(Y),v.style.display=""):(v.textContent=(I=i.agentIconText)!=null?I:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(T=i.agentIconText)!=null?T:"\u{1F4AC}",v.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let ye=(B=i.agentIconSize)!=null?B:"40px";d.style.height=ye,d.style.width=ye,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(d.src=i.iconUrl,d.style.display="block"):d.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(le=i.callToActionIconSize)!=null?le:"32px";m.style.height=ye,m.style.width=ye,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let se=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,se=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let Y=parseFloat(ye)||24,_=Math.max(Y-se,8),O=ie(i.callToActionIconName,_,"currentColor",2);O?m.appendChild(O):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(U=i.callToActionIconText)!=null?U:"\u2197"}let w=i.position&&nn[i.position]?nn[i.position]:nn["bottom-right"],b="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${b} ${w}`;let y="1px solid #e5e7eb",S="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(K=i.border)!=null?K:y,r.style.boxShadow=(j=i.shadow)!=null?j:S},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var mn=n=>{var U,K,j,ye,se,Y,_,O,Q,ue,Be,Et,dt,gt,Ht,Ne,ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt;let{config:t,showClose:r=!0}=n,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(U=t==null?void 0:t.launcher)!=null?U:{},s=(K=o.headerIconSize)!=null?K:"48px",i=(j=o.closeButtonSize)!=null?j:"32px",a=(ye=o.closeButtonPlacement)!=null?ye:"inline",u=(se=o.headerIconHidden)!=null?se:!1,c=o.headerIconName,v=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!u)if(c){let pe=parseFloat(s)||24,Ce=ie(c,pe*.6,"#ffffff",1);Ce?v.replaceChildren(Ce):v.textContent=(_=(Y=t==null?void 0:t.launcher)==null?void 0:Y.agentIconText)!=null?_:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let pe=g("img");pe.src=t.launcher.iconUrl,pe.alt="",pe.className="tvw-rounded-xl tvw-object-cover",pe.style.height=s,pe.style.width=s,v.replaceChildren(pe)}else v.textContent=(ue=(Q=t==null?void 0:t.launcher)==null?void 0:Q.agentIconText)!=null?ue:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Et=(Be=t==null?void 0:t.launcher)==null?void 0:Be.title)!=null?Et:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(gt=(dt=t==null?void 0:t.launcher)==null?void 0:dt.subtitle)!=null?gt:"Here to help you get answers fast",d.append(m,w),u?e.append(d):e.append(v,d);let b=(Ht=o.clearChat)!=null?Ht:{},y=(Ne=b.enabled)!=null?Ne:!0,S=(ne=b.placement)!=null?ne:"inline",x=null,k=null;if(y){let pe=(be=b.size)!=null?be:"32px",Ce=(Re=b.iconName)!=null?Re:"refresh-cw",qe=(Fe=b.iconColor)!=null?Fe:"",Bt=(Ue=b.backgroundColor)!=null?Ue:"",Mt=(Nt=b.borderWidth)!=null?Nt:"",Vt=(de=b.borderColor)!=null?de:"",F=(X=b.borderRadius)!=null?X:"",Qe=(at=b.paddingX)!=null?at:"",N=(vt=b.paddingY)!=null?vt:"",G=(Tt=b.tooltipText)!=null?Tt:"Clear chat",re=(yt=b.showTooltip)!=null?yt:!0;k=g("div",S==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),S==="top-right"&&(k.style.right="48px"),x=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=pe,x.style.width=pe,x.type="button",x.setAttribute("aria-label",G);let $e=ie(Ce,"20px",qe||"",1);if($e&&x.appendChild($e),qe&&(x.style.color=qe,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),Mt||Vt){let oe=Mt||"0px",Je=Vt||"transparent";x.style.border=`${oe} solid ${Je}`,x.classList.remove("tvw-border-none")}if(F&&(x.style.borderRadius=F,x.classList.remove("tvw-rounded-full")),Qe?(x.style.paddingLeft=Qe,x.style.paddingRight=Qe):(x.style.paddingLeft="",x.style.paddingRight=""),N?(x.style.paddingTop=N,x.style.paddingBottom=N):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),re&&G&&x&&k){let oe=null,Je=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=G;let ce=g("div");ce.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(ce);let D=x.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${D.left+D.width/2}px`,oe.style.top=`${D.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},Ke=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};k.addEventListener("mouseenter",Je),k.addEventListener("mouseleave",Ke),x.addEventListener("focus",Je),x.addEventListener("blur",Ke),k._cleanupTooltip=()=>{Ke(),k&&(k.removeEventListener("mouseenter",Je),k.removeEventListener("mouseleave",Ke)),x&&(x.removeEventListener("focus",Je),x.removeEventListener("blur",Ke))}}S==="inline"&&e.appendChild(k)}let J=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&S==="inline"?"":"tvw-ml-auto"),E=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=i,E.style.width=i,E.type="button";let I=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",T=(ee=o.closeButtonShowTooltip)!=null?ee:!0;E.setAttribute("aria-label",I),E.style.display=r?"":"none";let B=(Le=o.closeButtonIconName)!=null?Le:"x",le=(bt=o.closeButtonIconText)!=null?bt:"\xD7",z=ie(B,"20px",o.closeButtonColor||"",1);if(z?E.appendChild(z):E.textContent=le,o.closeButtonColor?(E.style.color=o.closeButtonColor,E.classList.remove("tvw-text-cw-muted")):(E.style.color="",E.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(E.style.backgroundColor=o.closeButtonBackgroundColor,E.classList.remove("hover:tvw-bg-gray-100")):(E.style.backgroundColor="",E.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let pe=o.closeButtonBorderWidth||"0px",Ce=o.closeButtonBorderColor||"transparent";E.style.border=`${pe} solid ${Ce}`,E.classList.remove("tvw-border-none")}else E.style.border="",E.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(E.style.borderRadius=o.closeButtonBorderRadius,E.classList.remove("tvw-rounded-full")):(E.style.borderRadius="",E.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(E.style.paddingLeft=o.closeButtonPaddingX,E.style.paddingRight=o.closeButtonPaddingX):(E.style.paddingLeft="",E.style.paddingRight=""),o.closeButtonPaddingY?(E.style.paddingTop=o.closeButtonPaddingY,E.style.paddingBottom=o.closeButtonPaddingY):(E.style.paddingTop="",E.style.paddingBottom=""),J.appendChild(E),T&&I){let pe=null,Ce=()=>{if(pe)return;pe=g("div","tvw-clear-chat-tooltip"),pe.textContent=I;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",pe.appendChild(Bt);let Mt=E.getBoundingClientRect();pe.style.position="fixed",pe.style.left=`${Mt.left+Mt.width/2}px`,pe.style.top=`${Mt.top-8}px`,pe.style.transform="translate(-50%, -100%)",document.body.appendChild(pe)},qe=()=>{pe&&pe.parentNode&&(pe.parentNode.removeChild(pe),pe=null)};J.addEventListener("mouseenter",Ce),J.addEventListener("mouseleave",qe),E.addEventListener("focus",Ce),E.addEventListener("blur",qe),J._cleanupTooltip=()=>{qe(),J.removeEventListener("mouseenter",Ce),J.removeEventListener("mouseleave",qe),E.removeEventListener("focus",Ce),E.removeEventListener("blur",qe)}}return a!=="top-right"&&e.appendChild(J),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:E,closeButtonWrapper:J,clearChatButton:x,clearChatButtonWrapper:k}},Bn=(n,t,r)=>{var i,a,u,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(u=e.clearChat)==null?void 0:u.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Rr=n=>mn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Hr=n=>{var b,y,S,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(b=t==null?void 0:t.launcher)!=null?b:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(y=o.title)!=null?y:"Chat Assistant",s.appendChild(i);let a=(S=o.closeButtonSize)!=null?S:"32px",u=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(x=o.closeButtonIconName)!=null?x:"x",d=ie(v,"20px",o.closeButtonColor||"",2);d?c.appendChild(d):c.textContent="\xD7",e&&c.addEventListener("click",e),u.appendChild(c),s.appendChild(u);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Br=n=>{var E,I,T,B,le,z,U,K;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(E=t==null?void 0:t.launcher)!=null?E:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),u=(I=s.headerIconSize)!=null?I:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=u,c.style.width=u;let v=s.headerIconName;if(v){let j=parseFloat(u)||24,ye=ie(v,j*.5,"#ffffff",2);ye?c.replaceChildren(ye):c.textContent=(T=s.agentIconText)!=null?T:"\u{1F4AC}"}else if(s.iconUrl){let j=g("img");j.src=s.iconUrl,j.alt="",j.className="tvw-rounded-xl tvw-object-cover",j.style.height=u,j.style.width=u,c.replaceChildren(j)}else c.textContent=(B=s.agentIconText)!=null?B:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(le=s.title)!=null?le:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",d.append(m,w),a.append(c,d);let b=(U=s.closeButtonSize)!=null?U:"32px",y=g("div",""),S=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");S.style.height=b,S.style.width=b,S.type="button",S.setAttribute("aria-label","Close chat"),S.style.display=r?"":"none";let x=(K=s.closeButtonIconName)!=null?K:"x",k=ie(x,"20px",s.closeButtonColor||"",2);k?S.appendChild(k):S.textContent="\xD7",e&&S.addEventListener("click",e),y.appendChild(S),a.appendChild(y),i.appendChild(a);let J=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return J.textContent="Online and ready to help",i.appendChild(J),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:w,closeButton:S,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},lr={default:Rr,minimal:Hr,expanded:Br},Fr=n=>{var t;return(t=lr[n])!=null?t:lr.default},Yn=(n,t,r)=>{var i,a,u;if(t!=null&&t.render){let c=t.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let d=g("span"),m=g("span"),w=g("button");w.style.display="none";let b=g("div");return b.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:m,closeButton:w,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=Fr(e)({config:n,showClose:(u=(a=t==null?void 0:t.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?u:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var il=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Xn=n=>{var ne,be,Re,Fe,Ue,Nt,de,X,at,vt,Tt,yt,Kt,ee,Le,bt,pe,Ce,qe,Bt,Mt,Vt,F,Qe,N,G,re,$e,oe,Je,Ke;let{config:t}=n,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(be=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?be:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=(Fe=(Re=t==null?void 0:t.theme)==null?void 0:Re.inputFontFamily)!=null?Fe:"sans-serif",a=(Nt=(Ue=t==null?void 0:t.theme)==null?void 0:Ue.inputFontWeight)!=null?Nt:"400";s.style.fontFamily=il(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let d=()=>{s.style.height="auto";let ce=Math.min(s.scrollHeight,v);s.style.height=`${ce}px`};s.addEventListener("input",d),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(de=t==null?void 0:t.sendButton)!=null?de:{},w=(X=m.useIcon)!=null?X:!1,b=(at=m.iconText)!=null?at:"\u2191",y=m.iconName,S=(vt=m.tooltipText)!=null?vt:"Send message",x=(Tt=m.showTooltip)!=null?Tt:!1,k=(yt=m.size)!=null?yt:"40px",J=m.backgroundColor,E=m.textColor,I=g("div","tvw-send-button-wrapper"),T=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(T.type="submit",w){if(T.style.width=k,T.style.height=k,T.style.minWidth=k,T.style.minHeight=k,T.style.fontSize="18px",T.style.lineHeight="1",T.innerHTML="",y){let ce=parseFloat(k)||24,D=E&&typeof E=="string"&&E.trim()?E.trim():"currentColor",Se=ie(y,ce,D,2);Se?(T.appendChild(Se),T.style.color=D):(T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white"))}else T.textContent=b,E?T.style.color=E:T.classList.add("tvw-text-white");J?T.style.backgroundColor=J:T.classList.add("tvw-bg-cw-primary")}else T.textContent=(ee=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?ee:"Send",E?T.style.color=E:T.classList.add("tvw-text-white");if(m.borderWidth&&(T.style.borderWidth=m.borderWidth,T.style.borderStyle="solid"),m.borderColor&&(T.style.borderColor=m.borderColor),m.paddingX?(T.style.paddingLeft=m.paddingX,T.style.paddingRight=m.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),m.paddingY?(T.style.paddingTop=m.paddingY,T.style.paddingBottom=m.paddingY):(T.style.paddingTop="",T.style.paddingBottom=""),x&&S){let ce=g("div","tvw-send-button-tooltip");ce.textContent=S,I.appendChild(ce)}I.appendChild(T);let B=(Le=t==null?void 0:t.voiceRecognition)!=null?Le:{},le=B.enabled===!0,z=null,U=null,K=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),j=((bt=B.provider)==null?void 0:bt.type)==="runtype";if(le&&(K||j)){U=g("div","tvw-send-button-wrapper"),z=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let ce=(pe=B.iconName)!=null?pe:"mic",D=(Ce=B.iconSize)!=null?Ce:k,Se=parseFloat(D)||24,et=(qe=B.backgroundColor)!=null?qe:J,tt=(Bt=B.iconColor)!=null?Bt:E;z.style.width=D,z.style.height=D,z.style.minWidth=D,z.style.minHeight=D,z.style.fontSize="18px",z.style.lineHeight="1";let Yt=tt||"currentColor",Gt=ie(ce,Se,Yt,1.5);Gt?(z.appendChild(Gt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),et?z.style.backgroundColor=et:z.classList.add("tvw-bg-cw-primary"),tt?z.style.color=tt:!tt&&!E&&z.classList.add("tvw-text-white"),B.borderWidth&&(z.style.borderWidth=B.borderWidth,z.style.borderStyle="solid"),B.borderColor&&(z.style.borderColor=B.borderColor),B.paddingX&&(z.style.paddingLeft=B.paddingX,z.style.paddingRight=B.paddingX),B.paddingY&&(z.style.paddingTop=B.paddingY,z.style.paddingBottom=B.paddingY),U.appendChild(z);let Ye=(Mt=B.tooltipText)!=null?Mt:"Start voice recognition";if(((Vt=B.showTooltip)!=null?Vt:!1)&&Ye){let fn=g("div","tvw-send-button-tooltip");fn.textContent=Ye,U.appendChild(fn)}}let se=(F=t==null?void 0:t.attachments)!=null?F:{},Y=se.enabled===!0,_=null,O=null,Q=null,ue=null;if(Y){ue=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),ue.style.display="none",Q=g("input"),Q.type="file",Q.accept=((Qe=se.allowedTypes)!=null?Qe:bn).join(","),Q.multiple=((N=se.maxFiles)!=null?N:4)>1,Q.style.display="none",Q.setAttribute("aria-label","Attach files"),O=g("div","tvw-send-button-wrapper"),_=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),_.type="button",_.setAttribute("aria-label",(G=se.buttonTooltipText)!=null?G:"Attach file");let ce=(re=se.buttonIconName)!=null?re:"paperclip",D=k,Se=parseFloat(D)||40,et=Math.round(Se*.6);_.style.width=D,_.style.height=D,_.style.minWidth=D,_.style.minHeight=D,_.style.fontSize="18px",_.style.lineHeight="1",_.style.backgroundColor="transparent",_.style.color="var(--cw-primary, #111827)",_.style.border="none",_.style.borderRadius="6px",_.style.transition="background-color 0.15s ease",_.addEventListener("mouseenter",()=>{_.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),_.addEventListener("mouseleave",()=>{_.style.backgroundColor="transparent"});let tt=ie(ce,et,"currentColor",1.5);tt?_.appendChild(tt):_.textContent="\u{1F4CE}",_.addEventListener("click",Ye=>{Ye.preventDefault(),Q==null||Q.click()}),O.appendChild(_);let Yt=($e=se.buttonTooltipText)!=null?$e:"Attach file",Gt=g("div","tvw-send-button-tooltip");Gt.textContent=Yt,O.appendChild(Gt)}o.addEventListener("click",ce=>{ce.target!==T&&ce.target!==I&&ce.target!==z&&ce.target!==U&&ce.target!==_&&ce.target!==O&&s.focus()}),ue&&(ue.style.gap="8px",o.append(ue)),Q&&o.append(Q),o.append(s);let Be=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Et=g("div","tvw-flex tvw-items-center tvw-gap-2");O&&Et.append(O);let dt=g("div","tvw-flex tvw-items-center tvw-gap-1");U&&dt.append(U),dt.append(I),Be.append(Et,dt),o.append(Be);let gt=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ht=(oe=t==null?void 0:t.statusIndicator)!=null?oe:{},Ne=(Je=Ht.visible)!=null?Je:!0;return gt.style.display=Ne?"":"none",gt.textContent=(Ke=Ht.idleText)!=null?Ke:"Online",r.append(e,o,gt),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:T,sendButtonWrapper:I,micButton:z,micButtonWrapper:U,statusText:gt,attachmentButton:_,attachmentButtonWrapper:O,attachmentInput:Q,attachmentPreviewsContainer:ue,actionsRow:Be,leftActions:Et,rightActions:dt}};var pa=n=>{var u,c,v,d,m,w,b;if(!((c=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?c:!0)){let y=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),S=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(d=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?d:"100%";return y.style.width=x,S.style.width="100%",y.appendChild(S),{wrapper:y,panel:S}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&nn[r.position]?nn[r.position]:nn["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(b=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?b:n==null?void 0:n.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},ga=(n,t=!0)=>{var w,b,y,S,x,k,J;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,o=((b=n==null?void 0:n.layout)==null?void 0:b.showHeader)!==!1,s=e?Yn(n,e,{showClose:t}):mn({config:n,showClose:t}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),u=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(S=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?S:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(k=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",a.append(u,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=Xn({config:n}),m=((J=n==null?void 0:n.layout)==null?void 0:J.showFooter)!==!1;return o?Bn(r,s,n):(s.header.style.display="none",Bn(r,s,n)),r.append(i),m||(d.footer.style.display="none"),r.append(d.footer),{container:r,body:i,messagesWrapper:v,suggestions:d.suggestions,textarea:d.textarea,sendButton:d.sendButton,sendButtonWrapper:d.sendButtonWrapper,micButton:d.micButton,micButtonWrapper:d.micButtonWrapper,composerForm:d.composerForm,statusText:d.statusText,introTitle:u,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:d.footer,attachmentButton:d.attachmentButton,attachmentButtonWrapper:d.attachmentButtonWrapper,attachmentInput:d.attachmentInput,attachmentPreviewsContainer:d.attachmentPreviewsContainer,actionsRow:d.actionsRow,leftActions:d.leftActions,rightActions:d.rightActions}};var al=320,ll=320,cl=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),dl=(n,t,r)=>{if(n.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),t&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return n.forEach((a,u)=>{var d;let c=g("img");c.alt=((d=a.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${al}px`,c.style.maxHeight=`${ll}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},Fn=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(r),n.appendChild(e),n.appendChild(o),n},$r=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:Fn};if(t){let o=t(e);if(o!==null)return o}return Fn()},ul=(n,t)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=t==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},ma=(n,t)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?r.textContent=t.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},pl=(n,t="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Or=(n,t,r)=>{var w,b,y,S,x,k;let e=(w=t.showCopy)!=null?w:!0,o=(b=t.showUpvote)!=null?b:!0,s=(y=t.showDownvote)!=null?y:!0,i=(S=t.visibility)!=null?S:"hover",a=(x=t.align)!=null?x:"right",u=(k=t.layout)!=null?k:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[u],d=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);d.id=`actions-${n.id}`,d.setAttribute("data-actions-for",n.id);let m=(J,E,I)=>{let T=document.createElement("button");T.className="tvw-message-action-btn",T.setAttribute("aria-label",E),T.setAttribute("title",E),T.setAttribute("data-action",I);let B=ie(J,14,"currentColor",2);return B&&T.appendChild(B),T};return e&&d.appendChild(m("copy","Copy message","copy")),o&&d.appendChild(m("thumbs-up","Upvote","upvote")),s&&d.appendChild(m("thumbs-down","Downvote","downvote")),d},Gn=(n,t,r,e,o,s)=>{var U,K,j,ye,se,Y,_;let i=r!=null?r:{},a=(U=i.layout)!=null?U:"bubble",u=i.avatar,c=i.timestamp,v=(K=u==null?void 0:u.show)!=null?K:!1,d=(j=c==null?void 0:c.show)!=null?j:!1,m=(ye=u==null?void 0:u.position)!=null?ye:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",b=pl(n.role,a),y=g("div",b.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let S=cl(n),x=(_=(Y=n.content)==null?void 0:Y.trim())!=null?_:"",J=S.length>0&&x===nr,E=document.createElement("div"),I=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),T=null;if(J?(T=document.createElement("div"),T.innerHTML=I,T.style.display="none",E.appendChild(T)):E.innerHTML=I,d&&w==="inline"&&n.createdAt){let O=ma(n,c);O.classList.add("tvw-ml-2","tvw-inline"),E.appendChild(O)}if(S.length>0){let O=dl(S,!J&&!!x,()=>{J&&T&&(T.style.display="")});O?y.appendChild(O):J&&T&&(T.style.display="")}if(y.appendChild(E),d&&w==="below"&&n.createdAt){let O=ma(n,c);O.classList.add("tvw-mt-1"),y.appendChild(O)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let O=$r("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);O&&y.appendChild(O)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let O=Or(n,e,o);y.appendChild(O)}if(!v||n.role==="system")return y;let le=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=ul(u,n.role);return m==="right"||m==="left"&&n.role==="user"?le.append(y,z):le.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),le},ha=(n,t,r,e,o,s)=>{let i=r!=null?r:{};return n.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):Gn(n,t,r,e,o,s)};var Zn=new Set,fa=(n,t)=>{let r=Zn.has(n),e=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let u=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},Nr=n=>{let t=n.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let e=Zn.has(n.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Ki(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let u=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=g("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),b=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return b.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(b),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?u.appendChild(x):u.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var Qn=new Set,wa=(n,t,r)=>{var c;let e=Qn.has(n),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"true":"false");let a=s.querySelector(".tvw-ml-auto"),u=a==null?void 0:a.querySelector(":scope > .tvw-flex.tvw-items-center");if(u){u.innerHTML="";let v=o.toggleTextColor||o.headerTextColor||"currentColor",d=ie(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Dr=(n,t)=>{var y;let r=n.toolCall,e=(y=t==null?void 0:t.toolCall)!=null?y:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=Qn.has(n.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),u=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Yi(r),a.appendChild(u);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=ie(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):c.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(c),i.append(a,m);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let S=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?S.style.color=e.contentTextColor:e.headerTextColor&&(S.style.color=e.headerTextColor),S.textContent=r.name,w.appendChild(S)}if(r.args!==void 0){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=Ts(r.args),S.append(x,k),w.appendChild(S)}if(r.chunks&&r.chunks.length){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=r.chunks.join(`
16
- `),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&r.result!==void 0){let S=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let k=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(k.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(k.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(k.style.color=e.codeBlockTextColor),k.textContent=Ts(r.result),S.append(x,k),w.appendChild(S)}if(r.status==="complete"&&typeof r.duration=="number"){let S=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(S.style.color=e.contentTextColor),S.textContent=`Duration: ${r.duration}ms`,w.appendChild(S)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let S=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,S,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var jr=(n,t)=>{var y,S,x,k,J,E,I,T,B,le,z;let r=n.approval,e=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let u=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(y=e==null?void 0:e.titleColor)!=null?y:"currentColor",v=ie(u,20,c,2);v&&a.appendChild(v);let d=g("div","tvw-flex-1 tvw-min-w-0"),m=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(S=e==null?void 0:e.title)!=null?S:"Approval Required",m.appendChild(w),!o){let U=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");U.setAttribute("data-approval-status",r.status),r.status==="approved"?(U.className+=" tvw-approval-badge-approved",U.textContent="Approved"):r.status==="denied"?(U.className+=" tvw-approval-badge-denied",U.textContent="Denied"):r.status==="timeout"&&(U.className+=" tvw-approval-badge-timeout",U.textContent="Timeout"),m.appendChild(U)}d.appendChild(m);let b=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(b.style.color=e.descriptionColor),b.textContent=r.description,d.appendChild(b),r.parameters){let U=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(U.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(U.style.color=e.parameterTextColor),U.style.fontSize="0.75rem",U.style.lineHeight="1rem",U.textContent=Ts(r.parameters),d.appendChild(U)}if(o){let U=g("div","tvw-flex tvw-gap-2 tvw-mt-2");U.setAttribute("data-approval-buttons","true");let K=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");K.type="button",K.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",K.style.color=(k=e==null?void 0:e.approveButtonTextColor)!=null?k:"#ffffff",K.setAttribute("data-approval-action","approve");let j=ie("shield-check",14,(J=e==null?void 0:e.approveButtonTextColor)!=null?J:"#ffffff",2);j&&(j.style.marginRight="4px",K.appendChild(j));let ye=document.createTextNode((E=e==null?void 0:e.approveLabel)!=null?E:"Approve");K.appendChild(ye);let se=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");se.type="button",se.style.backgroundColor=(I=e==null?void 0:e.denyButtonColor)!=null?I:"transparent",se.style.color=(T=e==null?void 0:e.denyButtonTextColor)!=null?T:"#dc2626",se.style.border=`1px solid ${(B=e==null?void 0:e.denyButtonTextColor)!=null?B:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let Y=ie("shield-x",14,(le=e==null?void 0:e.denyButtonTextColor)!=null?le:"#dc2626",2);Y&&(Y.style.marginRight="4px",se.appendChild(Y));let _=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(_),U.append(K,se),d.appendChild(U)}return i.append(a,d),s.appendChild(i),s};var va=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),d=o?o.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(w=>{let b=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");b.type="button",b.textContent=w,b.disabled=d,a!=null&&a.fontFamily&&(b.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(b.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(b.style.paddingLeft=a.paddingX,b.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(b.style.paddingTop=a.paddingY,b.style.paddingBottom=a.paddingY),b.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(b),t.push(b)}),n.appendChild(v)}}};var Ls=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ws=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}};function es(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var gl={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},ml={bg:"#f3f4f6",text:"#4b5563"},hl=["flowName","stepName","reasoningText","text","name","tool","toolName"],fl=100;function wl(n,t){let r={...gl,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return ml}function vl(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function yl(n){let t=new Date(n),r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function bl(n,t){try{let r=JSON.parse(n);if(typeof r!="object"||r===null)return null;for(let e of t){let o=e.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Cl(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(r=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function xl(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Sl(n,t,r){let e,o;try{o=JSON.parse(n.payload),e=JSON.stringify(o,null,2)}catch{o=n.payload,e=n.payload}let s=t.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:n,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),u=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return u.textContent=e,a.appendChild(u),a}}function _r(n,t,r,e,o,s,i,a){var m;let u=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");es(c,(m=e.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:n,index:t,config:a,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(d()),c;function d(){var j,ye;let w=g("div",""),b=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");b.setAttribute("data-event-id",n.id);let y=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),S=ie(u?"chevron-down":"chevron-right","14px","currentColor",2);S&&y.appendChild(S);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),k=(j=e.timestampFormat)!=null?j:"relative";x.textContent=k==="relative"?vl(n.timestamp,r):yl(n.timestamp);let J=null;e.showSequenceNumbers!==!1&&(J=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),J.textContent=String(t+1));let E=wl(n.type,e.badgeColors),I=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");I.style.backgroundColor=E.bg,I.style.color=E.text,I.style.borderColor=E.text+"50",I.textContent=n.type;let T=(ye=e.descriptionFields)!=null?ye:hl,B=bl(n.payload,T),le=null;B&&(le=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),le.textContent=B);let z=g("div","tvw-flex-1 tvw-min-w-0"),U=g("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),K=ie("clipboard","12px","currentColor",1.5);return K&&U.appendChild(K),U.addEventListener("click",async se=>{se.stopPropagation(),await Cl(xl(n)),U.innerHTML="";let Y=ie("check","12px","currentColor",1.5);Y&&U.appendChild(Y),setTimeout(()=>{U.innerHTML="";let _=ie("clipboard","12px","currentColor",1.5);_&&U.appendChild(_)},1500)}),b.appendChild(y),b.appendChild(x),J&&b.appendChild(J),b.appendChild(I),le&&b.appendChild(le),b.appendChild(z),b.appendChild(U),w.appendChild(b),u&&w.appendChild(Sl(n,i,a)),w}}function ya(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(d=>d.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let d=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>u().element,onClose:e});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return u();function u(){let d=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");es(m,d==null?void 0:d.panel);let w=[],b="",y="",S=null,x=[],k={},J=0,E=!1,I=0,T=0,B=!1,le=null,z=!1,U=0,K=new Set,j=new Map,ye="",se="",Y=null,_,O,Q,ue,Be;function Et(){let N=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),G=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");es(G,d==null?void 0:d.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",_=g("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),_.textContent="0";let $e=g("div","tvw-flex-1");O=g("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let oe=g("option","");oe.value="",oe.textContent="All events",O.appendChild(oe),Q=g("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),Q.type="button",Q.title="Copy All";let Ke=ie("clipboard-copy","12px","currentColor",1.5);Ke&&Q.appendChild(Ke);let ce=g("span","tvw-text-xs");ce.textContent="Copy All",Q.appendChild(ce),G.appendChild(re),G.appendChild(_),G.appendChild($e),G.appendChild(O),G.appendChild(Q);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");es(D,d==null?void 0:d.searchBar);let Se=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),et=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Se&&et.appendChild(Se),ue=g("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),es(ue,d==null?void 0:d.searchInput),ue.type="text",ue.placeholder="Search event payloads...",Be=g("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Be.type="button",Be.style.display="none";let tt=ie("x","12px","currentColor",2);return tt&&Be.appendChild(tt),D.appendChild(et),D.appendChild(ue),D.appendChild(Be),N.appendChild(G),N.appendChild(D),N}let dt,gt=s.find(N=>N.renderEventStreamToolbar);if(gt!=null&&gt.renderEventStreamToolbar&&o){let N=gt.renderEventStreamToolbar({config:o,defaultRenderer:()=>Et(),eventCount:t.getSize(),filteredCount:0,onFilterChange:G=>{b=G,at(),yt()},onSearchChange:G=>{y=G,at(),yt()}});dt=N!=null?N:Et()}else dt=Et();let Ht=g("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Ht.style.display="none";let Ne=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ne=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ne.style.height="100%";let be=g("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");es(be,d==null?void 0:d.scrollIndicator),be.style.display="none";let Re=ie("arrow-down","12px","currentColor",2);Re&&be.appendChild(Re);let Fe=g("span","");be.appendChild(Fe);let Ue=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Ue.style.display="none",Ne.appendChild(ne),Ne.appendChild(Ue),Ne.appendChild(be),m.setAttribute("tabindex","0"),m.appendChild(dt),m.appendChild(Ht),m.appendChild(Ne);function Nt(){let N=t.getAll(),G={};for(let ce of N)G[ce.type]=(G[ce.type]||0)+1;let re=Object.keys(G).sort(),$e=re.length!==x.length||!re.every((ce,D)=>ce===x[D]),oe=!$e&&re.some(ce=>G[ce]!==k[ce]),Je=N.length!==Object.values(k).reduce((ce,D)=>ce+D,0);if(!$e&&!oe&&!Je||(x=re,k=G,!O))return;let Ke=O.value;if(O.options[0].textContent="All events",$e){for(;O.options.length>1;)O.remove(1);for(let ce of re){let D=g("option","");D.value=ce,D.textContent=`${ce} (${G[ce]||0})`,O.appendChild(D)}Ke&&re.includes(Ke)?O.value=Ke:Ke&&(O.value="",b="")}else for(let ce=1;ce<O.options.length;ce++){let D=O.options[ce];D.textContent=`${D.value} (${G[D.value]||0})`}}function de(){let N=t.getAll();if(b&&(N=N.filter(G=>G.type===b)),y){let G=y.toLowerCase();N=N.filter(re=>re.type.toLowerCase().includes(G)||re.payload.toLowerCase().includes(G))}return N}function X(){return b!==""||y!==""}function at(){J=0,I=0,E=!1,be.style.display="none"}function vt(N){K.has(N)?K.delete(N):K.add(N),Y=N;let G=ne.scrollTop,re=E;z=!0,E=!0,yt(),ne.scrollTop=G,E=re,z=!1}function Tt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function yt(){T=Date.now(),B=!1,Nt();let N=t.getEvictedCount();N>0?(Ht.textContent=`${N.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=de();let G=w.length,re=t.getSize()>0;_&&(_.textContent=String(t.getSize())),G===0&&re&&X()?(Ue.textContent=y?`No events matching '${y}'`:"No events matching filter",Ue.style.display="",ne.style.display="none"):(Ue.style.display="none",ne.style.display=""),Q&&(Q.title=X()?`Copy Filtered (${G})`:"Copy All"),E&&G>J&&(I+=G-J,Fe.textContent=`${I} new event${I===1?"":"s"}`,be.style.display=""),J=G;let $e=t.getAll(),oe=$e.length>0?$e[0].timestamp:0,Je=new Set(w.map(D=>D.id));for(let D of K)Je.has(D)||K.delete(D);let Ke=b!==ye||y!==se,ce=j.size===0&&w.length>0;if(Ke||ce||w.length===0){ne.innerHTML="",j.clear();let D=document.createDocumentFragment();for(let Se=0;Se<w.length;Se++){let et=_r(w[Se],Se,oe,i,K,vt,s,o);j.set(w[Se].id,et),D.appendChild(et)}ne.appendChild(D),ye=b,se=y,Y=null}else{if(Y!==null){let Se=j.get(Y);if(Se&&Se.parentNode===ne){let et=w.findIndex(tt=>tt.id===Y);if(et>=0){let tt=_r(w[et],et,oe,i,K,vt,s,o);ne.insertBefore(tt,Se),Se.remove(),j.set(Y,tt)}}Y=null}let D=new Set(w.map(Se=>Se.id));for(let[Se,et]of j)D.has(Se)||(et.remove(),j.delete(Se));for(let Se=0;Se<w.length;Se++){let et=w[Se];if(!j.has(et.id)){let tt=_r(et,Se,oe,i,K,vt,s,o);j.set(et.id,tt),ne.appendChild(tt)}}}E||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-T>=fl){le!==null&&(cancelAnimationFrame(le),le=null),yt();return}B||(B=!0,le=requestAnimationFrame(()=>{le=null,yt()}))}let ee=(N,G)=>{if(!Q)return;Q.innerHTML="";let re=ie(N,"12px","currentColor",1.5);re&&Q.appendChild(re);let $e=g("span","tvw-text-xs");$e.textContent="Copy All",Q.appendChild($e),setTimeout(()=>{Q.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&Q.appendChild(oe);let Je=g("span","tvw-text-xs");Je.textContent="Copy All",Q.appendChild(Je),Q.disabled=!1},G)},Le=async()=>{if(Q){Q.disabled=!0;try{let N;X()?N=w:r?(N=await r(),N.length===0&&(N=t.getAll())):N=t.getAll();let G=N.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(G,null,2)),ee("check",1500)}catch{ee("x",1500)}}},bt=()=>{O&&(b=O.value,at(),yt())},pe=()=>{!ue||!Be||(Be.style.display=ue.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{y=ue.value,at(),yt()},150))},Ce=()=>{!ue||!Be||(ue.value="",y="",Be.style.display="none",S&&clearTimeout(S),at(),yt())},qe=()=>{if(z)return;let N=ne.scrollTop,G=N>U;U=N,Tt()&&G?(E=!1,I=0,be.style.display="none"):Tt()||(E=!0)},Bt=N=>{N.deltaY<0&&(E=!0)},Mt=()=>{ne.scrollTop=ne.scrollHeight,E=!1,I=0,be.style.display="none"},Vt=N=>{let G=N.target;if(!G||G.closest("button"))return;let re=G.closest("[data-event-id]");if(!re)return;let $e=re.getAttribute("data-event-id");$e&&vt($e)},F=N=>{if((N.metaKey||N.ctrlKey)&&N.key==="f"){N.preventDefault(),ue==null||ue.focus(),ue==null||ue.select();return}N.key==="Escape"&&(ue&&document.activeElement===ue?(Ce(),ue.blur(),m.focus()):e&&e())};Q&&Q.addEventListener("click",Le),O&&O.addEventListener("change",bt),ue&&ue.addEventListener("input",pe),Be&&Be.addEventListener("click",Ce),ne.addEventListener("scroll",qe),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",Vt),be.addEventListener("click",Mt),m.addEventListener("keydown",F);function Qe(){S&&clearTimeout(S),le!==null&&(cancelAnimationFrame(le),le=null),B=!1,j.clear(),Q&&Q.removeEventListener("click",Le),O&&O.removeEventListener("change",bt),ue&&ue.removeEventListener("input",pe),Be&&Be.removeEventListener("click",Ce),ne.removeEventListener("scroll",qe),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",Vt),be.removeEventListener("click",Mt),m.removeEventListener("keydown",F)}return{element:m,update:Kt,destroy:Qe}}}var ba={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"}},Vr=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var b,y,S;if(s.dataset.enhanced==="true")return;let i=(b=s.dataset.tvForm)!=null?b:"init";s.dataset.enhanced="true";let a=(y=ba[i])!=null?y:ba.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let x=g("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,u.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var T,B;let k=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");k.htmlFor=`${t.id}-${i}-${x.name}`;let J=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");J.textContent=x.label,k.appendChild(J);let E=(T=x.type)!=null?T:"text",I;E==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=E),I.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",I.id=`${t.id}-${i}-${x.name}`,I.name=x.name,I.placeholder=(B=x.placeholder)!=null?B:"",x.required&&(I.required=!0),k.appendChild(I),v.appendChild(k)});let d=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(S=a.submitLabel)!=null?S:"Submit",d.appendChild(m),d.appendChild(w),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async x=>{var I,T;x.preventDefault();let k=(I=r.formEndpoint)!=null?I:"/form",J=new FormData(v),E={};J.forEach((B,le)=>{E[le]=B}),E.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let B=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(E)});if(!B.ok)throw new Error(`Form submission failed (${B.status})`);let le=await B.json();m.textContent=(T=le.message)!=null?T:"Thanks! We'll be in touch soon.",le.success&&le.nextPrompt&&await e.sendMessage(String(le.nextPrompt))}catch(B){m.textContent=B instanceof Error?B.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Ur=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var e;let r=this.plugins.get(t);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let e=new Set(t.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var a,u;return((a=i.priority)!=null?a:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ps=new Ur;var qr={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"},zr={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"},rt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:qr,darkTheme:zr,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 cr(n){var t,r,e,o,s,i,a,u,c,v,d,m,w,b,y,S,x,k,J;return n?{...rt,...n,theme:{...rt.theme,...n.theme},darkTheme:{...rt.darkTheme,...n.darkTheme},launcher:{...rt.launcher,...n.launcher,clearChat:{...(t=rt.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...rt.copy,...n.copy},sendButton:{...rt.sendButton,...n.sendButton},statusIndicator:{...rt.statusIndicator,...n.statusIndicator},voiceRecognition:{...rt.voiceRecognition,...n.voiceRecognition},features:{...rt.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:rt.suggestionChips,suggestionChipsConfig:{...rt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...rt.layout,...n.layout,header:{...(o=rt.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=rt.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(u=rt.layout)==null?void 0:u.messages)==null?void 0:c.avatar,...(d=(v=n.layout)==null?void 0:v.messages)==null?void 0:d.avatar},timestamp:{...(w=(m=rt.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(b=n.layout)==null?void 0:b.messages)==null?void 0:y.timestamp}},slots:{...(S=rt.layout)==null?void 0:S.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...rt.markdown,...n.markdown,options:{...(k=rt.markdown)==null?void 0:k.options,...(J=n.markdown)==null?void 0:J.options}},messageActions:{...rt.messageActions,...n.messageActions}}:rt}var Ca=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:t,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(a=>{try{a(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var Al=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},El=n=>{let t=n.trim(),r=t.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(r,o+1)}return null},Rs=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=Al(n),r=El(t);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Jr=n=>typeof n=="string"?n:n==null?"":String(n),$n={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Jr(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Jr(r.element);if(e&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Jr(r.text)}}},xa=n=>Array.isArray(n)?n.map(t=>String(t)):[],Hs=n=>{let t=new Set(xa(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(xa(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let u={action:a,message:s.message};n.emit("action:detected",u);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",u)},d=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!d)continue;if(d.handled){let m=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:m,resubmit:d.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var Tl=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Ml=n=>n.map(t=>({...t,streaming:!1})),dr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Tl(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?Ml(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Kr=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,e])=>{this.register(r,e)})}},ts=new Kr;var ns=require("partial-json");function kl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Il(n,t){if(!kl(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:t}}function ur(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n;try{let o=(0,ns.parse)(r,ns.STR|ns.OBJ),s=Il(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function Sa(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function pr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=ts.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(n.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,a),null}}function Aa(){let n=ur();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function gr(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function mr(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var Ll=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function hr(n){let{onSubmit:t,onDismiss:r,title:e="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:u=!0,ratingLabels:c=Ll}=n,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let d=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=e,w.appendChild(b);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),m.appendChild(w);let S=document.createElement("div");S.className="tvw-feedback-rating tvw-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let T=1;T<=5;T++){let B=document.createElement("button");B.type="button",B.className="tvw-feedback-rating-btn tvw-feedback-star-btn",B.setAttribute("role","radio"),B.setAttribute("aria-checked","false"),B.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${c[T-1]}`),B.title=c[T-1],B.dataset.rating=String(T),B.innerHTML=`
15
+ `,r.addEventListener("click",t);let e=s=>{var x,H,Y,k,P,L,F,ue,z,V,X,_;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(H=i.title)!=null?H:"Chat Assistant");let d=r.querySelector("[data-role='launcher-subtitle']");d&&(d.textContent=(Y=i.subtitle)!=null?Y:"Get answers fast");let c=r.querySelector(".tvw-flex-col");c&&(i.textHidden?c.style.display="none":c.style.display="");let v=r.querySelector("[data-role='launcher-icon']");if(v)if(i.agentIconHidden)v.style.display="none";else{let Ce=(k=i.agentIconSize)!=null?k:"40px";if(v.style.height=Ce,v.style.width=Ce,v.innerHTML="",i.agentIconName){let se=parseFloat(Ce)||24,G=ie(i.agentIconName,se*.6,"#ffffff",2);G?(v.appendChild(G),v.style.display=""):(v.textContent=(P=i.agentIconText)!=null?P:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(L=i.agentIconText)!=null?L:"\u{1F4AC}",v.style.display="")}let p=r.querySelector("[data-role='launcher-image']");if(p){let Ce=(F=i.agentIconSize)!=null?F:"40px";p.style.height=Ce,p.style.width=Ce,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(p.src=i.iconUrl,p.style.display="block"):p.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let Ce=(ue=i.callToActionIconSize)!=null?ue:"32px";m.style.height=Ce,m.style.width=Ce,i.callToActionIconBackgroundColor?(m.style.backgroundColor=i.callToActionIconBackgroundColor,m.classList.remove("tvw-bg-cw-primary")):(m.style.backgroundColor="",m.classList.add("tvw-bg-cw-primary"));let se=0;if(i.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=i.callToActionIconPadding,se=(parseFloat(i.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),i.callToActionIconHidden)m.style.display="none";else if(m.style.display="",m.innerHTML="",i.callToActionIconName){let G=parseFloat(Ce)||24,U=Math.max(G-se,8),N=ie(i.callToActionIconName,U,"currentColor",2);N?m.appendChild(N):m.textContent=(z=i.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(V=i.callToActionIconText)!=null?V:"\u2197"}let w=i.position&&sn[i.position]?sn[i.position]:sn["bottom-right"],C="tvw-fixed tvw-flex tvw-items-center tvw-gap-3 tvw-rounded-launcher tvw-bg-cw-surface tvw-py-2.5 tvw-pl-3 tvw-pr-3 tvw-transition hover:tvw-translate-y-[-2px] tvw-cursor-pointer tvw-z-50";r.className=`${C} ${w}`;let y="1px solid #e5e7eb",A="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(X=i.border)!=null?X:y,r.style.boxShadow=(_=i.shadow)!=null?_:A},o=()=>{r.removeEventListener("click",t),r.remove()};return n&&e(n),{element:r,update:e,destroy:o}};var mn=n=>{var V,X,_,Ce,se,G,U,N,ee,fe,Fe,Mt,gt,ft,Ht,je,ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt;let{config:t,showClose:r=!0}=n,e=g("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(V=t==null?void 0:t.launcher)!=null?V:{},s=(X=o.headerIconSize)!=null?X:"48px",i=(_=o.closeButtonSize)!=null?_:"32px",a=(Ce=o.closeButtonPlacement)!=null?Ce:"inline",d=(se=o.headerIconHidden)!=null?se:!1,c=o.headerIconName,v=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!d)if(c){let ve=parseFloat(s)||24,Se=ie(c,ve*.6,"#ffffff",1);Se?v.replaceChildren(Se):v.textContent=(U=(G=t==null?void 0:t.launcher)==null?void 0:G.agentIconText)!=null?U:"\u{1F4AC}"}else if((N=t==null?void 0:t.launcher)!=null&&N.iconUrl){let ve=g("img");ve.src=t.launcher.iconUrl,ve.alt="",ve.className="tvw-rounded-xl tvw-object-cover",ve.style.height=s,ve.style.width=s,v.replaceChildren(ve)}else v.textContent=(fe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.agentIconText)!=null?fe:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col"),m=g("span","tvw-text-base tvw-font-semibold");m.textContent=(Mt=(Fe=t==null?void 0:t.launcher)==null?void 0:Fe.title)!=null?Mt:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(ft=(gt=t==null?void 0:t.launcher)==null?void 0:gt.subtitle)!=null?ft:"Here to help you get answers fast",p.append(m,w),d?e.append(p):e.append(v,p);let C=(Ht=o.clearChat)!=null?Ht:{},y=(je=C.enabled)!=null?je:!0,A=(ne=C.placement)!=null?ne:"inline",x=null,H=null;if(y){let ve=(xe=C.size)!=null?xe:"32px",Se=(He=C.iconName)!=null?He:"refresh-cw",Je=($e=C.iconColor)!=null?$e:"",Bt=(ze=C.backgroundColor)!=null?ze:"",It=(Ot=C.borderWidth)!=null?Ot:"",qt=(he=C.borderColor)!=null?he:"",I=(Z=C.borderRadius)!=null?Z:"",nt=(ct=C.paddingX)!=null?ct:"",O=(bt=C.paddingY)!=null?bt:"",Q=(kt=C.tooltipText)!=null?kt:"Clear chat",re=(Ct=C.showTooltip)!=null?Ct:!0;H=g("div",A==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),A==="top-right"&&(H.style.right="48px"),x=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=ve,x.style.width=ve,x.type="button",x.setAttribute("aria-label",Q);let Ne=ie(Se,"20px",Je||"",1);if(Ne&&x.appendChild(Ne),Je&&(x.style.color=Je,x.classList.remove("tvw-text-cw-muted")),Bt&&(x.style.backgroundColor=Bt,x.classList.remove("hover:tvw-bg-gray-100")),It||qt){let oe=It||"0px",Xe=qt||"transparent";x.style.border=`${oe} solid ${Xe}`,x.classList.remove("tvw-border-none")}if(I&&(x.style.borderRadius=I,x.classList.remove("tvw-rounded-full")),nt?(x.style.paddingLeft=nt,x.style.paddingRight=nt):(x.style.paddingLeft="",x.style.paddingRight=""),O?(x.style.paddingTop=O,x.style.paddingBottom=O):(x.style.paddingTop="",x.style.paddingBottom=""),H.appendChild(x),re&&Q&&x&&H){let oe=null,Xe=()=>{if(oe||!x)return;oe=g("div","tvw-clear-chat-tooltip"),oe.textContent=Q;let pe=g("div");pe.className="tvw-clear-chat-tooltip-arrow",oe.appendChild(pe);let D=x.getBoundingClientRect();oe.style.position="fixed",oe.style.left=`${D.left+D.width/2}px`,oe.style.top=`${D.top-8}px`,oe.style.transform="translate(-50%, -100%)",document.body.appendChild(oe)},Ge=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};H.addEventListener("mouseenter",Xe),H.addEventListener("mouseleave",Ge),x.addEventListener("focus",Xe),x.addEventListener("blur",Ge),H._cleanupTooltip=()=>{Ge(),H&&(H.removeEventListener("mouseenter",Xe),H.removeEventListener("mouseleave",Ge)),x&&(x.removeEventListener("focus",Xe),x.removeEventListener("blur",Ge))}}A==="inline"&&e.appendChild(H)}let Y=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":y&&A==="inline"?"":"tvw-ml-auto"),k=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");k.style.height=i,k.style.width=i,k.type="button";let P=(Kt=o.closeButtonTooltipText)!=null?Kt:"Close chat",L=(te=o.closeButtonShowTooltip)!=null?te:!0;k.setAttribute("aria-label",P),k.style.display=r?"":"none";let F=(Pe=o.closeButtonIconName)!=null?Pe:"x",ue=(xt=o.closeButtonIconText)!=null?xt:"\xD7",z=ie(F,"20px",o.closeButtonColor||"",1);if(z?k.appendChild(z):k.textContent=ue,o.closeButtonColor?(k.style.color=o.closeButtonColor,k.classList.remove("tvw-text-cw-muted")):(k.style.color="",k.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(k.style.backgroundColor=o.closeButtonBackgroundColor,k.classList.remove("hover:tvw-bg-gray-100")):(k.style.backgroundColor="",k.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let ve=o.closeButtonBorderWidth||"0px",Se=o.closeButtonBorderColor||"transparent";k.style.border=`${ve} solid ${Se}`,k.classList.remove("tvw-border-none")}else k.style.border="",k.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(k.style.borderRadius=o.closeButtonBorderRadius,k.classList.remove("tvw-rounded-full")):(k.style.borderRadius="",k.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(k.style.paddingLeft=o.closeButtonPaddingX,k.style.paddingRight=o.closeButtonPaddingX):(k.style.paddingLeft="",k.style.paddingRight=""),o.closeButtonPaddingY?(k.style.paddingTop=o.closeButtonPaddingY,k.style.paddingBottom=o.closeButtonPaddingY):(k.style.paddingTop="",k.style.paddingBottom=""),Y.appendChild(k),L&&P){let ve=null,Se=()=>{if(ve)return;ve=g("div","tvw-clear-chat-tooltip"),ve.textContent=P;let Bt=g("div");Bt.className="tvw-clear-chat-tooltip-arrow",ve.appendChild(Bt);let It=k.getBoundingClientRect();ve.style.position="fixed",ve.style.left=`${It.left+It.width/2}px`,ve.style.top=`${It.top-8}px`,ve.style.transform="translate(-50%, -100%)",document.body.appendChild(ve)},Je=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};Y.addEventListener("mouseenter",Se),Y.addEventListener("mouseleave",Je),k.addEventListener("focus",Se),k.addEventListener("blur",Je),Y._cleanupTooltip=()=>{Je(),Y.removeEventListener("mouseenter",Se),Y.removeEventListener("mouseleave",Je),k.removeEventListener("focus",Se),k.removeEventListener("blur",Je)}}return a!=="top-right"&&e.appendChild(Y),{header:e,iconHolder:v,headerTitle:m,headerSubtitle:w,closeButton:k,closeButtonWrapper:Y,clearChatButton:x,clearChatButtonWrapper:H}},Fn=(n,t,r)=>{var i,a,d,c;let e=(i=r==null?void 0:r.launcher)!=null?i:{},o=(a=e.closeButtonPlacement)!=null?a:"inline",s=(c=(d=e.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(t.header),o==="top-right"&&(n.style.position="relative",n.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(t.clearChatButtonWrapper))};var Br=n=>mn({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),Fr=n=>{var C,y,A,x;let{config:t,showClose:r=!0,onClose:e}=n,o=(C=t==null?void 0:t.launcher)!=null?C:{},s=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=g("span","tvw-text-base tvw-font-semibold");i.textContent=(y=o.title)!=null?y:"Chat Assistant",s.appendChild(i);let a=(A=o.closeButtonSize)!=null?A:"32px",d=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(x=o.closeButtonIconName)!=null?x:"x",p=ie(v,"20px",o.closeButtonColor||"",2);p?c.appendChild(p):c.textContent="\xD7",e&&c.addEventListener("click",e),d.appendChild(c),s.appendChild(d);let m=g("div");m.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:m,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:d,clearChatButton:null,clearChatButtonWrapper:null}},$r=n=>{var k,P,L,F,ue,z,V,X;let{config:t,showClose:r=!0,onClose:e,onClearChat:o}=n,s=(k=t==null?void 0:t.launcher)!=null?k:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),d=(P=s.headerIconSize)!=null?P:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=d,c.style.width=d;let v=s.headerIconName;if(v){let _=parseFloat(d)||24,Ce=ie(v,_*.5,"#ffffff",2);Ce?c.replaceChildren(Ce):c.textContent=(L=s.agentIconText)!=null?L:"\u{1F4AC}"}else if(s.iconUrl){let _=g("img");_.src=s.iconUrl,_.alt="",_.className="tvw-rounded-xl tvw-object-cover",_.style.height=d,_.style.width=d,c.replaceChildren(_)}else c.textContent=(F=s.agentIconText)!=null?F:"\u{1F4AC}";let p=g("div","tvw-flex tvw-flex-col tvw-flex-1"),m=g("span","tvw-text-lg tvw-font-semibold");m.textContent=(ue=s.title)!=null?ue:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(z=s.subtitle)!=null?z:"Here to help you get answers fast",p.append(m,w),a.append(c,p);let C=(V=s.closeButtonSize)!=null?V:"32px",y=g("div",""),A=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");A.style.height=C,A.style.width=C,A.type="button",A.setAttribute("aria-label","Close chat"),A.style.display=r?"":"none";let x=(X=s.closeButtonIconName)!=null?X:"x",H=ie(x,"20px",s.closeButtonColor||"",2);H?A.appendChild(H):A.textContent="\xD7",e&&A.addEventListener("click",e),y.appendChild(A),a.appendChild(y),i.appendChild(a);let Y=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return Y.textContent="Online and ready to help",i.appendChild(Y),{header:i,iconHolder:c,headerTitle:m,headerSubtitle:w,closeButton:A,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}},dr={default:Br,minimal:Fr,expanded:$r},Nr=n=>{var t;return(t=dr[n])!=null?t:dr.default},Zn=(n,t,r)=>{var i,a,d;if(t!=null&&t.render){let c=t.render({config:n,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=g("div");v.style.display="none";let p=g("span"),m=g("span"),w=g("button");w.style.display="none";let C=g("div");return C.style.display="none",{header:c,iconHolder:v,headerTitle:p,headerSubtitle:m,closeButton:w,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=t==null?void 0:t.layout)!=null?i:"default",s=Nr(e)({config:n,showClose:(d=(a=t==null?void 0:t.showCloseButton)!=null?a:r==null?void 0:r.showClose)!=null?d:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var gl=n=>{switch(n){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Qn=n=>{var ne,xe,He,$e,ze,Ot,he,Z,ct,bt,kt,Ct,Kt,te,Pe,xt,ve,Se,Je,Bt,It,qt,I,nt,O,Q,re,Ne,oe,Xe,Ge;let{config:t}=n,r=g("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=g("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=g("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=g("textarea");s.placeholder=(xe=(ne=t==null?void 0:t.copy)==null?void 0:ne.inputPlaceholder)!=null?xe:"Type your message\u2026",s.className="tvw-w-full tvw-min-h-[24px] tvw-resize-none tvw-border-none tvw-bg-transparent tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-none tvw-composer-textarea",s.rows=1;let i=($e=(He=t==null?void 0:t.theme)==null?void 0:He.inputFontFamily)!=null?$e:"sans-serif",a=(Ot=(ze=t==null?void 0:t.theme)==null?void 0:ze.inputFontWeight)!=null?Ot:"400";s.style.fontFamily=gl(i),s.style.fontWeight=a;let v=3*20;s.style.maxHeight=`${v}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let pe=Math.min(s.scrollHeight,v);s.style.height=`${pe}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let m=(he=t==null?void 0:t.sendButton)!=null?he:{},w=(Z=m.useIcon)!=null?Z:!1,C=(ct=m.iconText)!=null?ct:"\u2191",y=m.iconName,A=(bt=m.tooltipText)!=null?bt:"Send message",x=(kt=m.showTooltip)!=null?kt:!1,H=(Ct=m.size)!=null?Ct:"40px",Y=m.backgroundColor,k=m.textColor,P=g("div","tvw-send-button-wrapper"),L=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(L.type="submit",w){if(L.style.width=H,L.style.height=H,L.style.minWidth=H,L.style.minHeight=H,L.style.fontSize="18px",L.style.lineHeight="1",L.innerHTML="",y){let pe=parseFloat(H)||24,D=k&&typeof k=="string"&&k.trim()?k.trim():"currentColor",Ee=ie(y,pe,D,2);Ee?(L.appendChild(Ee),L.style.color=D):(L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white"))}else L.textContent=C,k?L.style.color=k:L.classList.add("tvw-text-white");Y?L.style.backgroundColor=Y:L.classList.add("tvw-bg-cw-primary")}else L.textContent=(te=(Kt=t==null?void 0:t.copy)==null?void 0:Kt.sendButtonLabel)!=null?te:"Send",k?L.style.color=k:L.classList.add("tvw-text-white");if(m.borderWidth&&(L.style.borderWidth=m.borderWidth,L.style.borderStyle="solid"),m.borderColor&&(L.style.borderColor=m.borderColor),m.paddingX?(L.style.paddingLeft=m.paddingX,L.style.paddingRight=m.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),m.paddingY?(L.style.paddingTop=m.paddingY,L.style.paddingBottom=m.paddingY):(L.style.paddingTop="",L.style.paddingBottom=""),x&&A){let pe=g("div","tvw-send-button-tooltip");pe.textContent=A,P.appendChild(pe)}P.appendChild(L);let F=(Pe=t==null?void 0:t.voiceRecognition)!=null?Pe:{},ue=F.enabled===!0,z=null,V=null,X=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),_=((xt=F.provider)==null?void 0:xt.type)==="runtype";if(ue&&(X||_)){V=g("div","tvw-send-button-wrapper"),z=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),z.type="button",z.setAttribute("aria-label","Start voice recognition");let pe=(ve=F.iconName)!=null?ve:"mic",D=(Se=F.iconSize)!=null?Se:H,Ee=parseFloat(D)||24,st=(Je=F.backgroundColor)!=null?Je:Y,rt=(Bt=F.iconColor)!=null?Bt:k;z.style.width=D,z.style.height=D,z.style.minWidth=D,z.style.minHeight=D,z.style.fontSize="18px",z.style.lineHeight="1";let Yt=rt||"currentColor",Qt=ie(pe,Ee,Yt,1.5);Qt?(z.appendChild(Qt),z.style.color=Yt):(z.textContent="\u{1F3A4}",z.style.color=Yt),st?z.style.backgroundColor=st:z.classList.add("tvw-bg-cw-primary"),rt?z.style.color=rt:!rt&&!k&&z.classList.add("tvw-text-white"),F.borderWidth&&(z.style.borderWidth=F.borderWidth,z.style.borderStyle="solid"),F.borderColor&&(z.style.borderColor=F.borderColor),F.paddingX&&(z.style.paddingLeft=F.paddingX,z.style.paddingRight=F.paddingX),F.paddingY&&(z.style.paddingTop=F.paddingY,z.style.paddingBottom=F.paddingY),V.appendChild(z);let Ze=(It=F.tooltipText)!=null?It:"Start voice recognition";if(((qt=F.showTooltip)!=null?qt:!1)&&Ze){let vn=g("div","tvw-send-button-tooltip");vn.textContent=Ze,V.appendChild(vn)}}let se=(I=t==null?void 0:t.attachments)!=null?I:{},G=se.enabled===!0,U=null,N=null,ee=null,fe=null;if(G){fe=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),fe.style.display="none",ee=g("input"),ee.type="file",ee.accept=((nt=se.allowedTypes)!=null?nt:xn).join(","),ee.multiple=((O=se.maxFiles)!=null?O:4)>1,ee.style.display="none",ee.setAttribute("aria-label","Attach files"),N=g("div","tvw-send-button-wrapper"),U=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),U.type="button",U.setAttribute("aria-label",(Q=se.buttonTooltipText)!=null?Q:"Attach file");let pe=(re=se.buttonIconName)!=null?re:"paperclip",D=H,Ee=parseFloat(D)||40,st=Math.round(Ee*.6);U.style.width=D,U.style.height=D,U.style.minWidth=D,U.style.minHeight=D,U.style.fontSize="18px",U.style.lineHeight="1",U.style.backgroundColor="transparent",U.style.color="var(--cw-primary, #111827)",U.style.border="none",U.style.borderRadius="6px",U.style.transition="background-color 0.15s ease",U.addEventListener("mouseenter",()=>{U.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),U.addEventListener("mouseleave",()=>{U.style.backgroundColor="transparent"});let rt=ie(pe,st,"currentColor",1.5);rt?U.appendChild(rt):U.textContent="\u{1F4CE}",U.addEventListener("click",Ze=>{Ze.preventDefault(),ee==null||ee.click()}),N.appendChild(U);let Yt=(Ne=se.buttonTooltipText)!=null?Ne:"Attach file",Qt=g("div","tvw-send-button-tooltip");Qt.textContent=Yt,N.appendChild(Qt)}o.addEventListener("click",pe=>{pe.target!==L&&pe.target!==P&&pe.target!==z&&pe.target!==V&&pe.target!==U&&pe.target!==N&&s.focus()}),fe&&(fe.style.gap="8px",o.append(fe)),ee&&o.append(ee),o.append(s);let Fe=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),Mt=g("div","tvw-flex tvw-items-center tvw-gap-2");N&&Mt.append(N);let gt=g("div","tvw-flex tvw-items-center tvw-gap-1");V&&gt.append(V),gt.append(P),Fe.append(Mt,gt),o.append(Fe);let ft=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Ht=(oe=t==null?void 0:t.statusIndicator)!=null?oe:{},je=(Xe=Ht.visible)!=null?Xe:!0;return ft.style.display=je?"":"none",ft.textContent=(Ge=Ht.idleText)!=null?Ge:"Online",r.append(e,o,ft),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:L,sendButtonWrapper:P,micButton:z,micButtonWrapper:V,statusText:ft,attachmentButton:U,attachmentButtonWrapper:N,attachmentInput:ee,attachmentPreviewsContainer:fe,actionsRow:Fe,leftActions:Mt,rightActions:gt}};var ya=n=>{var d,c,v,p,m,w,C;if(!((c=(d=n==null?void 0:n.launcher)==null?void 0:d.enabled)!=null?c:!0)){let y=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),A=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(p=(v=n==null?void 0:n.launcher)==null?void 0:v.width)!=null?p:"100%";return y.style.width=x,A.style.width="100%",y.appendChild(A),{wrapper:y,panel:A}}let r=(m=n==null?void 0:n.launcher)!=null?m:{},e=r.position&&sn[r.position]?sn[r.position]:sn["bottom-right"],o=g("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=g("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(C=(w=n==null?void 0:n.launcher)==null?void 0:w.width)!=null?C:n==null?void 0:n.launcherWidth,a=i!=null?i:"min(400px, calc(100vw - 24px))";return s.style.width=a,s.style.maxWidth=a,o.appendChild(s),{wrapper:o,panel:s}},ba=(n,t=!0)=>{var w,C,y,A,x,H,Y;let r=g("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(w=n==null?void 0:n.layout)==null?void 0:w.header,o=((C=n==null?void 0:n.layout)==null?void 0:C.showHeader)!==!1,s=e?Zn(n,e,{showClose:t}):mn({config:n,showClose:t}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),d=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");d.textContent=(A=(y=n==null?void 0:n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(H=(x=n==null?void 0:n.copy)==null?void 0:x.welcomeSubtitle)!=null?H:"Ask anything about your account or products.",a.append(d,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let p=Qn({config:n}),m=((Y=n==null?void 0:n.layout)==null?void 0:Y.showFooter)!==!1;return o?Fn(r,s,n):(s.header.style.display="none",Fn(r,s,n)),r.append(i),m||(p.footer.style.display="none"),r.append(p.footer),{container:r,body:i,messagesWrapper:v,suggestions:p.suggestions,textarea:p.textarea,sendButton:p.sendButton,sendButtonWrapper:p.sendButtonWrapper,micButton:p.micButton,micButtonWrapper:p.micButtonWrapper,composerForm:p.composerForm,statusText:p.statusText,introTitle:d,introSubtitle:c,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:p.footer,attachmentButton:p.attachmentButton,attachmentButtonWrapper:p.attachmentButtonWrapper,attachmentInput:p.attachmentInput,attachmentPreviewsContainer:p.attachmentPreviewsContainer,actionsRow:p.actionsRow,leftActions:p.leftActions,rightActions:p.rightActions}};var hl=320,ml=320,fl=n=>!n.contentParts||n.contentParts.length===0?[]:n.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),vl=(n,t,r)=>{if(n.length===0)return null;try{let e=g("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),t&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return n.forEach((a,d)=>{var p;let c=g("img");c.alt=((p=a.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${hl}px`,c.style.maxHeight=`${ml}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--cw-container, #f3f4f6)",c.style.border="1px solid var(--cw-border, #e5e7eb)";let v=!1;o+=1,c.addEventListener("error",()=>{v||(v=!0,o=Math.max(0,o-1),c.remove(),o===0&&i())}),c.addEventListener("load",()=>{v=!0}),c.src=a.image,e.appendChild(c)}),o===0?(i(),null):e}catch{return r==null||r(),null}},$n=()=>{let n=document.createElement("div");n.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";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="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let e=document.createElement("div");e.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",e.style.animationDelay="500ms";let o=document.createElement("span");return o.className="tvw-sr-only",o.textContent="Loading",n.appendChild(t),n.appendChild(r),n.appendChild(e),n.appendChild(o),n},Or=(n,t,r)=>{let e={config:r!=null?r:{},streaming:!0,location:n,defaultRenderer:$n};if(t){let o=t(e);if(o!==null)return o}return $n()},wl=(n,t)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=t==="user"?n.userAvatar:n.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("img");o.src=e,o.alt=t==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Ca=(n,t)=>{let r=g("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(n.createdAt);return t.format?r.textContent=t.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},yl=(n,t="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(t){case"flat":n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-text-cw-primary","tvw-py-2"):r.push("vanilla-message-assistant-bubble","tvw-text-cw-primary","tvw-py-2");break;case"minimal":r.push("tvw-text-sm","tvw-leading-relaxed"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),n==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-5","tvw-py-3"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3");break}return r},Dr=(n,t,r)=>{var w,C,y,A,x,H;let e=(w=t.showCopy)!=null?w:!0,o=(C=t.showUpvote)!=null?C:!0,s=(y=t.showDownvote)!=null?y:!0,i=(A=t.visibility)!=null?A:"hover",a=(x=t.align)!=null?x:"right",d=(H=t.layout)!=null?H:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[d],p=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);p.id=`actions-${n.id}`,p.setAttribute("data-actions-for",n.id);let m=(Y,k,P)=>{let L=document.createElement("button");L.className="tvw-message-action-btn",L.setAttribute("aria-label",k),L.setAttribute("title",k),L.setAttribute("data-action",P);let F=ie(Y,14,"currentColor",2);return F&&L.appendChild(F),L};return e&&p.appendChild(m("copy","Copy message","copy")),o&&p.appendChild(m("thumbs-up","Upvote","upvote")),s&&p.appendChild(m("thumbs-down","Downvote","downvote")),p},es=(n,t,r,e,o,s)=>{var V,X,_,Ce,se,G,U;let i=r!=null?r:{},a=(V=i.layout)!=null?V:"bubble",d=i.avatar,c=i.timestamp,v=(X=d==null?void 0:d.show)!=null?X:!1,p=(_=c==null?void 0:c.show)!=null?_:!1,m=(Ce=d==null?void 0:d.position)!=null?Ce:"left",w=(se=c==null?void 0:c.position)!=null?se:"below",C=yl(n.role,a),y=g("div",C.join(" "));y.id=`bubble-${n.id}`,y.setAttribute("data-message-id",n.id);let A=fl(n),x=(U=(G=n.content)==null?void 0:G.trim())!=null?U:"",Y=A.length>0&&x===nr,k=document.createElement("div"),P=t({text:n.content,message:n,streaming:!!n.streaming,raw:n.rawContent}),L=null;if(Y?(L=document.createElement("div"),L.innerHTML=P,L.style.display="none",k.appendChild(L)):k.innerHTML=P,p&&w==="inline"&&n.createdAt){let N=Ca(n,c);N.classList.add("tvw-ml-2","tvw-inline"),k.appendChild(N)}if(A.length>0){let N=vl(A,!Y&&!!x,()=>{Y&&L&&(L.style.display="")});N?y.appendChild(N):Y&&L&&(L.style.display="")}if(y.appendChild(k),p&&w==="below"&&n.createdAt){let N=Ca(n,c);N.classList.add("tvw-mt-1"),y.appendChild(N)}if(n.streaming&&n.role==="assistant"&&(!n.content||!n.content.trim())){let N=Or("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);N&&y.appendChild(N)}if(n.role==="assistant"&&!n.streaming&&n.content&&n.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let N=Dr(n,e,o);y.appendChild(N)}if(!v||n.role==="system")return y;let ue=g("div",`tvw-flex tvw-gap-2 ${n.role==="user"?"tvw-flex-row-reverse":""}`),z=wl(d,n.role);return m==="right"||m==="left"&&n.role==="user"?ue.append(y,z):ue.append(z,y),y.classList.remove("tvw-max-w-[85%]"),y.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ue},xa=(n,t,r,e,o,s)=>{let i=r!=null?r:{};return n.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:n,config:{},streaming:!!n.streaming}):n.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:n,config:{},streaming:!!n.streaming}):es(n,t,r,e,o,s)};var ts=new Set,Sa=(n,t)=>{let r=ts.has(n),e=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".tvw-border-t");if(!e||!o)return;e.setAttribute("aria-expanded",r?"true":"false");let s=e.querySelector(".tvw-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .tvw-flex.tvw-items-center");if(i){i.innerHTML="";let d=ie(r?"chevron-up":"chevron-down",16,"currentColor",2);d?i.appendChild(d):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},jr=n=>{let t=n.reasoning,r=g("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${n.id}`,r.setAttribute("data-message-id",n.id),!t)return r;let e=ts.has(n.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=ta(t),s.appendChild(a),t.status==="complete"?i.style.display="none":i.style.display="";let d=g("div","tvw-flex tvw-items-center"),v=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):d.textContent=e?"Hide":"Show";let p=g("div","tvw-flex tvw-items-center tvw-ml-auto");p.append(d),o.append(s,p);let m=g("div","tvw-border-t tvw-px-4 tvw-py-3");m.style.display=e?"":"none";let w=t.chunks.join(""),C=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return C.textContent=w||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),m.appendChild(C),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),d.innerHTML="";let x=ie(e?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=e?"Hide":"Show",m.style.display=e?"":"none"})(),r.append(o,m),r};var ns=new Set,Aa=(n,t,r)=>{var c;let e=ns.has(n),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),i=t.querySelector(".tvw-border-t");if(!s||!i)return;s.setAttribute("aria-expanded",e?"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 v=o.toggleTextColor||o.headerTextColor||"currentColor",p=ie(e?"chevron-up":"chevron-down",16,v,2);p?d.appendChild(p):d.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},_r=(n,t)=>{var y;let r=n.toolCall,e=(y=t==null?void 0:t.toolCall)!=null?y:{},o=g("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${n.id}`,o.setAttribute("data-message-id",n.id),e.backgroundColor&&(o.style.backgroundColor=e.backgroundColor),e.borderColor&&(o.style.borderColor=e.borderColor),e.borderWidth&&(o.style.borderWidth=e.borderWidth),e.borderRadius&&(o.style.borderRadius=e.borderRadius),!r)return o;let s=ns.has(n.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),d=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(d.style.color=e.headerTextColor),d.textContent=na(r),a.appendChild(d);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",p=ie(s?"chevron-up":"chevron-down",16,v,2);p?c.appendChild(p):c.textContent=s?"Hide":"Show";let m=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");m.append(c),i.append(a,m);let w=g("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(w.style.display=s?"":"none",e.contentBackgroundColor&&(w.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(w.style.color=e.contentTextColor),e.contentPaddingX&&(w.style.paddingLeft=e.contentPaddingX,w.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(w.style.paddingTop=e.contentPaddingY,w.style.paddingBottom=e.contentPaddingY),r.name){let A=g("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?A.style.color=e.contentTextColor:e.headerTextColor&&(A.style.color=e.headerTextColor),A.textContent=r.name,w.appendChild(A)}if(r.args!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=As(r.args),A.append(x,H),w.appendChild(A)}if(r.chunks&&r.chunks.length){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=r.chunks.join(`
16
+ `),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&r.result!==void 0){let A=g("div","tvw-space-y-1"),x=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let H=g("pre","tvw-max-h-48 tvw-overflow-auto tvw-whitespace-pre-wrap tvw-rounded-lg tvw-border tvw-px-3 tvw-py-2 tvw-text-xs tvw-text-cw-primary");H.style.fontSize="0.75rem",H.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(H.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(H.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(H.style.color=e.codeBlockTextColor),H.textContent=As(r.result),A.append(x,H),w.appendChild(A)}if(r.status==="complete"&&typeof r.duration=="number"){let A=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(A.style.color=e.contentTextColor),A.textContent=`Duration: ${r.duration}ms`,w.appendChild(A)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let A=e.toggleTextColor||e.headerTextColor||"currentColor",x=ie(s?"chevron-up":"chevron-down",16,A,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Ur=(n,t)=>{var y,A,x,H,Y,k,P,L,F,ue,z;let r=n.approval,e=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=g("div",["vanilla-message-bubble","vanilla-approval-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-border","tvw-shadow-sm","tvw-overflow-hidden"].join(" "));if(s.id=`bubble-${n.id}`,s.setAttribute("data-message-id",n.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let d=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(y=e==null?void 0:e.titleColor)!=null?y:"currentColor",v=ie(d,20,c,2);v&&a.appendChild(v);let p=g("div","tvw-flex-1 tvw-min-w-0"),m=g("div","tvw-flex tvw-items-center tvw-gap-2"),w=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(w.style.color=e.titleColor),w.textContent=(A=e==null?void 0:e.title)!=null?A:"Approval Required",m.appendChild(w),!o){let V=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");V.setAttribute("data-approval-status",r.status),r.status==="approved"?(V.className+=" tvw-approval-badge-approved",V.textContent="Approved"):r.status==="denied"?(V.className+=" tvw-approval-badge-denied",V.textContent="Denied"):r.status==="timeout"&&(V.className+=" tvw-approval-badge-timeout",V.textContent="Timeout"),m.appendChild(V)}p.appendChild(m);let C=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(C.style.color=e.descriptionColor),C.textContent=r.description,p.appendChild(C),r.parameters){let V=g("pre","tvw-mt-2 tvw-text-xs tvw-p-2 tvw-rounded tvw-overflow-x-auto tvw-max-h-32 tvw-bg-cw-container tvw-text-cw-primary");e!=null&&e.parameterBackgroundColor&&(V.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(V.style.color=e.parameterTextColor),V.style.fontSize="0.75rem",V.style.lineHeight="1rem",V.textContent=As(r.parameters),p.appendChild(V)}if(o){let V=g("div","tvw-flex tvw-gap-2 tvw-mt-2");V.setAttribute("data-approval-buttons","true");let X=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-border-none tvw-cursor-pointer");X.type="button",X.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",X.style.color=(H=e==null?void 0:e.approveButtonTextColor)!=null?H:"#ffffff",X.setAttribute("data-approval-action","approve");let _=ie("shield-check",14,(Y=e==null?void 0:e.approveButtonTextColor)!=null?Y:"#ffffff",2);_&&(_.style.marginRight="4px",X.appendChild(_));let Ce=document.createTextNode((k=e==null?void 0:e.approveLabel)!=null?k:"Approve");X.appendChild(Ce);let se=g("button","tvw-inline-flex tvw-items-center tvw-px-3 tvw-py-1.5 tvw-rounded-md tvw-text-xs tvw-font-medium tvw-cursor-pointer");se.type="button",se.style.backgroundColor=(P=e==null?void 0:e.denyButtonColor)!=null?P:"transparent",se.style.color=(L=e==null?void 0:e.denyButtonTextColor)!=null?L:"#dc2626",se.style.border=`1px solid ${(F=e==null?void 0:e.denyButtonTextColor)!=null?F:"#fca5a5"}`,se.setAttribute("data-approval-action","deny");let G=ie("shield-x",14,(ue=e==null?void 0:e.denyButtonTextColor)!=null?ue:"#dc2626",2);G&&(G.style.marginRight="4px",se.appendChild(G));let U=document.createTextNode((z=e==null?void 0:e.denyLabel)!=null?z:"Deny");se.appendChild(U),V.append(X,se),p.appendChild(V)}return i.append(a,p),s.appendChild(i),s};var Ea=n=>{let t=[];return{buttons:t,render:(e,o,s,i,a)=>{if(n.innerHTML="",t.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(w=>w.role==="user"))return;let v=document.createDocumentFragment(),p=o?o.isStreaming():!1,m=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(w=>{let C=g("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");C.type="button",C.textContent=w,C.disabled=p,a!=null&&a.fontFamily&&(C.style.fontFamily=m(a.fontFamily)),a!=null&&a.fontWeight&&(C.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(C.style.paddingLeft=a.paddingX,C.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(C.style.paddingTop=a.paddingY,C.style.paddingBottom=a.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(C),t.push(C)}),n.appendChild(v)}}};var ks=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let e of r)this.buffer[this.head]=e,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(e.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Is=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let e=indexedDB.open(this.dbName,1);e.onupgradeneeded=()=>{let o=e.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},e.onsuccess=()=>{this.db=e.result,t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{t(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{t()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)e.put(o)}catch{}}};function ss(n,t){t&&t.split(/\s+/).forEach(r=>r&&n.classList.add(r))}var bl={flow_:{bg:"#dcfce7",text:"#166534"},step_:{bg:"#dbeafe",text:"#1e40af"},reason_:{bg:"#ffedd5",text:"#9a3412"},tool_:{bg:"#f3e8ff",text:"#6b21a8"},agent_:{bg:"#ccfbf1",text:"#115e59"},error:{bg:"#fecaca",text:"#991b1b"}},Cl={bg:"#f3f4f6",text:"#4b5563"},xl=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sl=100;function Al(n,t){let r={...bl,...t};if(r[n])return r[n];for(let e of Object.keys(r))if(e.endsWith("_")&&n.startsWith(e))return r[e];return Cl}function El(n,t){return`+${((n-t)/1e3).toFixed(3)}s`}function Tl(n){let t=new Date(n),r=String(t.getHours()).padStart(2,"0"),e=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function Ml(n,t){try{let r=JSON.parse(n);if(typeof r!="object"||r===null)return null;for(let e of t){let o=e.split("."),s=r;for(let i of o)if(s&&typeof s=="object"&&s!==null)s=s[i];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function kl(n){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(n):new Promise(r=>{let e=document.createElement("textarea");e.value=n,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function Il(n){let t;try{t=JSON.parse(n.payload)}catch{t=n.payload}return JSON.stringify({type:n.type,timestamp:new Date(n.timestamp).toISOString(),payload:t},null,2)}function Ll(n,t,r){let e,o;try{o=JSON.parse(n.payload),e=JSON.stringify(o,null,2)}catch{o=n.payload,e=n.payload}let s=t.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:n,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=g("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),d=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return d.textContent=e,a.appendChild(d),a}}function qr(n,t,r,e,o,s,i,a){var m;let d=o.has(n.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");ss(c,(m=e.classNames)==null?void 0:m.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:n,index:t,config:a,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(n.id)});if(w)return c.appendChild(w),c}return c.appendChild(p()),c;function p(){var _,Ce;let w=g("div",""),C=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-3 tvw-py-3 hover:tvw-bg-cw-container tvw-cursor-pointer tvw-group");C.setAttribute("data-event-id",n.id);let y=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),A=ie(d?"chevron-down":"chevron-right","14px","currentColor",2);A&&y.appendChild(A);let x=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),H=(_=e.timestampFormat)!=null?_:"relative";x.textContent=H==="relative"?El(n.timestamp,r):Tl(n.timestamp);let Y=null;e.showSequenceNumbers!==!1&&(Y=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),Y.textContent=String(t+1));let k=Al(n.type,e.badgeColors),P=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded tvw-text-[11px] tvw-font-mono tvw-font-medium tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-border");P.style.backgroundColor=k.bg,P.style.color=k.text,P.style.borderColor=k.text+"50",P.textContent=n.type;let L=(Ce=e.descriptionFields)!=null?Ce:xl,F=Ml(n.payload,L),ue=null;F&&(ue=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ue.textContent=F);let z=g("div","tvw-flex-1 tvw-min-w-0"),V=g("button","tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-flex-shrink-0 tvw-border-none tvw-bg-transparent tvw-p-0"),X=ie("clipboard","12px","currentColor",1.5);return X&&V.appendChild(X),V.addEventListener("click",async se=>{se.stopPropagation(),await kl(Il(n)),V.innerHTML="";let G=ie("check","12px","currentColor",1.5);G&&V.appendChild(G),setTimeout(()=>{V.innerHTML="";let U=ie("clipboard","12px","currentColor",1.5);U&&V.appendChild(U)},1500)}),C.appendChild(y),C.appendChild(x),Y&&C.appendChild(Y),C.appendChild(P),ue&&C.appendChild(ue),C.appendChild(z),C.appendChild(V),w.appendChild(C),d&&w.appendChild(Ll(n,i,a)),w}}function Ta(n){var c,v;let{buffer:t,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=n,i=(v=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?v:{},a=s.find(p=>p.renderEventStreamView);if(a!=null&&a.renderEventStreamView&&o){let p=a.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>d().element,onClose:e});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=i.classNames,m=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");ss(m,p==null?void 0:p.panel);let w=[],C="",y="",A=null,x=[],H={},Y=0,k=!1,P=0,L=0,F=!1,ue=null,z=!1,V=0,X=new Set,_=new Map,Ce="",se="",G=null,U,N,ee,fe,Fe;function Mt(){let O=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),Q=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-px-4 tvw-py-3 tvw-pb-0 tvw-border-cw-divider tvw-bg-cw-surface tvw-overflow-hidden");ss(Q,p==null?void 0:p.headerBar);let re=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");re.textContent="Events",U=g("span","tvw-text-[11px] tvw-font-mono tvw-bg-cw-container tvw-text-cw-muted tvw-px-2 tvw-py-0.5 tvw-rounded tvw-border tvw-border-cw-border"),U.textContent="0";let Ne=g("div","tvw-flex-1");N=g("select","tvw-text-xs tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded tvw-px-2.5 tvw-py-1 tvw-text-cw-primary tvw-cursor-pointer");let oe=g("option","");oe.value="",oe.textContent="All events",N.appendChild(oe),ee=g("button","tvw-inline-flex tvw-items-center tvw-gap-1.5 tvw-rounded tvw-text-xs tvw-text-cw-muted hover:tvw-bg-cw-container hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border tvw-border-cw-border tvw-bg-cw-surface tvw-flex-shrink-0 tvw-px-2.5 tvw-py-1"),ee.type="button",ee.title="Copy All";let Ge=ie("clipboard-copy","12px","currentColor",1.5);Ge&&ee.appendChild(Ge);let pe=g("span","tvw-text-xs");pe.textContent="Copy All",ee.appendChild(pe),Q.appendChild(re),Q.appendChild(U),Q.appendChild(Ne),Q.appendChild(N),Q.appendChild(ee);let D=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");ss(D,p==null?void 0:p.searchBar);let Ee=ie("search","14px","var(--cw-muted, #9ca3af)",1.5),st=g("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Ee&&st.appendChild(Ee),fe=g("input","tvw-text-sm tvw-bg-cw-surface tvw-border tvw-border-cw-border tvw-rounded-md tvw-pl-8 tvw-pr-3 tvw-py-1 tvw-w-full tvw-text-cw-primary"),ss(fe,p==null?void 0:p.searchInput),fe.type="text",fe.placeholder="Search event payloads...",Fe=g("button","tvw-absolute tvw-right-5 tvw-top-1/2 tvw--translate-y-1/2 tvw-text-cw-muted hover:tvw-text-cw-primary tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-0 tvw-leading-none"),Fe.type="button",Fe.style.display="none";let rt=ie("x","12px","currentColor",2);return rt&&Fe.appendChild(rt),D.appendChild(st),D.appendChild(fe),D.appendChild(Fe),O.appendChild(Q),O.appendChild(D),O}let gt,ft=s.find(O=>O.renderEventStreamToolbar);if(ft!=null&&ft.renderEventStreamToolbar&&o){let O=ft.renderEventStreamToolbar({config:o,defaultRenderer:()=>Mt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{C=Q,ct(),Ct()},onSearchChange:Q=>{y=Q,ct(),Ct()}});gt=O!=null?O:Mt()}else gt=Mt();let Ht=g("div","tvw-text-xs tvw-text-cw-muted tvw-text-center tvw-py-0.5 tvw-px-4 tvw-bg-cw-container tvw-border-b tvw-border-cw-divider tvw-italic tvw-flex-shrink-0");Ht.style.display="none";let je=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),ne=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");ne.style.height="100%";let xe=g("div","tvw-absolute tvw-bottom-3 tvw-left-1/2 tvw-transform tvw--translate-x-1/2 tvw-bg-cw-accent tvw-text-white tvw-text-xs tvw-px-3 tvw-py-1.5 tvw-rounded-full tvw-cursor-pointer tvw-shadow-md tvw-z-10 tvw-flex tvw-items-center tvw-gap-1");ss(xe,p==null?void 0:p.scrollIndicator),xe.style.display="none";let He=ie("arrow-down","12px","currentColor",2);He&&xe.appendChild(He);let $e=g("span","");xe.appendChild($e);let ze=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");ze.style.display="none",je.appendChild(ne),je.appendChild(ze),je.appendChild(xe),m.setAttribute("tabindex","0"),m.appendChild(gt),m.appendChild(Ht),m.appendChild(je);function Ot(){let O=t.getAll(),Q={};for(let pe of O)Q[pe.type]=(Q[pe.type]||0)+1;let re=Object.keys(Q).sort(),Ne=re.length!==x.length||!re.every((pe,D)=>pe===x[D]),oe=!Ne&&re.some(pe=>Q[pe]!==H[pe]),Xe=O.length!==Object.values(H).reduce((pe,D)=>pe+D,0);if(!Ne&&!oe&&!Xe||(x=re,H=Q,!N))return;let Ge=N.value;if(N.options[0].textContent="All events",Ne){for(;N.options.length>1;)N.remove(1);for(let pe of re){let D=g("option","");D.value=pe,D.textContent=`${pe} (${Q[pe]||0})`,N.appendChild(D)}Ge&&re.includes(Ge)?N.value=Ge:Ge&&(N.value="",C="")}else for(let pe=1;pe<N.options.length;pe++){let D=N.options[pe];D.textContent=`${D.value} (${Q[D.value]||0})`}}function he(){let O=t.getAll();if(C&&(O=O.filter(Q=>Q.type===C)),y){let Q=y.toLowerCase();O=O.filter(re=>re.type.toLowerCase().includes(Q)||re.payload.toLowerCase().includes(Q))}return O}function Z(){return C!==""||y!==""}function ct(){Y=0,P=0,k=!1,xe.style.display="none"}function bt(O){X.has(O)?X.delete(O):X.add(O),G=O;let Q=ne.scrollTop,re=k;z=!0,k=!0,Ct(),ne.scrollTop=Q,k=re,z=!1}function kt(){return ne.scrollHeight-ne.scrollTop-ne.clientHeight<=50}function Ct(){L=Date.now(),F=!1,Ot();let O=t.getEvictedCount();O>0?(Ht.textContent=`${O.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",w=he();let Q=w.length,re=t.getSize()>0;U&&(U.textContent=String(t.getSize())),Q===0&&re&&Z()?(ze.textContent=y?`No events matching '${y}'`:"No events matching filter",ze.style.display="",ne.style.display="none"):(ze.style.display="none",ne.style.display=""),ee&&(ee.title=Z()?`Copy Filtered (${Q})`:"Copy All"),k&&Q>Y&&(P+=Q-Y,$e.textContent=`${P} new event${P===1?"":"s"}`,xe.style.display=""),Y=Q;let Ne=t.getAll(),oe=Ne.length>0?Ne[0].timestamp:0,Xe=new Set(w.map(D=>D.id));for(let D of X)Xe.has(D)||X.delete(D);let Ge=C!==Ce||y!==se,pe=_.size===0&&w.length>0;if(Ge||pe||w.length===0){ne.innerHTML="",_.clear();let D=document.createDocumentFragment();for(let Ee=0;Ee<w.length;Ee++){let st=qr(w[Ee],Ee,oe,i,X,bt,s,o);_.set(w[Ee].id,st),D.appendChild(st)}ne.appendChild(D),Ce=C,se=y,G=null}else{if(G!==null){let Ee=_.get(G);if(Ee&&Ee.parentNode===ne){let st=w.findIndex(rt=>rt.id===G);if(st>=0){let rt=qr(w[st],st,oe,i,X,bt,s,o);ne.insertBefore(rt,Ee),Ee.remove(),_.set(G,rt)}}G=null}let D=new Set(w.map(Ee=>Ee.id));for(let[Ee,st]of _)D.has(Ee)||(st.remove(),_.delete(Ee));for(let Ee=0;Ee<w.length;Ee++){let st=w[Ee];if(!_.has(st.id)){let rt=qr(st,Ee,oe,i,X,bt,s,o);_.set(st.id,rt),ne.appendChild(rt)}}}k||(ne.scrollTop=ne.scrollHeight)}function Kt(){if(Date.now()-L>=Sl){ue!==null&&(cancelAnimationFrame(ue),ue=null),Ct();return}F||(F=!0,ue=requestAnimationFrame(()=>{ue=null,Ct()}))}let te=(O,Q)=>{if(!ee)return;ee.innerHTML="";let re=ie(O,"12px","currentColor",1.5);re&&ee.appendChild(re);let Ne=g("span","tvw-text-xs");Ne.textContent="Copy All",ee.appendChild(Ne),setTimeout(()=>{ee.innerHTML="";let oe=ie("clipboard-copy","12px","currentColor",1.5);oe&&ee.appendChild(oe);let Xe=g("span","tvw-text-xs");Xe.textContent="Copy All",ee.appendChild(Xe),ee.disabled=!1},Q)},Pe=async()=>{if(ee){ee.disabled=!0;try{let O;Z()?O=w:r?(O=await r(),O.length===0&&(O=t.getAll())):O=t.getAll();let Q=O.map(re=>{try{return JSON.parse(re.payload)}catch{return re.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),te("check",1500)}catch{te("x",1500)}}},xt=()=>{N&&(C=N.value,ct(),Ct())},ve=()=>{!fe||!Fe||(Fe.style.display=fe.value?"":"none",A&&clearTimeout(A),A=setTimeout(()=>{y=fe.value,ct(),Ct()},150))},Se=()=>{!fe||!Fe||(fe.value="",y="",Fe.style.display="none",A&&clearTimeout(A),ct(),Ct())},Je=()=>{if(z)return;let O=ne.scrollTop,Q=O>V;V=O,kt()&&Q?(k=!1,P=0,xe.style.display="none"):kt()||(k=!0)},Bt=O=>{O.deltaY<0&&(k=!0)},It=()=>{ne.scrollTop=ne.scrollHeight,k=!1,P=0,xe.style.display="none"},qt=O=>{let Q=O.target;if(!Q||Q.closest("button"))return;let re=Q.closest("[data-event-id]");if(!re)return;let Ne=re.getAttribute("data-event-id");Ne&&bt(Ne)},I=O=>{if((O.metaKey||O.ctrlKey)&&O.key==="f"){O.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}O.key==="Escape"&&(fe&&document.activeElement===fe?(Se(),fe.blur(),m.focus()):e&&e())};ee&&ee.addEventListener("click",Pe),N&&N.addEventListener("change",xt),fe&&fe.addEventListener("input",ve),Fe&&Fe.addEventListener("click",Se),ne.addEventListener("scroll",Je),ne.addEventListener("wheel",Bt,{passive:!0}),ne.addEventListener("click",qt),xe.addEventListener("click",It),m.addEventListener("keydown",I);function nt(){A&&clearTimeout(A),ue!==null&&(cancelAnimationFrame(ue),ue=null),F=!1,_.clear(),ee&&ee.removeEventListener("click",Pe),N&&N.removeEventListener("change",xt),fe&&fe.removeEventListener("input",ve),Fe&&Fe.removeEventListener("click",Se),ne.removeEventListener("scroll",Je),ne.removeEventListener("wheel",Bt),ne.removeEventListener("click",qt),xe.removeEventListener("click",It),m.removeEventListener("keydown",I)}return{element:m,update:Kt,destroy:nt}}}var Ma={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"}},Vr=(n,t,r,e)=>{let o=n.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,y,A;if(s.dataset.enhanced==="true")return;let i=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let a=(y=Ma[i])!=null?y:Ma.init;s.classList.add("tvw-form-card","tvw-space-y-4");let d=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,d.appendChild(c),a.description){let x=g("p","tvw-text-sm tvw-text-cw-muted");x.textContent=a.description,d.appendChild(x)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(x=>{var L,F;let H=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");H.htmlFor=`${t.id}-${i}-${x.name}`;let Y=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");Y.textContent=x.label,H.appendChild(Y);let k=(L=x.type)!=null?L:"text",P;k==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=k),P.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",P.id=`${t.id}-${i}-${x.name}`,P.name=x.name,P.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(P.required=!0),H.appendChild(P),v.appendChild(H)});let p=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),m=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(A=a.submitLabel)!=null?A:"Submit",p.appendChild(m),p.appendChild(w),v.appendChild(p),s.replaceChildren(d,v),v.addEventListener("submit",async x=>{var P,L;x.preventDefault();let H=(P=r.formEndpoint)!=null?P:"/form",Y=new FormData(v),k={};Y.forEach((F,ue)=>{k[ue]=F}),k.type=i,w.disabled=!0,m.textContent="Submitting\u2026";try{let F=await fetch(H,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(k)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let ue=await F.json();m.textContent=(L=ue.message)!=null?L:"Thanks! We'll be in touch soon.",ue.success&&ue.nextPrompt&&await e.sendMessage(String(ue.nextPrompt))}catch(F){m.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var zr=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var e;let r=this.plugins.get(t);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let e=new Set(t.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...t].sort((s,i)=>{var a,d;return((a=i.priority)!=null?a:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Ls=new zr;var Jr={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"},Kr={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"},it={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Jr,darkTheme:Kr,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 ur(n){var t,r,e,o,s,i,a,d,c,v,p,m,w,C,y,A,x,H,Y;return n?{...it,...n,theme:{...it.theme,...n.theme},darkTheme:{...it.darkTheme,...n.darkTheme},launcher:{...it.launcher,...n.launcher,clearChat:{...(t=it.launcher)==null?void 0:t.clearChat,...(r=n.launcher)==null?void 0:r.clearChat}},copy:{...it.copy,...n.copy},sendButton:{...it.sendButton,...n.sendButton},statusIndicator:{...it.statusIndicator,...n.statusIndicator},voiceRecognition:{...it.voiceRecognition,...n.voiceRecognition},features:{...it.features,...n.features},suggestionChips:(e=n.suggestionChips)!=null?e:it.suggestionChips,suggestionChipsConfig:{...it.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...it.layout,...n.layout,header:{...(o=it.layout)==null?void 0:o.header,...(s=n.layout)==null?void 0:s.header},messages:{...(i=it.layout)==null?void 0:i.messages,...(a=n.layout)==null?void 0:a.messages,avatar:{...(c=(d=it.layout)==null?void 0:d.messages)==null?void 0:c.avatar,...(p=(v=n.layout)==null?void 0:v.messages)==null?void 0:p.avatar},timestamp:{...(w=(m=it.layout)==null?void 0:m.messages)==null?void 0:w.timestamp,...(y=(C=n.layout)==null?void 0:C.messages)==null?void 0:y.timestamp}},slots:{...(A=it.layout)==null?void 0:A.slots,...(x=n.layout)==null?void 0:x.slots}},markdown:{...it.markdown,...n.markdown,options:{...(H=it.markdown)==null?void 0:H.options,...(Y=n.markdown)==null?void 0:Y.options}},messageActions:{...it.messageActions,...n.messageActions}}:it}var ka=()=>{let n=new Map,t=(o,s)=>(n.has(o)||n.set(o,new Set),n.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=n.get(o))==null||i.delete(s)};return{on:t,off:r,emit:(o,s)=>{var i;(i=n.get(o))==null||i.forEach(a=>{try{a(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Wl=n=>{let t=n.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:n},Pl=n=>{let t=n.trim(),r=t.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<t.length;o+=1){let s=t[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return t.slice(r,o+1)}return null},Ws=({text:n})=>{if(!n||!n.includes("{"))return null;try{let t=Wl(n),r=Pl(t);if(!r)return null;let e=JSON.parse(r);if(!e||typeof e!="object"||!e.action)return null;let{action:o,...s}=e;return{type:String(o),payload:s,raw:e}}catch{return null}},Yr=n=>typeof n=="string"?n:n==null?"":String(n),Nn={message:n=>n.type!=="message"?void 0:{handled:!0,displayText:Yr(n.payload.text)},messageAndClick:(n,t)=>{var o;if(n.type!=="message_and_click")return;let r=n.payload,e=Yr(r.element);if(e&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:Yr(r.text)}}},Ia=n=>Array.isArray(n)?n.map(t=>String(t)):[],Ps=n=>{let t=new Set(Ia(n.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(Ia(n.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(t);n.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.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?n.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;t.add(s.message.id),e();let d={action:a,message:s.message};n.emit("action:detected",d);for(let c of n.handlers)if(c)try{let v=()=>{n.emit("action:resubmit",d)},p=c(a,{message:s.message,metadata:n.getSessionMetadata(),updateMetadata:n.updateSessionMetadata,document:n.documentRef,triggerResubmit:v});if(!p)continue;if(p.handled){let m=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:m,resubmit:p.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var Rl=n=>{if(!n)return null;try{return JSON.parse(n)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Hl=n=>n.map(t=>({...t,streaming:!1})),pr=(n="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Rl(r.getItem(n)):null},save:r=>{let e=t();if(e)try{let o={...r,messages:r.messages?Hl(r.messages):void 0};e.setItem(n,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=t();if(r)try{r.removeItem(n)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var Xr=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,e])=>{this.register(r,e)})}},rs=new Xr;var os=require("partial-json");function Bl(n){if(!n||typeof n!="object"||!("component"in n))return!1;let t=n.component;return typeof t=="string"&&t.length>0}function Fl(n,t){if(!Bl(n))return null;let r=n.props&&typeof n.props=="object"&&n.props!==null?n.props:{};return{component:n.component,props:r,raw:t}}function gr(){let n=null,t=0;return{getExtractedDirective:()=>n,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=t)return n;try{let o=(0,os.parse)(r,os.STR|os.OBJ),s=Fl(o,r);s&&(n=s)}catch{}return t=r.length,n},reset:()=>{n=null,t=0}}}function La(n){return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"&&"props"in n&&typeof n.props=="object"}function hr(n,t){let{config:r,message:e,onPropsUpdate:o}=t,s=rs.get(n.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${n.component}" not found in registry. Falling back to default rendering.`),null;let i={message:e,config:r,updateProps:a=>{o&&o(a)}};try{return s(n.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${n.component}":`,a),null}}function Wa(){let n=gr();return{processChunk:t=>n.processChunk(t),getDirective:()=>n.getExtractedDirective(),reset:()=>{n.reset()}}}function mr(n){if(!n.rawContent)return!1;try{let t=JSON.parse(n.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function fr(n){if(!n.rawContent)return null;try{let t=JSON.parse(n.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:n.rawContent}}catch{}return null}var $l=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function vr(n){let{onSubmit:t,onDismiss:r,title:e="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,ratingLabels:c=$l}=n,v=document.createElement("div");v.className="tvw-feedback-container tvw-feedback-csat",v.setAttribute("role","dialog"),v.setAttribute("aria-label","Customer satisfaction feedback");let p=null,m=document.createElement("div");m.className="tvw-feedback-content";let w=document.createElement("div");w.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=e,w.appendChild(C);let y=document.createElement("p");y.className="tvw-feedback-subtitle",y.textContent=o,w.appendChild(y),m.appendChild(w);let A=document.createElement("div");A.className="tvw-feedback-rating tvw-feedback-rating-csat",A.setAttribute("role","radiogroup"),A.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let L=1;L<=5;L++){let F=document.createElement("button");F.type="button",F.className="tvw-feedback-rating-btn tvw-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${L} star${L>1?"s":""}: ${c[L-1]}`),F.title=c[L-1],F.dataset.rating=String(L),F.innerHTML=`
17
17
  <svg class="tvw-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
19
  </svg>
20
- `,B.addEventListener("click",()=>{d=T,x.forEach((le,z)=>{let U=z<T;le.classList.toggle("selected",U),le.setAttribute("aria-checked",z===T-1?"true":"false")})}),x.push(B),S.appendChild(B)}m.appendChild(S);let k=null;if(u){let T=document.createElement("div");T.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"),T.appendChild(k),m.appendChild(T)}let J=document.createElement("div");J.className="tvw-feedback-actions";let E=document.createElement("button");E.type="button",E.className="tvw-feedback-btn tvw-feedback-btn-skip",E.textContent=a,E.addEventListener("click",()=>{r==null||r(),v.remove()});let I=document.createElement("button");return I.type="button",I.className="tvw-feedback-btn tvw-feedback-btn-submit",I.textContent=i,I.addEventListener("click",async()=>{if(d===null){S.classList.add("tvw-feedback-shake"),setTimeout(()=>S.classList.remove("tvw-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let T=(k==null?void 0:k.value.trim())||void 0;await t(d,T),v.remove()}catch(T){I.disabled=!1,I.textContent=i,console.error("[CSAT Feedback] Failed to submit:",T)}}),J.appendChild(E),J.appendChild(I),m.appendChild(J),v.appendChild(m),v}function fr(n){let{onSubmit:t,onDismiss:r,title:e="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=n,d=document.createElement("div");d.className="tvw-feedback-container tvw-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let b=document.createElement("div");b.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,b.appendChild(y);let S=document.createElement("p");S.className="tvw-feedback-subtitle",S.textContent=o,b.appendChild(S),w.appendChild(b);let x=document.createElement("div");x.className="tvw-feedback-rating tvw-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="tvw-feedback-labels";let J=document.createElement("span");J.className="tvw-feedback-label-low",J.textContent=c;let E=document.createElement("span");E.className="tvw-feedback-label-high",E.textContent=v,k.appendChild(J),k.appendChild(E);let I=document.createElement("div");I.className="tvw-feedback-numbers";let T=[];for(let K=0;K<=10;K++){let j=document.createElement("button");j.type="button",j.className="tvw-feedback-rating-btn tvw-feedback-number-btn",j.setAttribute("role","radio"),j.setAttribute("aria-checked","false"),j.setAttribute("aria-label",`Rating ${K} out of 10`),j.textContent=String(K),j.dataset.rating=String(K),K<=6?j.classList.add("tvw-feedback-detractor"):K<=8?j.classList.add("tvw-feedback-passive"):j.classList.add("tvw-feedback-promoter"),j.addEventListener("click",()=>{m=K,T.forEach((ye,se)=>{ye.classList.toggle("selected",se===K),ye.setAttribute("aria-checked",se===K?"true":"false")})}),T.push(j),I.appendChild(j)}x.appendChild(k),x.appendChild(I),w.appendChild(x);let B=null;if(u){let K=document.createElement("div");K.className="tvw-feedback-comment-container",B=document.createElement("textarea"),B.className="tvw-feedback-comment",B.placeholder=s,B.rows=3,B.setAttribute("aria-label","Additional comments"),K.appendChild(B),w.appendChild(K)}let le=document.createElement("div");le.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{r==null||r(),d.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(m===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let K=(B==null?void 0:B.value.trim())||void 0;await t(m,K),d.remove()}catch(K){U.disabled=!1,U.textContent=i,console.error("[NPS Feedback] Failed to submit:",K)}}),le.appendChild(z),le.appendChild(U),w.appendChild(le),d.appendChild(w),d}var ss="persona-chat-history",Wl=30*1e3,Pl={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Rl(n){var e,o,s;if(!n)return[];let t=[],r=Array.from((e=n.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){t.push(a);continue}let u=(o=Pl[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${u}`,{type:a.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let i of Array.from((s=n.files)!=null?s:[]))i.type.startsWith("image/")&&t.push(i);return t}function Hl(n){var t,r,e,o,s,i,a,u,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(r=n.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=n.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=n.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(u=(a=n.persist)==null?void 0:a.focusInput)!=null?u:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function Bl(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Yr=n=>!n||typeof n!="object"?{}:{...n},Ea=n=>n.map(t=>({...t,streaming:!1})),Ta=(n,t,r)=>{let e=n!=null&&n.markdown?Es(n.markdown):null;return o=>{var a,u,c;let s=(a=o.text)!=null?a:"",i=(u=o.message.rawContent)!=null?u:null;if(t){let v=t.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.resubmit&&!o.streaming&&r&&r())}return n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):Ys(s)}},wr=(n,t,r)=>{var hs,fs,ws,vs,ys,V,Ie,De,lt,mt,At,ot,h,We,$,C,L,ae,Ae,ze,Lt,it,Ct,ht,Oe,_e,ut,Ve,xt,Dt,Xt,Qr,eo,to,no;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=cr(t),o=Ps.getForInstance(e.plugins);e.components&&ts.registerAll(e.components);let s=Ca(),i=(hs=e.storageAdapter)!=null?hs:dr(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(p=>{let f=p!=null?p:{messages:[],metadata:{}};return c(f)});else{let p=l!=null?l:{messages:[],metadata:{}},f=c(p);f.metadata&&(a=Yr(f.metadata)),(fs=f.messages)!=null&&fs.length&&(e={...e,initialMessages:f.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(ws=l.messages)!=null&&ws.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var f;a=(f=l({...a}))!=null?f:{},as()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Rs],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[$n.message,$n.messageAndClick],b=Hs({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});b.syncFromMetadata();let y=(ys=(vs=e.launcher)==null?void 0:vs.enabled)!=null?ys:!0,S=(Ie=(V=e.launcher)==null?void 0:V.autoExpand)!=null?Ie:!1,x=(De=e.autoFocusInput)!=null?De:!1,k=S,J=y,E=(mt=(lt=e.layout)==null?void 0:lt.header)==null?void 0:mt.layout,I=y?S:!0,T=!1,B=null,le=()=>{T=!0,B&&clearTimeout(B),B=setTimeout(()=>{T&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),T=!1)},1e4)},z=Ta(e,b,le),U=(ot=(At=e.features)==null?void 0:At.showReasoning)!=null?ot:!0,K=(We=(h=e.features)==null?void 0:h.showToolCalls)!=null?We:!0,j=(C=($=e.features)==null?void 0:$.showEventStreamToggle)!=null?C:!1,se=`${(ae=typeof e.persistState=="object"?(L=e.persistState)==null?void 0:L.keyPrefix:void 0)!=null?ae:"persona-"}event-stream`,Y=j?new Ws(se):null,_=(Lt=(ze=(Ae=e.features)==null?void 0:Ae.eventStream)==null?void 0:ze.maxEvents)!=null?Lt:2e3,O=j?new Ls(_,Y):null,Q=null,ue=!1,Be=null,Et=0;Y==null||Y.open().then(()=>O==null?void 0:O.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var p,f;s.emit("message:copy",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.id,"copy").catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onCopy)==null||f.call(p,l)},onFeedback:l=>{var p,f;s.emit("message:feedback",l),M!=null&&M.isClientTokenMode()&&M.submitMessageFeedback(l.messageId,l.type).catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(f=(p=e.messageActions)==null?void 0:p.onFeedback)==null||f.call(p,l)}},gt=(it=e.statusIndicator)!=null?it:{},Ht=l=>{var p,f,A,H;return l==="idle"?(p=gt.idleText)!=null?p:Rt.idle:l==="connecting"?(f=gt.connectingText)!=null?f:Rt.connecting:l==="connected"?(A=gt.connectedText)!=null?A:Rt.connected:l==="error"?(H=gt.errorText)!=null?H:Rt.error:Rt[l]},{wrapper:Ne,panel:ne}=pa(e),be=ga(e,y),{container:Re,body:Fe,messagesWrapper:Ue,suggestions:Nt,textarea:de,sendButton:X,sendButtonWrapper:at,composerForm:vt,statusText:Tt,introTitle:yt,introSubtitle:Kt,closeButton:ee,iconHolder:Le,headerTitle:bt,headerSubtitle:pe,header:Ce,footer:qe,actionsRow:Bt,leftActions:Mt,rightActions:Vt}=be,F=be.micButton,Qe=be.micButtonWrapper,N=be.attachmentButton,G=be.attachmentButtonWrapper,re=be.attachmentInput,$e=be.attachmentPreviewsContainer,oe=null;(Ct=e.attachments)!=null&&Ct.enabled&&re&&$e&&(oe=Hn.fromConfig(e.attachments),oe.setPreviewsContainer($e),re.addEventListener("change",l=>{let p=l.target;oe==null||oe.handleFileSelect(p.files),p.value=""}));let Je=o.find(l=>l.renderHeader);if(Je!=null&&Je.renderHeader){let l=Je.renderHeader({config:e,defaultRenderer:()=>{let p=mn({config:e,showClose:y});return Bn(Re,p,e),p.header},onClose:()=>nt(!1,"user")});if(l){let p=Re.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),Ce=l)}}let Ke=()=>{var p,f,A,H;if(!O)return;if(ue=!0,!Q&&O&&(Q=ya({buffer:O,getFullHistory:()=>O.getAllFromStore(),onClose:()=>ce(),config:e,plugins:o})),Q&&(Fe.style.display="none",(p=qe.parentNode)==null||p.insertBefore(Q.element,qe),Q.update()),D){D.classList.remove("tvw-text-cw-muted"),D.classList.add("tvw-text-cw-accent"),D.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let P=(H=(A=(f=e.features)==null?void 0:f.eventStream)==null?void 0:A.classNames)==null?void 0:H.toggleButtonActive;P&&P.split(/\s+/).forEach(q=>q&&D.classList.add(q))}let l=()=>{if(!ue)return;let P=Date.now();P-Et>=200&&(Q==null||Q.update(),Et=P),Be=requestAnimationFrame(l)};Et=0,Be=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},ce=()=>{var l,p,f;if(ue){if(ue=!1,Q&&Q.element.remove(),Fe.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let A=(f=(p=(l=e.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:f.toggleButtonActive;A&&A.split(/\s+/).forEach(H=>H&&D.classList.remove(H))}Be!==null&&(cancelAnimationFrame(Be),Be=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(j){let l=(Oe=(ht=e.features)==null?void 0:ht.eventStream)==null?void 0:Oe.classNames,p="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");D=g("button",p),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let f=ie("activity","18px","currentColor",1.5);f&&D.appendChild(f);let A=be.clearChatButtonWrapper,H=be.closeButtonWrapper,P=A||H;P&&P.parentNode===Ce?Ce.insertBefore(D,P):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}let Se=o.find(l=>l.renderComposer);if(Se!=null&&Se.renderComposer){let l=Se.renderComposer({config:e,defaultRenderer:()=>Xn({config:e}).footer,onSubmit:p=>{M&&!M.isStreaming()&&M.sendMessage(p)},disabled:!1});l&&(qe.replaceWith(l),qe=l)}(()=>{var A,H;let l=(H=(A=e.layout)==null?void 0:A.slots)!=null?H:{},p=P=>{switch(P){case"body-top":return Re.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Ue;case"footer-top":return Nt;case"composer":return vt;case"footer-bottom":return Tt;default:return null}},f=(P,q)=>{var ge;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Ce.insertBefore(q,Ce.firstChild);else if(P==="header-right")Ce.appendChild(q);else{let me=Ce.querySelector(".tvw-flex-col");me?(ge=me.parentNode)==null||ge.insertBefore(q,me.nextSibling):Ce.appendChild(q)}break;case"body-top":{let me=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");me?me.replaceWith(q):Fe.insertBefore(q,Fe.firstChild);break}case"body-bottom":Fe.appendChild(q);break;case"footer-top":Nt.replaceWith(q);break;case"footer-bottom":Tt.replaceWith(q);break;default:break}};for(let[P,q]of Object.entries(l))if(q)try{let ge=q({config:e,defaultContent:()=>p(P)});ge&&f(P,ge)}catch(ge){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,ge)}})();let tt=l=>{let f=l.target.closest('button[data-expand-header="true"]');if(!f)return;let A=f.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-bubble-type");P==="reasoning"?(Zn.has(H)?Zn.delete(H):Zn.add(H),fa(H,A)):P==="tool"&&(Qn.has(H)?Qn.delete(H):Qn.add(H),wa(H,A,e))};Ue.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))}),Ue.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),tt(l))});let Yt=new Map;Ue.addEventListener("click",l=>{var q;let f=l.target.closest(".tvw-message-action-btn[data-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest("[data-actions-for]");if(!A)return;let H=A.getAttribute("data-actions-for");if(!H)return;let P=f.getAttribute("data-action");if(P==="copy"){let me=M.getMessages().find(fe=>fe.id===H);if(me&&dt.onCopy){let fe=me.content||"";navigator.clipboard.writeText(fe).then(()=>{f.classList.add("tvw-message-action-success");let xe=ie("check",14,"currentColor",2);xe&&(f.innerHTML="",f.appendChild(xe)),setTimeout(()=>{f.classList.remove("tvw-message-action-success");let Te=ie("copy",14,"currentColor",2);Te&&(f.innerHTML="",f.appendChild(Te))},2e3)}).catch(xe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",xe)}),dt.onCopy(me)}}else if(P==="upvote"||P==="downvote")if(((q=Yt.get(H))!=null?q:null)===P)Yt.delete(H),f.classList.remove("tvw-message-action-active");else{let fe=P==="upvote"?"downvote":"upvote",xe=A.querySelector(`[data-action="${fe}"]`);xe&&xe.classList.remove("tvw-message-action-active"),Yt.set(H,P),f.classList.add("tvw-message-action-active");let te=M.getMessages().find(W=>W.id===H);te&&dt.onFeedback&&dt.onFeedback({type:P,messageId:te.id,message:te})}}),Ue.addEventListener("click",l=>{let f=l.target.closest("button[data-approval-action]");if(!f)return;l.preventDefault(),l.stopPropagation();let A=f.closest(".vanilla-approval-bubble");if(!A)return;let H=A.getAttribute("data-message-id");if(!H)return;let P=f.getAttribute("data-approval-action");if(!P)return;let q=P==="approve"?"approved":"denied",me=M.getMessages().find(xe=>xe.id===H);if(!(me!=null&&me.approval))return;let fe=A.querySelector("[data-approval-buttons]");fe&&fe.querySelectorAll("button").forEach(Te=>{Te.disabled=!0,Te.style.opacity="0.5",Te.style.cursor="not-allowed"}),M.resolveApproval(me.approval,q)}),ne.appendChild(Re),n.appendChild(Ne);let Gt=()=>{var he,we,st,Pe,ft,Pt,Z,je,rn,jt,tn,kn,zs,Tr,Mr,pt;let l=(we=(he=e.launcher)==null?void 0:he.sidebarMode)!=null?we:!1,p=l||((Pe=(st=e.launcher)==null?void 0:st.fullHeight)!=null?Pe:!1),f=(ft=e.theme)!=null?ft:{},A=(Z=(Pt=e.launcher)==null?void 0:Pt.position)!=null?Z:"bottom-left",H=A==="bottom-left"||A==="top-left",P=l?"none":"1px solid var(--tvw-cw-border)",q=l?H?"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)",ge=l?"0":"16px",me=(je=f.panelBorder)!=null?je:P,fe=(rn=f.panelShadow)!=null?rn:q,xe=(jt=f.panelBorderRadius)!=null?jt:ge;n.style.cssText="",Ne.style.cssText="",ne.style.cssText="",Re.style.cssText="",Fe.style.cssText="",qe.style.cssText="";let Te=(kn=(tn=e==null?void 0:e.launcher)==null?void 0:tn.width)!=null?kn:e==null?void 0:e.launcherWidth,te=Te!=null?Te:"min(400px, calc(100vw - 24px))";l||(ne.style.width=te,ne.style.maxWidth=te),ne.style.boxShadow=fe,ne.style.borderRadius=xe,Re.style.border=me,Re.style.borderRadius=xe;let W=((zs=e.launcher)==null?void 0:zs.enabled)===!1;if(p&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",Ne.style.display="flex",Ne.style.flexDirection="column",Ne.style.flex="1 1 0%",Ne.style.minHeight="0",Ne.style.maxHeight="100%",Ne.style.height="100%",W&&(Ne.style.overflow="hidden"),ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.height="100%",ne.style.overflow="hidden",Re.style.display="flex",Re.style.flexDirection="column",Re.style.flex="1 1 0%",Re.style.minHeight="0",Re.style.maxHeight="100%",Re.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",qe.style.flexShrink="0"),Ne.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&&!W&&((Tr=nn[A])!=null?Tr:nn["bottom-right"]).split(" ").forEach(zn=>Ne.classList.add(zn)),l){let qn=(pt=(Mr=e.launcher)==null?void 0:Mr.sidebarWidth)!=null?pt:"420px";Ne.style.cssText=`
20
+ `,F.addEventListener("click",()=>{p=L,x.forEach((ue,z)=>{let V=z<L;ue.classList.toggle("selected",V),ue.setAttribute("aria-checked",z===L-1?"true":"false")})}),x.push(F),A.appendChild(F)}m.appendChild(A);let H=null;if(d){let L=document.createElement("div");L.className="tvw-feedback-comment-container",H=document.createElement("textarea"),H.className="tvw-feedback-comment",H.placeholder=s,H.rows=3,H.setAttribute("aria-label","Additional comments"),L.appendChild(H),m.appendChild(L)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let k=document.createElement("button");k.type="button",k.className="tvw-feedback-btn tvw-feedback-btn-skip",k.textContent=a,k.addEventListener("click",()=>{r==null||r(),v.remove()});let P=document.createElement("button");return P.type="button",P.className="tvw-feedback-btn tvw-feedback-btn-submit",P.textContent=i,P.addEventListener("click",async()=>{if(p===null){A.classList.add("tvw-feedback-shake"),setTimeout(()=>A.classList.remove("tvw-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let L=(H==null?void 0:H.value.trim())||void 0;await t(p,L),v.remove()}catch(L){P.disabled=!1,P.textContent=i,console.error("[CSAT Feedback] Failed to submit:",L)}}),Y.appendChild(k),Y.appendChild(P),m.appendChild(Y),v.appendChild(m),v}function wr(n){let{onSubmit:t,onDismiss:r,title:e="How likely are you to recommend us?",subtitle:o="On a scale of 0 to 10",commentPlaceholder:s="What could we do better? (optional)...",submitText:i="Submit",skipText:a="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:v="Very likely"}=n,p=document.createElement("div");p.className="tvw-feedback-container tvw-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let m=null,w=document.createElement("div");w.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let y=document.createElement("h3");y.className="tvw-feedback-title",y.textContent=e,C.appendChild(y);let A=document.createElement("p");A.className="tvw-feedback-subtitle",A.textContent=o,C.appendChild(A),w.appendChild(C);let x=document.createElement("div");x.className="tvw-feedback-rating tvw-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let H=document.createElement("div");H.className="tvw-feedback-labels";let Y=document.createElement("span");Y.className="tvw-feedback-label-low",Y.textContent=c;let k=document.createElement("span");k.className="tvw-feedback-label-high",k.textContent=v,H.appendChild(Y),H.appendChild(k);let P=document.createElement("div");P.className="tvw-feedback-numbers";let L=[];for(let X=0;X<=10;X++){let _=document.createElement("button");_.type="button",_.className="tvw-feedback-rating-btn tvw-feedback-number-btn",_.setAttribute("role","radio"),_.setAttribute("aria-checked","false"),_.setAttribute("aria-label",`Rating ${X} out of 10`),_.textContent=String(X),_.dataset.rating=String(X),X<=6?_.classList.add("tvw-feedback-detractor"):X<=8?_.classList.add("tvw-feedback-passive"):_.classList.add("tvw-feedback-promoter"),_.addEventListener("click",()=>{m=X,L.forEach((Ce,se)=>{Ce.classList.toggle("selected",se===X),Ce.setAttribute("aria-checked",se===X?"true":"false")})}),L.push(_),P.appendChild(_)}x.appendChild(H),x.appendChild(P),w.appendChild(x);let F=null;if(d){let X=document.createElement("div");X.className="tvw-feedback-comment-container",F=document.createElement("textarea"),F.className="tvw-feedback-comment",F.placeholder=s,F.rows=3,F.setAttribute("aria-label","Additional comments"),X.appendChild(F),w.appendChild(X)}let ue=document.createElement("div");ue.className="tvw-feedback-actions";let z=document.createElement("button");z.type="button",z.className="tvw-feedback-btn tvw-feedback-btn-skip",z.textContent=a,z.addEventListener("click",()=>{r==null||r(),p.remove()});let V=document.createElement("button");return V.type="button",V.className="tvw-feedback-btn tvw-feedback-btn-submit",V.textContent=i,V.addEventListener("click",async()=>{if(m===null){P.classList.add("tvw-feedback-shake"),setTimeout(()=>P.classList.remove("tvw-feedback-shake"),500);return}V.disabled=!0,V.textContent="Submitting...";try{let X=(F==null?void 0:F.value.trim())||void 0;await t(m,X),p.remove()}catch(X){V.disabled=!1,V.textContent=i,console.error("[NPS Feedback] Failed to submit:",X)}}),ue.appendChild(z),ue.appendChild(V),w.appendChild(ue),p.appendChild(w),p}var is="persona-chat-history",Nl=30*1e3,Ol={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Dl(n){var e,o,s;if(!n)return[];let t=[],r=Array.from((e=n.items)!=null?e:[]);for(let i of r){if(i.kind!=="file"||!i.type.startsWith("image/"))continue;let a=i.getAsFile();if(!a)continue;if(a.name){t.push(a);continue}let d=(o=Ol[a.type])!=null?o:"png";t.push(new File([a],`clipboard-image-${Date.now()}.${d}`,{type:a.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let i of Array.from((s=n.files)!=null?s:[]))i.type.startsWith("image/")&&t.push(i);return t}function jl(n){var t,r,e,o,s,i,a,d,c;return n?n===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=n.storage)!=null?t:"session",keyPrefix:(r=n.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=n.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=n.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(d=(a=n.persist)==null?void 0:a.focusInput)!=null?d:!0},clearOnChatClear:(c=n.clearOnChatClear)!=null?c:!0}:null}function _l(n){try{let t=n==="local"?localStorage:sessionStorage,r="__persist_test__";return t.setItem(r,"1"),t.removeItem(r),t}catch{return null}}var Gr=n=>!n||typeof n!="object"?{}:{...n},Pa=n=>n.map(t=>({...t,streaming:!1})),Ra=(n,t,r)=>{let e=n!=null&&n.markdown?Ss(n.markdown):null;return o=>{var a,d,c;let s=(a=o.text)!=null?a:"",i=(d=o.message.rawContent)!=null?d:null;if(t){let v=t.process({text:s,raw:i!=null?i:s,message:o.message,streaming:o.streaming});v!==null&&(s=v.text,v.persist||(o.message.__skipPersist=!0),v.resubmit&&!o.streaming&&r&&r())}return n!=null&&n.postprocessMessage?n.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):Ys(s)}},yr=(n,t,r)=>{var q,We,_e,dt,vt,Tt,at,f,Re,$,b,R,ae,Te,Ke,Wt,lt,St,wt,De,qe,ht,Ve,At,jt,Zt,to,no,so,ro,oo,io,ao,lo,co;n.id&&n.id!=="persona-root"&&!n.getAttribute("data-persona-instance")&&n.setAttribute("data-persona-instance",n.id),n.id="persona-root";let e=ur(t),o=Ls.getForInstance(e.plugins);e.components&&rs.registerAll(e.components);let s=ka(),i=(q=e.storageAdapter)!=null?q:pr(),a={},d=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")d=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return c(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=c(u);h.metadata&&(a=Gr(h.metadata)),(We=h.messages)!=null&&We.length&&(e={...e,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(e.onStateLoaded)try{let l=c({messages:[],metadata:{}});(_e=l.messages)!=null&&_e.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,p=l=>{var h;a=(h=l({...a}))!=null?h:{},ds()},m=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ws],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Nn.message,Nn.messageAndClick],C=Ps({parsers:m,handlers:w,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let y=(vt=(dt=e.launcher)==null?void 0:dt.enabled)!=null?vt:!0,A=(at=(Tt=e.launcher)==null?void 0:Tt.autoExpand)!=null?at:!1,x=(f=e.autoFocusInput)!=null?f:!1,H=A,Y=y,k=($=(Re=e.layout)==null?void 0:Re.header)==null?void 0:$.layout,P=y?A:!0,L=!1,F=null,ue=()=>{L=!0,F&&clearTimeout(F),F=setTimeout(()=>{L&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),L=!1)},1e4)},z=Ra(e,C,ue),V=(R=(b=e.features)==null?void 0:b.showReasoning)!=null?R:!0,X=(Te=(ae=e.features)==null?void 0:ae.showToolCalls)!=null?Te:!0,_=(Wt=(Ke=e.features)==null?void 0:Ke.showEventStreamToggle)!=null?Wt:!1,se=`${(St=typeof e.persistState=="object"?(lt=e.persistState)==null?void 0:lt.keyPrefix:void 0)!=null?St:"persona-"}event-stream`,G=_?new Is(se):null,U=(qe=(De=(wt=e.features)==null?void 0:wt.eventStream)==null?void 0:De.maxEvents)!=null?qe:2e3,N=_?new ks(U,G):null,ee=null,fe=!1,Fe=null,Mt=0;G==null||G.open().then(()=>N==null?void 0:N.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let gt={onCopy:l=>{var u,h;s.emit("message:copy",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.id,"copy").catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),T!=null&&T.isClientTokenMode()&&T.submitMessageFeedback(l.messageId,l.type).catch(S=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(h=(u=e.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},ft=(ht=e.statusIndicator)!=null?ht:{},Ht=l=>{var u,h,S,W;return l==="idle"?(u=ft.idleText)!=null?u:Rt.idle:l==="connecting"?(h=ft.connectingText)!=null?h:Rt.connecting:l==="connected"?(S=ft.connectedText)!=null?S:Rt.connected:l==="error"?(W=ft.errorText)!=null?W:Rt.error:Rt[l]},{wrapper:je,panel:ne}=ya(e),xe=ba(e,y),{container:He,body:$e,messagesWrapper:ze,suggestions:Ot,textarea:he,sendButton:Z,sendButtonWrapper:ct,composerForm:bt,statusText:kt,introTitle:Ct,introSubtitle:Kt,closeButton:te,iconHolder:Pe,headerTitle:xt,headerSubtitle:ve,header:Se,footer:Je,actionsRow:Bt,leftActions:It,rightActions:qt}=xe,I=xe.micButton,nt=xe.micButtonWrapper,O=xe.attachmentButton,Q=xe.attachmentButtonWrapper,re=xe.attachmentInput,Ne=xe.attachmentPreviewsContainer,oe=null;(Ve=e.attachments)!=null&&Ve.enabled&&re&&Ne&&(oe=Bn.fromConfig(e.attachments),oe.setPreviewsContainer(Ne),re.addEventListener("change",l=>{let u=l.target;oe==null||oe.handleFileSelect(u.files),u.value=""}));let Xe=o.find(l=>l.renderHeader);if(Xe!=null&&Xe.renderHeader){let l=Xe.renderHeader({config:e,defaultRenderer:()=>{let u=mn({config:e,showClose:y});return Fn(He,u,e),u.header},onClose:()=>ot(!1,"user")});if(l){let u=He.querySelector(".tvw-border-b-cw-divider");u&&(u.replaceWith(l),Se=l)}}let Ge=()=>{var u,h,S,W;if(!N)return;if(fe=!0,!ee&&N&&(ee=Ta({buffer:N,getFullHistory:()=>N.getAllFromStore(),onClose:()=>pe(),config:e,plugins:o})),ee&&($e.style.display="none",(u=Je.parentNode)==null||u.insertBefore(ee.element,Je),ee.update()),D){D.classList.remove("tvw-text-cw-muted"),D.classList.add("tvw-text-cw-accent"),D.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let M=(W=(S=(h=e.features)==null?void 0:h.eventStream)==null?void 0:S.classNames)==null?void 0:W.toggleButtonActive;M&&M.split(/\s+/).forEach(j=>j&&D.classList.add(j))}let l=()=>{if(!fe)return;let M=Date.now();M-Mt>=200&&(ee==null||ee.update(),Mt=M),Fe=requestAnimationFrame(l)};Mt=0,Fe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},pe=()=>{var l,u,h;if(fe){if(fe=!1,ee&&ee.element.remove(),$e.style.display="",D){D.classList.remove("tvw-text-cw-accent"),D.classList.add("tvw-text-cw-muted"),D.style.boxShadow="";let S=(h=(u=(l=e.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;S&&S.split(/\s+/).forEach(W=>W&&D.classList.remove(W))}Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(_){let l=(jt=(At=e.features)==null?void 0:At.eventStream)==null?void 0:jt.classNames,u="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");D=g("button",u),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let h=ie("activity","18px","currentColor",1.5);h&&D.appendChild(h);let S=xe.clearChatButtonWrapper,W=xe.closeButtonWrapper,M=S||W;M&&M.parentNode===Se?Se.insertBefore(D,M):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}let Ee=o.find(l=>l.renderComposer);if(Ee!=null&&Ee.renderComposer){let l=Ee.renderComposer({config:e,defaultRenderer:()=>Qn({config:e}).footer,onSubmit:u=>{T&&!T.isStreaming()&&T.sendMessage(u)},disabled:!1});l&&(Je.replaceWith(l),Je=l)}(()=>{var S,W;let l=(W=(S=e.layout)==null?void 0:S.slots)!=null?W:{},u=M=>{switch(M){case"body-top":return He.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ze;case"footer-top":return Ot;case"composer":return bt;case"footer-bottom":return kt;default:return null}},h=(M,j)=>{var le;switch(M){case"header-left":case"header-center":case"header-right":if(M==="header-left")Se.insertBefore(j,Se.firstChild);else if(M==="header-right")Se.appendChild(j);else{let de=Se.querySelector(".tvw-flex-col");de?(le=de.parentNode)==null||le.insertBefore(j,de.nextSibling):Se.appendChild(j)}break;case"body-top":{let de=$e.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");de?de.replaceWith(j):$e.insertBefore(j,$e.firstChild);break}case"body-bottom":$e.appendChild(j);break;case"footer-top":Ot.replaceWith(j);break;case"footer-bottom":kt.replaceWith(j);break;default:break}};for(let[M,j]of Object.entries(l))if(j)try{let le=j({config:e,defaultContent:()=>u(M)});le&&h(M,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${M}":`,le)}})();let rt=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let S=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-bubble-type");M==="reasoning"?(ts.has(W)?ts.delete(W):ts.add(W),Sa(W,S)):M==="tool"&&(ns.has(W)?ns.delete(W):ns.add(W),Aa(W,S,e))};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))}),ze.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),rt(l))});let Yt=new Map;ze.addEventListener("click",l=>{var j;let h=l.target.closest(".tvw-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest("[data-actions-for]");if(!S)return;let W=S.getAttribute("data-actions-for");if(!W)return;let M=h.getAttribute("data-action");if(M==="copy"){let de=T.getMessages().find(ye=>ye.id===W);if(de&&gt.onCopy){let ye=de.content||"";navigator.clipboard.writeText(ye).then(()=>{h.classList.add("tvw-message-action-success");let we=ie("check",14,"currentColor",2);we&&(h.innerHTML="",h.appendChild(we)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let Me=ie("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(we=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",we)}),gt.onCopy(de)}}else if(M==="upvote"||M==="downvote")if(((j=Yt.get(W))!=null?j:null)===M)Yt.delete(W),h.classList.remove("tvw-message-action-active");else{let ye=M==="upvote"?"downvote":"upvote",we=S.querySelector(`[data-action="${ye}"]`);we&&we.classList.remove("tvw-message-action-active"),Yt.set(W,M),h.classList.add("tvw-message-action-active");let J=T.getMessages().find(E=>E.id===W);J&&gt.onFeedback&&gt.onFeedback({type:M,messageId:J.id,message:J})}}),ze.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let S=h.closest(".vanilla-approval-bubble");if(!S)return;let W=S.getAttribute("data-message-id");if(!W)return;let M=h.getAttribute("data-approval-action");if(!M)return;let j=M==="approve"?"approved":"denied",de=T.getMessages().find(we=>we.id===W);if(!(de!=null&&de.approval))return;let ye=S.querySelector("[data-approval-buttons]");ye&&ye.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),T.resolveApproval(de.approval,j)}),ne.appendChild(He),n.appendChild(je);let Qt=()=>{var ce,ge,Oe,me,Ye,ut,K,Ue,on,_t,nn,In,zs,kr,Ir,mt;let l=(ge=(ce=e.launcher)==null?void 0:ce.sidebarMode)!=null?ge:!1,u=l||((me=(Oe=e.launcher)==null?void 0:Oe.fullHeight)!=null?me:!1),h=(Ye=e.theme)!=null?Ye:{},S=(K=(ut=e.launcher)==null?void 0:ut.position)!=null?K:"bottom-left",W=S==="bottom-left"||S==="top-left",M=l?"none":"1px solid var(--tvw-cw-border)",j=l?W?"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)",le=l?"0":"16px",de=(Ue=h.panelBorder)!=null?Ue:M,ye=(on=h.panelShadow)!=null?on:j,we=(_t=h.panelBorderRadius)!=null?_t:le;n.style.cssText="",je.style.cssText="",ne.style.cssText="",He.style.cssText="",$e.style.cssText="",Je.style.cssText="";let Me=(In=(nn=e==null?void 0:e.launcher)==null?void 0:nn.width)!=null?In:e==null?void 0:e.launcherWidth,J=Me!=null?Me:"min(400px, calc(100vw - 24px))";l||(ne.style.width=J,ne.style.maxWidth=J),ne.style.boxShadow=ye,ne.style.borderRadius=we,He.style.border=de,He.style.borderRadius=we;let E=((zs=e.launcher)==null?void 0:zs.enabled)===!1;if(u&&(n.style.display="flex",n.style.flexDirection="column",n.style.height="100%",n.style.minHeight="0",je.style.display="flex",je.style.flexDirection="column",je.style.flex="1 1 0%",je.style.minHeight="0",je.style.maxHeight="100%",je.style.height="100%",E&&(je.style.overflow="hidden"),ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.height="100%",ne.style.overflow="hidden",He.style.display="flex",He.style.flexDirection="column",He.style.flex="1 1 0%",He.style.minHeight="0",He.style.maxHeight="100%",He.style.overflow="hidden",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.overflowY="auto",Je.style.flexShrink="0"),je.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&&!E&&((kr=sn[S])!=null?kr:sn["bottom-right"]).split(" ").forEach(Yn=>je.classList.add(Yn)),l){let Kn=(mt=(Ir=e.launcher)==null?void 0:Ir.sidebarWidth)!=null?mt:"420px";je.style.cssText=`
21
21
  position: fixed !important;
22
22
  top: 0 !important;
23
23
  bottom: 0 !important;
24
- width: ${qn} !important;
24
+ width: ${Kn} !important;
25
25
  height: 100vh !important;
26
26
  max-height: 100vh !important;
27
27
  margin: 0 !important;
28
28
  padding: 0 !important;
29
29
  display: flex !important;
30
30
  flex-direction: column !important;
31
- ${H?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
31
+ ${W?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
32
  `,ne.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
@@ -40,9 +40,9 @@
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${fe} !important;
44
- border-radius: ${xe} !important;
45
- `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),Re.style.cssText=`
43
+ box-shadow: ${ye} !important;
44
+ border-radius: ${we} !important;
45
+ `,ne.style.setProperty("width","100%","important"),ne.style.setProperty("max-width","100%","important"),He.style.cssText=`
46
46
  display: flex !important;
47
47
  flex-direction: column !important;
48
48
  flex: 1 1 0% !important;
@@ -51,13 +51,13 @@
51
51
  min-height: 0 !important;
52
52
  max-height: 100% !important;
53
53
  overflow: hidden !important;
54
- border-radius: ${xe} !important;
55
- border: ${me} !important;
56
- `,qe.style.cssText=`
54
+ border-radius: ${we} !important;
55
+ border: ${de} !important;
56
+ `,Je.style.cssText=`
57
57
  flex-shrink: 0 !important;
58
58
  border-top: none !important;
59
59
  padding: 8px 16px 12px 16px !important;
60
- `}if(!W){let qn="max-height: -moz-available !important; max-height: stretch !important;",zn=l?"":"padding-top: 1.25em !important;";Ne.style.cssText+=qn+zn}};Gt(),ar(n,e);let Ye=[];j&&Ye.push(()=>{Be!==null&&(cancelAnimationFrame(Be),Be=null),Q==null||Q.destroy(),Q=null,O==null||O.destroy(),O=null,Y=null});let Zt=null,fn=()=>{Zt&&(Zt(),Zt=null),e.colorScheme==="auto"&&(Zt=ca(()=>{ar(n,e)}))};fn(),Ye.push(()=>{Zt&&(Zt(),Zt=null)});let wn=va(Nt),sn=null,M,vn=!1,an=!0,Cn=0,rs=0,ln=null,cn=!1,Nn=0,Dn=!1,Bs=125,Fs=2e3,$s=5,os=50,jn=new Map,Ee={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},is=(ut=(_e=e.voiceRecognition)==null?void 0:_e.autoResume)!=null?ut:!1,Qt=l=>{s.emit("voice:state",{active:Ee.active,source:l,timestamp:Date.now()})},Ut=()=>{d(l=>({...l,voiceState:{active:Ee.active,timestamp:Date.now(),manuallyDeactivated:Ee.manuallyDeactivated}}))},Os=()=>{var A,H;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Yr(a.voiceState),p=!!l.active,f=Number((H=l.timestamp)!=null?H:0);Ee.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-f<Wl&&setTimeout(()=>{var P,q;Ee.active||(Ee.manuallyDeactivated=!1,((q=(P=e.voiceRecognition)==null?void 0:P.provider)==null?void 0:q.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("restore"),M.isVoiceActive()&&Tn()}):En("restore"))},1e3)},Ns=()=>M?Ea(M.getMessages()).filter(l=>!l.__skipPersist):[];function as(l){if(!(i!=null&&i.save))return;let f={messages:l?Ea(l):M?Ns():[],metadata:a};try{let A=i.save(f);A instanceof Promise&&A.catch(H=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",H)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let xn=(l=!1)=>{if(!an)return;let p=Date.now();cn&&p<Nn&&!l||(cn&&p>=Nn&&(cn=!1),!(!l&&!vn)&&(p-rs<Bs||(rs=p,ln&&cancelAnimationFrame(ln),ln=requestAnimationFrame(()=>{cn||!an||(Dn=!0,Fe.scrollTop=Fe.scrollHeight,Cn=Fe.scrollTop,requestAnimationFrame(()=>{Dn=!1}),ln=null)}))))},dn=null,Ds=()=>Ne.querySelector("#persona-scroll-container")||Fe,js=(l,p=500)=>{let f=l.scrollTop,A=l.clientHeight,H=l.scrollHeight,P=H-f;if(f+A>=H-2||Math.abs(P)<5)return;dn!==null&&(cancelAnimationFrame(dn),dn=null);let ge=performance.now(),me=xe=>1-Math.pow(1-xe,3),fe=xe=>{let Te=l.scrollHeight;Te!==H&&(H=Te,P=H-f);let te=xe-ge,W=Math.min(te/p,1),he=me(W),we=f+P*he;l.scrollTop=we,W<1?dn=requestAnimationFrame(fe):(l.scrollTop=l.scrollHeight,dn=null)};dn=requestAnimationFrame(fe)},_s=l=>{let p=new Map;l.forEach(f=>{let A=jn.get(f.id);p.set(f.id,{streaming:f.streaming,role:f.role}),!A&&f.role==="assistant"&&s.emit("assistant:message",f),f.role==="assistant"&&(A!=null&&A.streaming)&&f.streaming===!1&&s.emit("assistant:complete",f),f.variant==="approval"&&f.approval&&(A?f.approval.status!=="pending"&&s.emit("approval:resolved",{approval:f.approval,decision:f.approval.status}):s.emit("approval:requested",{approval:f.approval,message:f}))}),jn.clear(),p.forEach((f,A)=>{jn.set(A,f)})},Sn=(l,p,f)=>{var fe,xe,Te,te;let A=document.createElement("div"),P=(()=>{var he;let W=o.find(we=>we.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((he=e.loadingIndicator)!=null&&he.render)return e.loadingIndicator.render})();p.forEach(W=>{var ft,Pt;let he=null,we=o.find(Z=>!!(W.variant==="reasoning"&&Z.renderReasoning||W.variant==="tool"&&Z.renderToolCall||W.variant==="approval"&&Z.renderApproval||!W.variant&&Z.renderMessage)),st=(ft=e.layout)==null?void 0:ft.messages;if(we)if(W.variant==="reasoning"&&W.reasoning&&we.renderReasoning){if(!U)return;he=we.renderReasoning({message:W,defaultRenderer:()=>Nr(W),config:e})}else if(W.variant==="tool"&&W.toolCall&&we.renderToolCall){if(!K)return;he=we.renderToolCall({message:W,defaultRenderer:()=>Dr(W,e),config:e})}else if(W.variant==="approval"&&W.approval&&we.renderApproval){if(e.approval===!1)return;he=we.renderApproval({message:W,defaultRenderer:()=>jr(W,e),config:e})}else we.renderMessage&&(he=we.renderMessage({message:W,defaultRenderer:()=>{let Z=Gn(W,f,st,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e});return W.role!=="user"&&Vr(Z,W,e,M),Z},config:e}));if(!he&&W.role==="assistant"&&!W.variant&&e.enableComponentStreaming!==!1&&gr(W)){let je=mr(W);if(je){let rn=pr(je,{config:e,message:W,transform:f});if(rn){let jt=document.createElement("div");if(jt.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(" "),jt.id=`bubble-${W.id}`,jt.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let tn=document.createElement("div");tn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",tn.innerHTML=f({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),jt.appendChild(tn)}jt.appendChild(rn),he=jt}}}if(!he)if(W.variant==="reasoning"&&W.reasoning){if(!U)return;he=Nr(W)}else if(W.variant==="tool"&&W.toolCall){if(!K)return;he=Dr(W,e)}else if(W.variant==="approval"&&W.approval){if(e.approval===!1)return;he=jr(W,e)}else{let Z=(Pt=e.layout)==null?void 0:Pt.messages;Z!=null&&Z.renderUserMessage&&W.role==="user"?he=Z.renderUserMessage({message:W,config:e,streaming:!!W.streaming}):Z!=null&&Z.renderAssistantMessage&&W.role==="assistant"?he=Z.renderAssistantMessage({message:W,config:e,streaming:!!W.streaming}):he=Gn(W,f,Z,e.messageActions,dt,{loadingIndicatorRenderer:P,widgetConfig:e}),W.role!=="user"&&he&&Vr(he,W,e,M)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${W.id}`,Pe.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(he),A.appendChild(Pe)});let q=p.some(W=>W.role==="assistant"&&W.streaming),ge=p[p.length-1],me=(ge==null?void 0:ge.role)==="assistant"&&!ge.streaming&&ge.variant!=="approval";if(vn&&p.some(W=>W.role==="user")&&!q&&!me){let W={config:e,streaming:!0,location:"standalone",defaultRenderer:Fn},he=o.find(st=>st.renderLoadingIndicator),we=null;if(he!=null&&he.renderLoadingIndicator&&(we=he.renderLoadingIndicator(W)),we===null&&((fe=e.loadingIndicator)!=null&&fe.render)&&(we=e.loadingIndicator.render(W)),we===null&&(we=Fn()),we){let st=document.createElement("div"),Pe=((xe=e.loadingIndicator)==null?void 0:xe.showBubble)!==!1;st.className=Pe?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),st.setAttribute("data-typing-indicator","true"),st.appendChild(we);let ft=document.createElement("div");ft.className="tvw-flex",ft.id="wrapper-typing-indicator",ft.setAttribute("data-wrapper-id","typing-indicator"),ft.appendChild(st),A.appendChild(ft)}}if(!vn&&p.length>0){let W=p[p.length-1],he={config:e,lastMessage:W,messageCount:p.length},we=o.find(Pe=>Pe.renderIdleIndicator),st=null;if(we!=null&&we.renderIdleIndicator&&(st=we.renderIdleIndicator(he)),st===null&&((Te=e.loadingIndicator)!=null&&Te.renderIdle)&&(st=e.loadingIndicator.renderIdle(he)),st){let Pe=document.createElement("div"),ft=((te=e.loadingIndicator)==null?void 0:te.showBubble)!==!1;Pe.className=ft?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(st);let Pt=document.createElement("div");Pt.className="tvw-flex",Pt.id="wrapper-idle-indicator",Pt.setAttribute("data-wrapper-id","idle-indicator"),Pt.appendChild(Pe),A.appendChild(Pt)}}ua(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let W=Ds();js(W)})})},An=()=>{y&&(I?(Ne.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-95","tvw-opacity-0"),ne.classList.add("tvw-scale-100","tvw-opacity-100"),Xe?Xe.element.style.display="none":Ge&&(Ge.style.display="none")):(Ne.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-100","tvw-opacity-100"),ne.classList.add("tvw-scale-95","tvw-opacity-0"),Xe?Xe.element.style.display="":Ge&&(Ge.style.display="")))},nt=(l,p="user")=>{if(!y||I===l)return;let f=I;I=l,An(),I&&(yn(),xn(!0));let A={open:I,source:p,timestamp:Date.now()};I&&!f?s.emit("widget:opened",A):!I&&f&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()})},_n=l=>{X.disabled=l,F&&(F.disabled=l),wn.buttons.forEach(p=>{p.disabled=l})},Vn=()=>{Ee.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>Vn(),200)});let ls=()=>{var H,P,q,ge,me,fe,xe,Te,te,W,he,we,st,Pe;yt.textContent=(P=(H=e.copy)==null?void 0:H.welcomeTitle)!=null?P:"Hello \u{1F44B}",Kt.textContent=(ge=(q=e.copy)==null?void 0:q.welcomeSubtitle)!=null?ge:"Ask anything about your account or products.",de.placeholder=(fe=(me=e.copy)==null?void 0:me.inputPlaceholder)!=null?fe:"How can I help...",(Te=(xe=e.sendButton)==null?void 0:xe.useIcon)!=null&&Te||(X.textContent=(W=(te=e.copy)==null?void 0:te.sendButtonLabel)!=null?W:"Send");let p=(we=(he=e.theme)==null?void 0:he.inputFontFamily)!=null?we:"sans-serif",f=(Pe=(st=e.theme)==null?void 0:st.inputFontWeight)!=null?Pe:"400",A=ft=>{switch(ft){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};de.style.fontFamily=A(p),de.style.fontWeight=f};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(p=>({...p,sessionId:l}))}}),M=new Kn(e,{onMessagesChanged(l){Sn(Ue,l,z),M&&(l.some(H=>H.role==="user")?wn.render([],M,de,l):wn.render(e.suggestionChips,M,de,l,e.suggestionChipsConfig)),xn(!vn),_s(l);let p=[...l].reverse().find(A=>A.role==="user"),f=Ee.lastUserMessageId;p&&p.id!==f&&(Ee.lastUserMessageId=p.id,s.emit("user:message",p)),Ee.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),as(l)},onStatusChanged(l){var A;let p=(A=e.statusIndicator)!=null?A:{},f=H=>{var P,q,ge,me;return H==="idle"?(P=p.idleText)!=null?P:Rt.idle:H==="connecting"?(q=p.connectingText)!=null?q:Rt.connecting:H==="connected"?(ge=p.connectedText)!=null?ge:Rt.connected:H==="error"?(me=p.errorText)!=null?me:Rt.error:Rt[H]};Tt.textContent=f(l)},onStreamingChanged(l){vn=l,_n(l),M&&Sn(Ue,M.getMessages(),z),l||xn(!0)},onVoiceStatusChanged(l){var p,f;((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"&&l!=="listening"&&(Ee.active=!1,Mn(),Qt("system"),Ut())}}),((xt=(Ve=e.voiceRecognition)==null?void 0:Ve.provider)==null?void 0:xt.type)==="runtype")try{M.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&M.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),O&&M.setSSEEventCallback((l,p)=>{O==null||O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),u&&u.then(l=>{var p;l&&(l.metadata&&(a=Yr(l.metadata),b.syncFromMetadata()),(p=l.messages)!=null&&p.length&&M.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let cs=l=>{var H;l.preventDefault();let p=de.value.trim(),f=(H=oe==null?void 0:oe.hasAttachments())!=null?H:!1;if(!p&&!f)return;let A;f&&(A=[],A.push(...oe.getContentParts()),p&&A.push(sr(p))),de.value="",de.style.height="auto",M.sendMessage(p,{contentParts:A}),f&&oe.clearAttachments()},ds=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},us=async l=>{var f;if(((f=e.attachments)==null?void 0:f.enabled)!==!0||!oe)return;let p=Rl(l.clipboardData);p.length!==0&&(l.preventDefault(),await oe.handleFiles(p))},Ft=null,qt=!1,un=null,kt=null,ps=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,En=(l="user")=>{var P,q,ge,me;if(qt||M.isStreaming())return;let p=ps();if(!p)return;Ft=new p;let A=(q=((P=e.voiceRecognition)!=null?P:{}).pauseDuration)!=null?q:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let H=de.value;Ft.onresult=fe=>{let xe="",Te="";for(let W=0;W<fe.results.length;W++){let he=fe.results[W],we=he[0].transcript;he.isFinal?xe+=we+" ":Te=we}let te=H+xe+Te;de.value=te,un&&clearTimeout(un),(xe||Te)&&(un=window.setTimeout(()=>{let W=de.value.trim();W&&Ft&&qt&&(en(),de.value="",de.style.height="auto",M.sendMessage(W,{viaVoice:!0}))},A))},Ft.onerror=fe=>{fe.error!=="no-speech"&&en()},Ft.onend=()=>{if(qt){let fe=de.value.trim();fe&&fe!==H.trim()&&(de.value="",de.style.height="auto",M.sendMessage(fe,{viaVoice:!0})),en()}};try{if(Ft.start(),qt=!0,Ee.active=!0,l!=="system"&&(Ee.manuallyDeactivated=!1),Qt(l),Ut(),F){kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let fe=(ge=e.voiceRecognition)!=null?ge:{},xe=(me=fe.recordingBackgroundColor)!=null?me:"#ef4444",Te=fe.recordingIconColor,te=fe.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=xe,Te){F.style.color=Te;let W=F.querySelector("svg");W&&W.setAttribute("stroke",Te)}te&&(F.style.borderColor=te),F.setAttribute("aria-label","Stop voice recognition")}}catch{en("system")}},en=(l="user")=>{if(qt){if(qt=!1,un&&(clearTimeout(un),un=null),Ft){try{Ft.stop()}catch{}Ft=null}if(Ee.active=!1,Qt(l),Ut(),F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=kt.backgroundColor,F.style.color=kt.color,F.style.borderColor=kt.borderColor;let p=F.querySelector("svg");p&&p.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}}},Vs=(l,p)=>{var Pe,ft,Pt,Z,je,rn,jt,tn;let f=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((Pe=l==null?void 0:l.provider)==null?void 0:Pe.type)==="runtype";if(!(f||A))return null;let P=g("div","tvw-send-button-wrapper"),q=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");q.type="button",q.setAttribute("aria-label","Start voice recognition");let ge=(ft=l==null?void 0:l.iconName)!=null?ft:"mic",me=(Pt=p==null?void 0:p.size)!=null?Pt:"40px",fe=(Z=l==null?void 0:l.iconSize)!=null?Z:me,xe=parseFloat(fe)||24,Te=(je=l==null?void 0:l.backgroundColor)!=null?je:p==null?void 0:p.backgroundColor,te=(rn=l==null?void 0:l.iconColor)!=null?rn:p==null?void 0:p.textColor;q.style.width=fe,q.style.height=fe,q.style.minWidth=fe,q.style.minHeight=fe,q.style.fontSize="18px",q.style.lineHeight="1";let W=te||"currentColor",he=ie(ge,xe,W,1.5);he?(q.appendChild(he),q.style.color=W):(q.textContent="\u{1F3A4}",q.style.color=W),Te?q.style.backgroundColor=Te:q.classList.add("tvw-bg-cw-primary"),te?q.style.color=te:!te&&!(p!=null&&p.textColor)&&q.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(q.style.borderWidth=l.borderWidth,q.style.borderStyle="solid"),l!=null&&l.borderColor&&(q.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(q.style.paddingLeft=l.paddingX,q.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(q.style.paddingTop=l.paddingY,q.style.paddingBottom=l.paddingY),P.appendChild(q);let we=(jt=l==null?void 0:l.tooltipText)!=null?jt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&we){let kn=g("div","tvw-send-button-tooltip");kn.textContent=we,P.appendChild(kn)}return{micButton:q,micButtonWrapper:P}},Tn=()=>{var H,P;if(!F)return;kt={backgroundColor:F.style.backgroundColor,color:F.style.color,borderColor:F.style.borderColor};let l=(H=e.voiceRecognition)!=null?H:{},p=(P=l.recordingBackgroundColor)!=null?P:"#ef4444",f=l.recordingIconColor,A=l.recordingBorderColor;if(F.classList.add("tvw-voice-recording"),F.style.backgroundColor=p,f){F.style.color=f;let q=F.querySelector("svg");q&&q.setAttribute("stroke",f)}A&&(F.style.borderColor=A),F.setAttribute("aria-label","Stop voice recognition")},Mn=()=>{var l,p,f;if(F){if(F.classList.remove("tvw-voice-recording"),kt){F.style.backgroundColor=(l=kt.backgroundColor)!=null?l:"",F.style.color=(p=kt.color)!=null?p:"",F.style.borderColor=(f=kt.borderColor)!=null?f:"";let A=F.querySelector("svg");A&&A.setAttribute("stroke",kt.color||"currentColor"),kt=null}F.setAttribute("aria-label","Start voice recognition")}},Un=()=>{var l,p;if(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"){M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Ee.manuallyDeactivated=!M.isVoiceActive(),Ut(),Qt("user"),M.isVoiceActive()?Tn():Mn()});return}if(qt){let f=de.value.trim();Ee.manuallyDeactivated=!0,Ut(),en("user"),f&&(de.value="",de.style.height="auto",M.sendMessage(f))}else Ee.manuallyDeactivated=!1,Ut(),En("user")};F&&(F.addEventListener("click",Un),Ye.push(()=>{var l,p;((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?(M.isVoiceActive()&&M.toggleVoice(),Mn()):en("system"),F&&F.removeEventListener("click",Un)}));let Us=s.on("assistant:complete",()=>{is&&(Ee.active||Ee.manuallyDeactivated||is==="assistant"&&!Ee.lastUserMessageWasVoice||setTimeout(()=>{var l,p;!Ee.active&&!Ee.manuallyDeactivated&&(((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("auto"),M.isVoiceActive()&&Tn()}):En("auto"))},600))});Ye.push(Us);let qs=s.on("action:resubmit",()=>{setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)});Ye.push(qs);let pn=()=>{nt(!I,"user")},Xe=null,Ge=null;if(y){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:e,defaultRenderer:()=>Is(e,pn).element,onToggle:pn});p&&(Ge=p)}Ge||(Xe=Is(e,pn))}Xe?n.appendChild(Xe.element):Ge&&n.appendChild(Ge),An(),wn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),ls(),_n(M.isStreaming()),xn(!0),Os(),x&&(y?I&&setTimeout(()=>Vn(),200):setTimeout(()=>Vn(),0));let yn=()=>{var f,A,H,P,q,ge,me,fe;let l=(A=(f=e.launcher)==null?void 0:f.sidebarMode)!=null?A:!1,p=l||((P=(H=e.launcher)==null?void 0:H.fullHeight)!=null?P:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let xe=(ge=(q=e==null?void 0:e.launcher)==null?void 0:q.width)!=null?ge:e==null?void 0:e.launcherWidth,Te=xe!=null?xe:"min(400px, calc(100vw - 24px))";ne.style.width=Te,ne.style.maxWidth=Te}if(!p){let xe=window.innerHeight,Te=64,te=(fe=(me=e.launcher)==null?void 0:me.heightOffset)!=null?fe:0,W=Math.max(200,xe-Te),he=Math.min(640,W),we=Math.max(200,he-te);ne.style.height=`${we}px`}};yn(),window.addEventListener("resize",yn),Ye.push(()=>window.removeEventListener("resize",yn)),Cn=Fe.scrollTop;let gs=()=>{let l=Fe.scrollTop,p=Fe.scrollHeight,f=Fe.clientHeight,A=p-l-f,H=Math.abs(l-Cn);if(Cn=l,!Dn&&!(H<=$s)){if(!an&&A<os){cn=!1,an=!0;return}an&&A>os&&(cn=!0,Nn=Date.now()+Fs,an=!1)}};Fe.addEventListener("scroll",gs,{passive:!0}),Ye.push(()=>Fe.removeEventListener("scroll",gs)),Ye.push(()=>{ln&&cancelAnimationFrame(ln)});let ms=()=>{ee&&(sn&&(ee.removeEventListener("click",sn),sn=null),y?(ee.style.display="",sn=()=>{I=!1,An()},ee.addEventListener("click",sn)):ee.style.display="none")};ms(),(()=>{let{clearChatButton:l}=be;l&&l.addEventListener("click",()=>{M.clearMessages();try{localStorage.removeItem(ss),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ss}`)}catch(f){console.error("[AgentWidget] Failed to clear default localStorage:",f)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==ss)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(f){console.error("[AgentWidget] Failed to clear custom localStorage:",f)}let p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let f=i.clear();f instanceof Promise&&f.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(f){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()})})(),vt.addEventListener("submit",cs),de.addEventListener("keydown",ds),de.addEventListener("paste",us),Ye.push(()=>{vt.removeEventListener("submit",cs),de.removeEventListener("keydown",ds),de.removeEventListener("paste",us)}),Ye.push(()=>{M.cancel()}),Xe?Ye.push(()=>{Xe==null||Xe.destroy()}):Ge&&Ye.push(()=>{Ge==null||Ge.remove()});let It={update(l){var ro,oo,io,ao,lo,co,uo,po,go,mo,ho,fo,wo,vo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,Oo,No,Do,jo,_o,Vo,Uo,qo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,mi,hi,fi,wi,vi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi,ki,Ii,Li,Wi,Pi,Ri,Hi,Bi,Fi,$i,Oi,Ni,Di;let p=e.toolCall,f=e.colorScheme;e={...e,...l},Gt(),ar(n,e),e.colorScheme!==f&&fn();let A=Ps.getForInstance(e.plugins);o.length=0,o.push(...A),y=(oo=(ro=e.launcher)==null?void 0:ro.enabled)!=null?oo:!0,S=(ao=(io=e.launcher)==null?void 0:io.autoExpand)!=null?ao:!1,U=(co=(lo=e.features)==null?void 0:lo.showReasoning)!=null?co:!0,K=(po=(uo=e.features)==null?void 0:uo.showToolCalls)!=null?po:!0;let H=j;if(j=(mo=(go=e.features)==null?void 0:go.showEventStreamToggle)!=null?mo:!1,j&&!H){if(O||(Y=new Ws(se),O=new Ls(_,Y),Y.open().then(()=>O==null?void 0:O.restore()).catch(()=>{}),M.setSSEEventCallback((R,Me)=>{O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:R,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&Ce){let R=(fo=(ho=e.features)==null?void 0:ho.eventStream)==null?void 0:fo.classNames,Me="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(R!=null&&R.toggleButton?" "+R.toggleButton:"");D=g("button",Me),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let Ze=ie("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=be.clearChatButtonWrapper,He=be.closeButtonWrapper,wt=ve||He;wt&&wt.parentNode===Ce?Ce.insertBefore(D,wt):Ce.appendChild(D),D.addEventListener("click",()=>{ue?ce():Ke()})}}else!j&&H&&(ce(),D&&(D.remove(),D=null),O==null||O.clear(),Y==null||Y.destroy(),O=null,Y=null);if(((wo=e.launcher)==null?void 0:wo.enabled)===!1&&Xe&&(Xe.destroy(),Xe=null),((vo=e.launcher)==null?void 0:vo.enabled)===!1&&Ge&&(Ge.remove(),Ge=null),((yo=e.launcher)==null?void 0:yo.enabled)!==!1&&!Xe&&!Ge){let R=o.find(Me=>Me.renderLauncher);if(R!=null&&R.renderLauncher){let Me=R.renderLauncher({config:e,defaultRenderer:()=>Is(e,pn).element,onToggle:pn});Me&&(Ge=Me,n.appendChild(Ge))}Ge||(Xe=Is(e,pn),n.appendChild(Xe.element))}Xe&&Xe.update(e),bt&&((bo=e.launcher)==null?void 0:bo.title)!==void 0&&(bt.textContent=e.launcher.title),pe&&((Co=e.launcher)==null?void 0:Co.subtitle)!==void 0&&(pe.textContent=e.launcher.subtitle);let P=(xo=e.layout)==null?void 0:xo.header;if((P==null?void 0:P.layout)!==E&&Ce){let R=P?Yn(e,P,{showClose:y,onClose:()=>nt(!1,"user")}):mn({config:e,showClose:y,onClose:()=>nt(!1,"user")});Ce.replaceWith(R.header),Ce=R.header,Le=R.iconHolder,bt=R.headerTitle,pe=R.headerSubtitle,ee=R.closeButton,E=P==null?void 0:P.layout}else if(P&&(Le&&(Le.style.display=P.showIcon===!1?"none":""),bt&&(bt.style.display=P.showTitle===!1?"none":""),pe&&(pe.style.display=P.showSubtitle===!1?"none":""),ee&&(ee.style.display=P.showCloseButton===!1?"none":""),be.clearChatButtonWrapper)){let R=P.showClearChat;if(R!==void 0){be.clearChatButtonWrapper.style.display=R?"":"none";let{closeButtonWrapper:Me}=be;Me&&!Me.classList.contains("tvw-absolute")&&(R?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let ge=((So=e.layout)==null?void 0:So.showHeader)!==!1;Ce&&(Ce.style.display=ge?"":"none");let me=((Ao=e.layout)==null?void 0:Ao.showFooter)!==!1;qe&&(qe.style.display=me?"":"none"),y!==J?y?nt(S,"auto"):(I=!0,An()):S!==k&&nt(S,"auto"),k=S,J=y,yn(),ms(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&M&&Sn(Ue,M.getMessages(),z);let te=(Eo=e.launcher)!=null?Eo:{},W=(To=te.headerIconHidden)!=null?To:!1,he=(ko=(Mo=e.layout)==null?void 0:Mo.header)==null?void 0:ko.showIcon,we=W||he===!1,st=te.headerIconName,Pe=(Io=te.headerIconSize)!=null?Io:"48px";if(Le){let R=Re.querySelector(".tvw-border-b-cw-divider"),Me=R==null?void 0:R.querySelector(".tvw-flex-col");if(we)Le.style.display="none",R&&Me&&!R.contains(Me)&&R.insertBefore(Me,R.firstChild);else{if(Le.style.display="",Le.style.height=Pe,Le.style.width=Pe,R&&Me&&(R.contains(Le)?Le.nextSibling!==Me&&(Le.remove(),R.insertBefore(Le,Me)):R.insertBefore(Le,Me)),st){let ve=parseFloat(Pe)||24,He=ie(st,ve*.6,"#ffffff",2);He?Le.replaceChildren(He):Le.textContent=(Lo=te.agentIconText)!=null?Lo:"\u{1F4AC}"}else if(te.iconUrl){let ve=Le.querySelector("img");if(ve)ve.src=te.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let He=document.createElement("img");He.src=te.iconUrl,He.alt="",He.className="tvw-rounded-xl tvw-object-cover",He.style.height=Pe,He.style.width=Pe,Le.replaceChildren(He)}}else{let ve=Le.querySelector("svg"),He=Le.querySelector("img");(ve||He)&&Le.replaceChildren(),Le.textContent=(Wo=te.agentIconText)!=null?Wo:"\u{1F4AC}"}let Ze=Le.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let ft=(Ro=(Po=e.layout)==null?void 0:Po.header)==null?void 0:Ro.showTitle,Pt=(Bo=(Ho=e.layout)==null?void 0:Ho.header)==null?void 0:Bo.showSubtitle;if(bt&&(bt.style.display=ft===!1?"none":""),pe&&(pe.style.display=Pt===!1?"none":""),ee){(($o=(Fo=e.layout)==null?void 0:Fo.header)==null?void 0:$o.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Oo=te.closeButtonSize)!=null?Oo:"32px",Ze=(No=te.closeButtonPlacement)!=null?No:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=be,He=Ze==="top-right",wt=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&He!==wt)if(ve.remove(),He)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Re.style.position="relative",Re.appendChild(ve);else{let ke=(jo=(Do=te.clearChat)==null?void 0:Do.placement)!=null?jo:"inline",St=(Vo=(_o=te.clearChat)==null?void 0:_o.enabled)!=null?Vo:!0;ve.className=St&&ke==="inline"?"":"tvw-ml-auto";let _t=Re.querySelector(".tvw-border-b-cw-divider");_t&&_t.appendChild(ve)}if(te.closeButtonColor?(ee.style.color=te.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),te.closeButtonBackgroundColor?(ee.style.backgroundColor=te.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),te.closeButtonBorderWidth||te.closeButtonBorderColor){let ke=te.closeButtonBorderWidth||"0px",St=te.closeButtonBorderColor||"transparent";ee.style.border=`${ke} solid ${St}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");te.closeButtonBorderRadius?(ee.style.borderRadius=te.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),te.closeButtonPaddingX?(ee.style.paddingLeft=te.closeButtonPaddingX,ee.style.paddingRight=te.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),te.closeButtonPaddingY?(ee.style.paddingTop=te.closeButtonPaddingY,ee.style.paddingBottom=te.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let Wt=(Uo=te.closeButtonIconName)!=null?Uo:"x",zt=(qo=te.closeButtonIconText)!=null?qo:"\xD7";ee.innerHTML="";let Ot=ie(Wt,"20px",te.closeButtonColor||"",2);Ot?ee.appendChild(Ot):ee.textContent=zt;let ct=(zo=te.closeButtonTooltipText)!=null?zo:"Close chat",Jt=(Jo=te.closeButtonShowTooltip)!=null?Jo:!0;if(ee.setAttribute("aria-label",ct),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!ee)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let Ss=g("div");Ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(Ss);let In=ee.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${In.left+In.width/2}px`,ke.style.top=`${In.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};ve.addEventListener("mouseenter",St),ve.addEventListener("mouseleave",_t),ee.addEventListener("focus",St),ee.addEventListener("blur",_t),ve._cleanupTooltip=()=>{_t(),ve&&(ve.removeEventListener("mouseenter",St),ve.removeEventListener("mouseleave",_t)),ee&&(ee.removeEventListener("focus",St),ee.removeEventListener("blur",_t))}}}let{clearChatButton:Z,clearChatButtonWrapper:je}=be;if(Z){let R=(Ko=te.clearChat)!=null?Ko:{},Me=(Yo=R.enabled)!=null?Yo:!0,Ze=(Go=(Xo=e.layout)==null?void 0:Xo.header)==null?void 0:Go.showClearChat,ve=Ze!==void 0?Ze:Me,He=(Zo=R.placement)!=null?Zo:"inline";if(je){je.style.display=ve?"":"none";let{closeButtonWrapper:wt}=be;wt&&!wt.classList.contains("tvw-absolute")&&(ve?wt.classList.remove("tvw-ml-auto"):wt.classList.add("tvw-ml-auto"));let Wt=He==="top-right",zt=je.classList.contains("tvw-absolute");if(Wt!==zt&&ve){if(je.remove(),Wt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",Re.style.position="relative",Re.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let ct=Re.querySelector(".tvw-border-b-cw-divider"),Jt=be.closeButtonWrapper;ct&&Jt&&Jt.parentElement===ct?ct.insertBefore(je,Jt):ct&&ct.appendChild(je)}let Ot=be.closeButtonWrapper;Ot&&!Ot.classList.contains("tvw-absolute")&&(Wt?Ot.classList.add("tvw-ml-auto"):Ot.classList.remove("tvw-ml-auto"))}}if(ve){let wt=(Qo=R.size)!=null?Qo:"32px";Z.style.height=wt,Z.style.width=wt;let Wt=(ei=R.iconName)!=null?ei:"refresh-cw",zt=(ti=R.iconColor)!=null?ti:"";Z.innerHTML="";let Ot=ie(Wt,"20px",zt||"",2);if(Ot&&Z.appendChild(Ot),zt?(Z.style.color=zt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),R.backgroundColor?(Z.style.backgroundColor=R.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),R.borderWidth||R.borderColor){let ke=R.borderWidth||"0px",St=R.borderColor||"transparent";Z.style.border=`${ke} solid ${St}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");R.borderRadius?(Z.style.borderRadius=R.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),R.paddingX?(Z.style.paddingLeft=R.paddingX,Z.style.paddingRight=R.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),R.paddingY?(Z.style.paddingTop=R.paddingY,Z.style.paddingBottom=R.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ct=(ni=R.tooltipText)!=null?ni:"Clear chat",Jt=(si=R.showTooltip)!=null?si:!0;if(Z.setAttribute("aria-label",ct),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),Jt&&ct)){let ke=null,St=()=>{if(ke||!Z)return;ke=g("div","tvw-clear-chat-tooltip"),ke.textContent=ct;let Ss=g("div");Ss.className="tvw-clear-chat-tooltip-arrow",ke.appendChild(Ss);let In=Z.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${In.left+In.width/2}px`,ke.style.top=`${In.top-8}px`,ke.style.transform="translate(-50%, -100%)",document.body.appendChild(ke)},_t=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};je.addEventListener("mouseenter",St),je.addEventListener("mouseleave",_t),Z.addEventListener("focus",St),Z.addEventListener("blur",_t),je._cleanupTooltip=()=>{_t(),je&&(je.removeEventListener("mouseenter",St),je.removeEventListener("mouseleave",_t)),Z&&(Z.removeEventListener("focus",St),Z.removeEventListener("blur",_t))}}}}let rn=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Rs],jt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[$n.message,$n.messageAndClick];b=Hs({parsers:rn,handlers:jt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=Ta(e,b,le),M.updateConfig(e),Sn(Ue,M.getMessages(),z),wn.render(e.suggestionChips,M,de,void 0,e.suggestionChipsConfig),ls(),_n(M.isStreaming());let tn=((ri=e.voiceRecognition)==null?void 0:ri.enabled)===!0,kn=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),zs=((ii=(oi=e.voiceRecognition)==null?void 0:oi.provider)==null?void 0:ii.type)==="runtype";if(tn&&(kn||zs))if(!F||!Qe){let R=Vs(e.voiceRecognition,e.sendButton);R&&(F=R.micButton,Qe=R.micButtonWrapper,Vt.insertBefore(Qe,at),F.addEventListener("click",Un),F.disabled=M.isStreaming())}else{let R=(ai=e.voiceRecognition)!=null?ai:{},Me=(li=e.sendButton)!=null?li:{},Ze=(ci=R.iconName)!=null?ci:"mic",ve=(di=Me.size)!=null?di:"40px",He=(ui=R.iconSize)!=null?ui:ve,wt=parseFloat(He)||24;F.style.width=He,F.style.height=He,F.style.minWidth=He,F.style.minHeight=He;let Wt=(gi=(pi=R.iconColor)!=null?pi:Me.textColor)!=null?gi:"currentColor";F.innerHTML="";let zt=ie(Ze,wt,Wt,2);zt?F.appendChild(zt):F.textContent="\u{1F3A4}";let Ot=(mi=R.backgroundColor)!=null?mi:Me.backgroundColor;Ot?(F.style.backgroundColor=Ot,F.classList.remove("tvw-bg-cw-primary")):(F.style.backgroundColor="",F.classList.add("tvw-bg-cw-primary")),Wt?(F.style.color=Wt,F.classList.remove("tvw-text-white")):!Wt&&!Me.textColor&&(F.style.color="",F.classList.add("tvw-text-white")),R.borderWidth?(F.style.borderWidth=R.borderWidth,F.style.borderStyle="solid"):(F.style.borderWidth="",F.style.borderStyle=""),R.borderColor?F.style.borderColor=R.borderColor:F.style.borderColor="",R.paddingX?(F.style.paddingLeft=R.paddingX,F.style.paddingRight=R.paddingX):(F.style.paddingLeft="",F.style.paddingRight=""),R.paddingY?(F.style.paddingTop=R.paddingY,F.style.paddingBottom=R.paddingY):(F.style.paddingTop="",F.style.paddingBottom="");let ct=Qe==null?void 0:Qe.querySelector(".tvw-send-button-tooltip"),Jt=(hi=R.tooltipText)!=null?hi:"Start voice recognition";if(((fi=R.showTooltip)!=null?fi:!1)&&Jt)if(ct)ct.textContent=Jt,ct.style.display="";else{let St=document.createElement("div");St.className="tvw-send-button-tooltip",St.textContent=Jt,Qe==null||Qe.insertBefore(St,F)}else ct&&(ct.style.display="none");Qe.style.display="",F.disabled=M.isStreaming()}else F&&Qe&&(Qe.style.display="none",((vi=(wi=e.voiceRecognition)==null?void 0:wi.provider)==null?void 0:vi.type)==="runtype"?M.isVoiceActive()&&M.toggleVoice():qt&&en());if(((yi=e.attachments)==null?void 0:yi.enabled)===!0)if(!G||!N){let R=(bi=e.attachments)!=null?bi:{},Ze=(xi=((Ci=e.sendButton)!=null?Ci:{}).size)!=null?xi:"40px";$e||($e=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",vt.insertBefore($e,de)),re||(re=document.createElement("input"),re.type="file",re.accept=((Si=R.allowedTypes)!=null?Si:bn).join(","),re.multiple=((Ai=R.maxFiles)!=null?Ai:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),vt.insertBefore(re,de)),G=g("div","tvw-send-button-wrapper"),N=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),N.type="button",N.setAttribute("aria-label",(Ei=R.buttonTooltipText)!=null?Ei:"Attach file");let ve=(Ti=R.buttonIconName)!=null?Ti:"paperclip",He=Ze,wt=parseFloat(He)||40,Wt=Math.round(wt*.6);N.style.width=He,N.style.height=He,N.style.minWidth=He,N.style.minHeight=He,N.style.fontSize="18px",N.style.lineHeight="1",N.style.backgroundColor="transparent",N.style.color="var(--cw-primary, #111827)",N.style.border="none",N.style.borderRadius="6px",N.style.transition="background-color 0.15s ease",N.addEventListener("mouseenter",()=>{N.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),N.addEventListener("mouseleave",()=>{N.style.backgroundColor="transparent"});let zt=ie(ve,Wt,"currentColor",1.5);zt?N.appendChild(zt):N.textContent="\u{1F4CE}",N.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),G.appendChild(N);let Ot=(Mi=R.buttonTooltipText)!=null?Mi:"Attach file",ct=g("div","tvw-send-button-tooltip");ct.textContent=Ot,G.appendChild(ct),Mt.append(G),!oe&&re&&$e&&(oe=Hn.fromConfig(R),oe.setPreviewsContainer($e),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{G.style.display="";let R=(ki=e.attachments)!=null?ki:{};re&&(re.accept=((Ii=R.allowedTypes)!=null?Ii:bn).join(","),re.multiple=((Li=R.maxFiles)!=null?Li:4)>1),oe&&oe.updateConfig({allowedTypes:R.allowedTypes,maxFileSize:R.maxFileSize,maxFiles:R.maxFiles})}else G&&(G.style.display="none"),oe&&oe.clearAttachments();let pt=(Wi=e.sendButton)!=null?Wi:{},qn=(Pi=pt.useIcon)!=null?Pi:!1,zn=(Ri=pt.iconText)!=null?Ri:"\u2191",so=pt.iconName,kr=(Hi=pt.tooltipText)!=null?Hi:"Send message",Ba=(Bi=pt.showTooltip)!=null?Bi:!1,bs=(Fi=pt.size)!=null?Fi:"40px",Js=pt.backgroundColor,on=pt.textColor;if(qn){if(X.style.width=bs,X.style.height=bs,X.style.minWidth=bs,X.style.minHeight=bs,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",so){let R=parseFloat(bs)||24,Me=on&&typeof on=="string"&&on.trim()?on.trim():"currentColor",Ze=ie(so,R,Me,2);Ze?(X.appendChild(Ze),X.style.color=Me):(X.textContent=zn,on?X.style.color=on:X.classList.add("tvw-text-white"))}else X.textContent=zn,on?X.style.color=on:X.classList.add("tvw-text-white");X.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Js?(X.style.backgroundColor=Js,X.classList.remove("tvw-bg-cw-primary")):X.classList.add("tvw-bg-cw-primary")}else X.textContent=(Oi=($i=e.copy)==null?void 0:$i.sendButtonLabel)!=null?Oi:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.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",Js?(X.style.backgroundColor=Js,X.classList.remove("tvw-bg-cw-accent")):X.classList.add("tvw-bg-cw-accent"),on?X.style.color=on:X.classList.add("tvw-text-white");pt.borderWidth?(X.style.borderWidth=pt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),pt.borderColor?X.style.borderColor=pt.borderColor:X.style.borderColor="",pt.paddingX?(X.style.paddingLeft=pt.paddingX,X.style.paddingRight=pt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),pt.paddingY?(X.style.paddingTop=pt.paddingY,X.style.paddingBottom=pt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let Cs=at==null?void 0:at.querySelector(".tvw-send-button-tooltip");if(Ba&&kr)if(Cs)Cs.textContent=kr,Cs.style.display="";else{let R=document.createElement("div");R.className="tvw-send-button-tooltip",R.textContent=kr,at==null||at.insertBefore(R,X)}else Cs&&(Cs.style.display="none");let xs=(Ni=e.statusIndicator)!=null?Ni:{},Fa=(Di=xs.visible)!=null?Di:!0;if(Tt.style.display=Fa?"":"none",M){let R=M.getStatus(),Me=Ze=>{var ve,He,wt,Wt;return Ze==="idle"?(ve=xs.idleText)!=null?ve:Rt.idle:Ze==="connecting"?(He=xs.connectingText)!=null?He:Rt.connecting:Ze==="connected"?(wt=xs.connectedText)!=null?wt:Rt.connected:Ze==="error"?(Wt=xs.errorText)!=null?Wt:Rt.error:Rt[Ze]};Tt.textContent=Me(R)}},open(){y&&nt(!0,"api")},close(){y&&nt(!1,"api")},toggle(){y&&nt(!I,"api")},clearChat(){M.clearMessages();try{localStorage.removeItem(ss),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ss}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==ss)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(f=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",f)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},b.syncFromMetadata(),O==null||O.clear(),Q==null||Q.update()},setMessage(l){return!de||M.isStreaming()?!1:(!I&&y&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(M.isStreaming())return!1;let p=(l==null?void 0:l.trim())||de.value.trim();return p?(!I&&y&&nt(!0,"system"),de.value="",de.style.height="auto",M.sendMessage(p),!0):!1},startVoiceRecognition(){var p,f;return M.isStreaming()?!1:((f=(p=e.voiceRecognition)==null?void 0:p.provider)==null?void 0:f.type)==="runtype"?(M.isVoiceActive()||(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),M.toggleVoice().then(()=>{Ee.active=M.isVoiceActive(),Qt("user"),M.isVoiceActive()&&Tn()})),!0):qt?!0:ps()?(!I&&y&&nt(!0,"system"),Ee.manuallyDeactivated=!1,Ut(),En("user"),!0):!1},stopVoiceRecognition(){var l,p;return((p=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:p.type)==="runtype"?M.isVoiceActive()?(M.toggleVoice().then(()=>{Ee.active=!1,Ee.manuallyDeactivated=!0,Ut(),Qt("user"),Mn()}),!0):!1:qt?(Ee.manuallyDeactivated=!0,Ut(),en("user"),!0):!1},injectMessage(l){return!I&&y&&nt(!0,"system"),M.injectMessage(l)},injectAssistantMessage(l){!I&&y&&nt(!0,"system");let p=M.injectAssistantMessage(l);return T&&(T=!1,B&&(clearTimeout(B),B=null),setTimeout(()=>{M&&!M.isStreaming()&&M.continueConversation()},100)),p},injectUserMessage(l){return!I&&y&&nt(!0,"system"),M.injectUserMessage(l)},injectSystemMessage(l){return!I&&y&&nt(!0,"system"),M.injectSystemMessage(l)},injectMessageBatch(l){return!I&&y&&nt(!0,"system"),M.injectMessageBatch(l)},injectTestMessage(l){!I&&y&&nt(!0,"system"),M.injectTestEvent(l)},async connectStream(l,p){return M.connectStream(l,p)},__pushEventStreamEvent(l){O&&O.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!j||!O||Ke()},hideEventStream(){ue&&ce()},isEventStreamVisible(){return ue},focusInput(){return y&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,p){let A=M.getMessages().find(H=>{var P;return H.variant==="approval"&&((P=H.approval)==null?void 0:P.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return M.resolveApproval(A.approval,p)},getMessages(){return M.getMessages()},getStatus(){return M.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return y&&I},isVoiceActive(){return Ee.active},getState(){return{open:y&&I,launcherEnabled:y,voiceActive:Ee.active,streaming:M.isStreaming()}},showCSATFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=hr({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitCSATFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&y&&nt(!0,"system");let p=Ue.querySelector(".tvw-feedback-container");p&&p.remove();let f=fr({onSubmit:async(A,H)=>{var P;M.isClientTokenMode()&&await M.submitNPSFeedback(A,H),(P=l==null?void 0:l.onSubmit)==null||P.call(l,A,H)},onDismiss:l==null?void 0:l.onDismiss,...l});Ue.appendChild(f),f.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return M.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return M.submitNPSFeedback(l,p)},destroy(){Ye.forEach(l=>l()),Ne.remove(),Xe==null||Xe.destroy(),Ge==null||Ge.remove(),sn&&ee.removeEventListener("click",sn)}};if((((Dt=r==null?void 0:r.debugTools)!=null?Dt:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:It,getMessages:It.getMessages,getStatus:It.getStatus,getMetadata:It.getPersistentMetadata,updateMetadata:It.updatePersistentMetadata,clearHistory:()=>It.clearChat(),setVoiceActive:f=>f?It.startVoiceRecognition():It.stopVoiceRecognition()};window.AgentWidgetBrowser=p,Ye.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),p=f=>{let A=f.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&It.focusInput()};if(window.addEventListener("persona:focusInput",p),Ye.push(()=>{window.removeEventListener("persona:focusInput",p)}),j){let f=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.showEventStream()},A=H=>{let P=H.detail;(!(P!=null&&P.instanceId)||P.instanceId===l)&&It.hideEventStream()};window.addEventListener("persona:showEventStream",f),window.addEventListener("persona:hideEventStream",A),Ye.push(()=>{window.removeEventListener("persona:showEventStream",f),window.removeEventListener("persona:hideEventStream",A)})}}let $t=Hl(e.persistState);if($t&&y){let l=Bl($t.storage),p=`${$t.keyPrefix}widget-open`,f=`${$t.keyPrefix}widget-voice`,A=`${$t.keyPrefix}widget-voice-mode`;if(l){let H=((Xt=$t.persist)==null?void 0:Xt.openState)&&l.getItem(p)==="true",P=((Qr=$t.persist)==null?void 0:Qr.voiceState)&&l.getItem(f)==="true",q=((eo=$t.persist)==null?void 0:eo.voiceState)&&l.getItem(A)==="true";if(H&&setTimeout(()=>{It.open(),setTimeout(()=>{var ge;if(P||q)It.startVoiceRecognition();else if((ge=$t.persist)!=null&&ge.focusInput){let me=n.querySelector("textarea");me&&me.focus()}},100)},0),(to=$t.persist)!=null&&to.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(no=$t.persist)!=null&&no.voiceState&&(s.on("voice:state",ge=>{l.setItem(f,ge.active?"true":"false")}),s.on("user:message",ge=>{l.setItem(A,ge.viaVoice?"true":"false")})),$t.clearOnChatClear){let ge=()=>{l.removeItem(p),l.removeItem(f),l.removeItem(A)},me=()=>ge();window.addEventListener("persona:clear-chat",me),Ye.push(()=>{window.removeEventListener("persona:clear-chat",me)})}}}return It};var Xr={},Fl=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},$l=()=>{try{if(typeof Xr!="undefined"&&Xr.url)return new URL("../widget.css",Xr.url).href}catch{}return null},Ma=n=>{let t=$l(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-persona","true"),n.insertBefore(e,n.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&t){let o=document.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},Gr=n=>{var c,v,d,m;let t=Fl(n.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),t.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),Ma(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Ma(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=wr(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let u={...a,host:r,destroy(){a.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=u),u};var ka={name:"@runtypelabs/persona",version:"1.47.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var On=ka.version;function hn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function Nl(n){if(n)return{getHeaders:hn(n.getHeaders),onFeedback:hn(n.onFeedback),onCopy:hn(n.onCopy),requestMiddleware:hn(n.requestMiddleware),actionHandlers:hn(n.actionHandlers),actionParsers:hn(n.actionParsers),postprocessMessage:hn(n.postprocessMessage),contextProviders:hn(n.contextProviders),streamParser:hn(n.streamParser)}}var Ia=`({ text, message }: any) => {
60
+ `}if(!E){let Kn="max-height: -moz-available !important; max-height: stretch !important;",Yn=l?"":"padding-top: 1.25em !important;";je.style.cssText+=Kn+Yn}};Qt(),cr(n,e);let Ze=[];_&&Ze.push(()=>{Fe!==null&&(cancelAnimationFrame(Fe),Fe=null),ee==null||ee.destroy(),ee=null,N==null||N.destroy(),N=null,G=null});let en=null,vn=()=>{en&&(en(),en=null),e.colorScheme==="auto"&&(en=fa(()=>{cr(n,e)}))};vn(),Ze.push(()=>{en&&(en(),en=null)});let wn=Ea(Ot),rn=null,T,yn=!1,ln=!0,Sn=0,as=0,cn=null,dn=!1,Dn=0,jn=!1,Rs=125,Hs=2e3,Bs=5,ls=50,_n=new Map,Ae={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},cs=(to=(Zt=e.voiceRecognition)==null?void 0:Zt.autoResume)!=null?to:!1,Xt=l=>{s.emit("voice:state",{active:Ae.active,source:l,timestamp:Date.now()})},Dt=()=>{p(l=>({...l,voiceState:{active:Ae.active,timestamp:Date.now(),manuallyDeactivated:Ae.manuallyDeactivated}}))},Fs=()=>{var S,W;if(((S=e.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=Gr(a.voiceState),u=!!l.active,h=Number((W=l.timestamp)!=null?W:0);Ae.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Nl&&setTimeout(()=>{var M,j;Ae.active||(Ae.manuallyDeactivated=!1,((j=(M=e.voiceRecognition)==null?void 0:M.provider)==null?void 0:j.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("restore"),T.isVoiceActive()&&bn()}):Mn("restore"))},1e3)},$s=()=>T?Pa(T.getMessages()).filter(l=>!l.__skipPersist):[];function ds(l){if(!(i!=null&&i.save))return;let h={messages:l?Pa(l):T?$s():[],metadata:a};try{let S=i.save(h);S instanceof Promise&&S.catch(W=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",W)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let An=(l=!1)=>{if(!ln)return;let u=Date.now();dn&&u<Dn&&!l||(dn&&u>=Dn&&(dn=!1),!(!l&&!yn)&&(u-as<Rs||(as=u,cn&&cancelAnimationFrame(cn),cn=requestAnimationFrame(()=>{dn||!ln||(jn=!0,$e.scrollTop=$e.scrollHeight,Sn=$e.scrollTop,requestAnimationFrame(()=>{jn=!1}),cn=null)}))))},un=null,Ns=()=>je.querySelector("#persona-scroll-container")||$e,Os=(l,u=500)=>{let h=l.scrollTop,S=l.clientHeight,W=l.scrollHeight,M=W-h;if(h+S>=W-2||Math.abs(M)<5)return;un!==null&&(cancelAnimationFrame(un),un=null);let le=performance.now(),de=we=>1-Math.pow(1-we,3),ye=we=>{let Me=l.scrollHeight;Me!==W&&(W=Me,M=W-h);let J=we-le,E=Math.min(J/u,1),ce=de(E),ge=h+M*ce;l.scrollTop=ge,E<1?un=requestAnimationFrame(ye):(l.scrollTop=l.scrollHeight,un=null)};un=requestAnimationFrame(ye)},Ds=l=>{let u=new Map;l.forEach(h=>{let S=_n.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!S&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(S!=null&&S.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(S?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),_n.clear(),u.forEach((h,S)=>{_n.set(S,h)})},En=(l,u,h)=>{var ye,we,Me,J;let S=document.createElement("div"),M=(()=>{var ce;let E=o.find(ge=>ge.renderLoadingIndicator);if(E!=null&&E.renderLoadingIndicator)return E.renderLoadingIndicator;if((ce=e.loadingIndicator)!=null&&ce.render)return e.loadingIndicator.render})();u.forEach(E=>{var Ye,ut;let ce=null,ge=o.find(K=>!!(E.variant==="reasoning"&&K.renderReasoning||E.variant==="tool"&&K.renderToolCall||E.variant==="approval"&&K.renderApproval||!E.variant&&K.renderMessage)),Oe=(Ye=e.layout)==null?void 0:Ye.messages;if(ge)if(E.variant==="reasoning"&&E.reasoning&&ge.renderReasoning){if(!V)return;ce=ge.renderReasoning({message:E,defaultRenderer:()=>jr(E),config:e})}else if(E.variant==="tool"&&E.toolCall&&ge.renderToolCall){if(!X)return;ce=ge.renderToolCall({message:E,defaultRenderer:()=>_r(E,e),config:e})}else if(E.variant==="approval"&&E.approval&&ge.renderApproval){if(e.approval===!1)return;ce=ge.renderApproval({message:E,defaultRenderer:()=>Ur(E,e),config:e})}else ge.renderMessage&&(ce=ge.renderMessage({message:E,defaultRenderer:()=>{let K=es(E,h,Oe,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e});return E.role!=="user"&&Vr(K,E,e,T),K},config:e}));if(!ce&&E.role==="assistant"&&!E.variant&&e.enableComponentStreaming!==!1&&mr(E)){let Ue=fr(E);if(Ue){let on=hr(Ue,{config:e,message:E,transform:h});if(on){let _t=document.createElement("div");if(_t.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(" "),_t.id=`bubble-${E.id}`,_t.setAttribute("data-message-id",E.id),E.content&&E.content.trim()){let nn=document.createElement("div");nn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",nn.innerHTML=h({text:E.content,message:E,streaming:!!E.streaming,raw:E.rawContent}),_t.appendChild(nn)}_t.appendChild(on),ce=_t}}}if(!ce)if(E.variant==="reasoning"&&E.reasoning){if(!V)return;ce=jr(E)}else if(E.variant==="tool"&&E.toolCall){if(!X)return;ce=_r(E,e)}else if(E.variant==="approval"&&E.approval){if(e.approval===!1)return;ce=Ur(E,e)}else{let K=(ut=e.layout)==null?void 0:ut.messages;K!=null&&K.renderUserMessage&&E.role==="user"?ce=K.renderUserMessage({message:E,config:e,streaming:!!E.streaming}):K!=null&&K.renderAssistantMessage&&E.role==="assistant"?ce=K.renderAssistantMessage({message:E,config:e,streaming:!!E.streaming}):ce=es(E,h,K,e.messageActions,gt,{loadingIndicatorRenderer:M,widgetConfig:e}),E.role!=="user"&&ce&&Vr(ce,E,e,T)}let me=document.createElement("div");me.className="tvw-flex",me.id=`wrapper-${E.id}`,me.setAttribute("data-wrapper-id",E.id),E.role==="user"&&me.classList.add("tvw-justify-end"),me.appendChild(ce),S.appendChild(me)});let j=u.some(E=>E.role==="assistant"&&E.streaming),le=u[u.length-1],de=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(yn&&u.some(E=>E.role==="user")&&!j&&!de){let E={config:e,streaming:!0,location:"standalone",defaultRenderer:$n},ce=o.find(Oe=>Oe.renderLoadingIndicator),ge=null;if(ce!=null&&ce.renderLoadingIndicator&&(ge=ce.renderLoadingIndicator(E)),ge===null&&((ye=e.loadingIndicator)!=null&&ye.render)&&(ge=e.loadingIndicator.render(E)),ge===null&&(ge=$n()),ge){let Oe=document.createElement("div"),me=((we=e.loadingIndicator)==null?void 0:we.showBubble)!==!1;Oe.className=me?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),Oe.setAttribute("data-typing-indicator","true"),Oe.appendChild(ge);let Ye=document.createElement("div");Ye.className="tvw-flex",Ye.id="wrapper-typing-indicator",Ye.setAttribute("data-wrapper-id","typing-indicator"),Ye.appendChild(Oe),S.appendChild(Ye)}}if(!yn&&u.length>0){let E=u[u.length-1],ce={config:e,lastMessage:E,messageCount:u.length},ge=o.find(me=>me.renderIdleIndicator),Oe=null;if(ge!=null&&ge.renderIdleIndicator&&(Oe=ge.renderIdleIndicator(ce)),Oe===null&&((Me=e.loadingIndicator)!=null&&Me.renderIdle)&&(Oe=e.loadingIndicator.renderIdle(ce)),Oe){let me=document.createElement("div"),Ye=((J=e.loadingIndicator)==null?void 0:J.showBubble)!==!1;me.className=Ye?["tvw-max-w-[85%]","tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-px-5","tvw-py-3"].join(" "):["tvw-max-w-[85%]","tvw-text-sm","tvw-leading-relaxed","tvw-text-cw-primary"].join(" "),me.setAttribute("data-idle-indicator","true"),me.appendChild(Oe);let ut=document.createElement("div");ut.className="tvw-flex",ut.id="wrapper-idle-indicator",ut.setAttribute("data-wrapper-id","idle-indicator"),ut.appendChild(me),S.appendChild(ut)}}wa(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let E=Ns();Os(E)})})},Tn=()=>{y&&(P?(je.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-95","tvw-opacity-0"),ne.classList.add("tvw-scale-100","tvw-opacity-100"),Qe?Qe.element.style.display="none":et&&(et.style.display="none")):(je.classList.add("tvw-pointer-events-none","tvw-opacity-0"),ne.classList.remove("tvw-scale-100","tvw-opacity-100"),ne.classList.add("tvw-scale-95","tvw-opacity-0"),Qe?Qe.element.style.display="":et&&(et.style.display="")))},ot=(l,u="user")=>{if(!y||P===l)return;let h=P;P=l,Tn(),P&&(Cn(),An(!0));let S={open:P,source:u,timestamp:Date.now()};P&&!h?s.emit("widget:opened",S):!P&&h&&s.emit("widget:closed",S),s.emit("widget:state",{open:P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()})},Un=l=>{Z.disabled=l,I&&(I.disabled=l),wn.buttons.forEach(u=>{u.disabled=l})},qn=()=>{Ae.active||he&&he.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>qn(),200)});let us=()=>{var W,M,j,le,de,ye,we,Me,J,E,ce,ge,Oe,me;Ct.textContent=(M=(W=e.copy)==null?void 0:W.welcomeTitle)!=null?M:"Hello \u{1F44B}",Kt.textContent=(le=(j=e.copy)==null?void 0:j.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",he.placeholder=(ye=(de=e.copy)==null?void 0:de.inputPlaceholder)!=null?ye:"How can I help...",(Me=(we=e.sendButton)==null?void 0:we.useIcon)!=null&&Me||(Z.textContent=(E=(J=e.copy)==null?void 0:J.sendButtonLabel)!=null?E:"Send");let u=(ge=(ce=e.theme)==null?void 0:ce.inputFontFamily)!=null?ge:"sans-serif",h=(me=(Oe=e.theme)==null?void 0:Oe.inputFontWeight)!=null?me:"400",S=Ye=>{switch(Ye){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};he.style.fontFamily=S(u),he.style.fontWeight=h};if(e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),T=new Gn(e,{onMessagesChanged(l){En(ze,l,z),T&&(l.some(W=>W.role==="user")?wn.render([],T,he,l):wn.render(e.suggestionChips,T,he,l,e.suggestionChipsConfig)),An(!yn),Ds(l);let u=[...l].reverse().find(S=>S.role==="user"),h=Ae.lastUserMessageId;u&&u.id!==h&&(Ae.lastUserMessageId=u.id,s.emit("user:message",u)),Ae.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),ds(l)},onStatusChanged(l){var S;let u=(S=e.statusIndicator)!=null?S:{},h=W=>{var M,j,le,de;return W==="idle"?(M=u.idleText)!=null?M:Rt.idle:W==="connecting"?(j=u.connectingText)!=null?j:Rt.connecting:W==="connected"?(le=u.connectedText)!=null?le:Rt.connected:W==="error"?(de=u.errorText)!=null?de:Rt.error:Rt[W]};kt.textContent=h(l)},onStreamingChanged(l){yn=l,Un(l),T&&En(ze,T.getMessages(),z),l||An(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":Gt(),_s();break;case"speaking":Gt(),Us();break;default:l==="idle"&&T.isBargeInActive()?(Gt(),bn(),I==null||I.setAttribute("aria-label","End voice session")):(Ae.active=!1,Gt(),Xt("system"),Dt());break}}}),((so=(no=e.voiceRecognition)==null?void 0:no.provider)==null?void 0:so.type)==="runtype")try{T.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}e.clientToken&&T.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),N&&T.setSSEEventCallback((l,u)=>{N==null||N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(a=Gr(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&T.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let ps=l=>{var W;l.preventDefault();let u=he.value.trim(),h=(W=oe==null?void 0:oe.hasAttachments())!=null?W:!1;if(!u&&!h)return;let S;h&&(S=[],S.push(...oe.getContentParts()),u&&S.push(sr(u))),he.value="",he.style.height="auto",T.sendMessage(u,{contentParts:S}),h&&oe.clearAttachments()},gs=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Z.click())},hs=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!oe)return;let u=Dl(l.clipboardData);u.length!==0&&(l.preventDefault(),await oe.handleFiles(u))},Ft=null,Vt=!1,pn=null,ke=null,ms=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Mn=(l="user")=>{var M,j,le,de,ye,we,Me,J;if(Vt||T.isStreaming())return;let u=ms();if(!u)return;Ft=new u;let S=(j=((M=e.voiceRecognition)!=null?M:{}).pauseDuration)!=null?j:2e3;Ft.continuous=!0,Ft.interimResults=!0,Ft.lang="en-US";let W=he.value;Ft.onresult=E=>{let ce="",ge="";for(let me=0;me<E.results.length;me++){let Ye=E.results[me],ut=Ye[0].transcript;Ye.isFinal?ce+=ut+" ":ge=ut}let Oe=W+ce+ge;he.value=Oe,pn&&clearTimeout(pn),(ce||ge)&&(pn=window.setTimeout(()=>{let me=he.value.trim();me&&Ft&&Vt&&(tn(),he.value="",he.style.height="auto",T.sendMessage(me,{viaVoice:!0}))},S))},Ft.onerror=E=>{E.error!=="no-speech"&&tn()},Ft.onend=()=>{if(Vt){let E=he.value.trim();E&&E!==W.trim()&&(he.value="",he.style.height="auto",T.sendMessage(E,{viaVoice:!0})),tn()}};try{if(Ft.start(),Vt=!0,Ae.active=!0,l!=="system"&&(Ae.manuallyDeactivated=!1),Xt(l),Dt(),I){let E=(le=e.voiceRecognition)!=null?le:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(de=E.iconName)!=null?de:"mic",iconSize:parseFloat((Me=(we=E.iconSize)!=null?we:(ye=e.sendButton)==null?void 0:ye.size)!=null?Me:"40")||24};let ce=(J=E.recordingBackgroundColor)!=null?J:"#ef4444",ge=E.recordingIconColor,Oe=E.recordingBorderColor;if(I.classList.add("tvw-voice-recording"),I.style.backgroundColor=ce,ge){I.style.color=ge;let me=I.querySelector("svg");me&&me.setAttribute("stroke",ge)}Oe&&(I.style.borderColor=Oe),I.setAttribute("aria-label","Stop voice recognition")}}catch{tn("system")}},tn=(l="user")=>{if(Vt){if(Vt=!1,pn&&(clearTimeout(pn),pn=null),Ft){try{Ft.stop()}catch{}Ft=null}Ae.active=!1,Xt(l),Dt(),I&&Gt()}},js=(l,u)=>{var me,Ye,ut,K,Ue,on,_t,nn;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((me=l==null?void 0:l.provider)==null?void 0:me.type)==="runtype";if(!(h||S))return null;let M=g("div","tvw-send-button-wrapper"),j=g("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 le=(Ye=l==null?void 0:l.iconName)!=null?Ye:"mic",de=(ut=u==null?void 0:u.size)!=null?ut:"40px",ye=(K=l==null?void 0:l.iconSize)!=null?K:de,we=parseFloat(ye)||24,Me=(Ue=l==null?void 0:l.backgroundColor)!=null?Ue:u==null?void 0:u.backgroundColor,J=(on=l==null?void 0:l.iconColor)!=null?on:u==null?void 0:u.textColor;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 E=J||"currentColor",ce=ie(le,we,E,1.5);ce?(j.appendChild(ce),j.style.color=E):(j.textContent="\u{1F3A4}",j.style.color=E),Me?j.style.backgroundColor=Me:j.classList.add("tvw-bg-cw-primary"),J?j.style.color=J:!J&&!(u!=null&&u.textColor)&&j.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(j.style.borderWidth=l.borderWidth,j.style.borderStyle="solid"),l!=null&&l.borderColor&&(j.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(j.style.paddingLeft=l.paddingX,j.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(j.style.paddingTop=l.paddingY,j.style.paddingBottom=l.paddingY),M.appendChild(j);let ge=(_t=l==null?void 0:l.tooltipText)!=null?_t:"Start voice recognition";if(((nn=l==null?void 0:l.showTooltip)!=null?nn:!1)&&ge){let In=g("div","tvw-send-button-tooltip");In.textContent=ge,M.appendChild(In)}return{micButton:j,micButtonWrapper:M}},Vn=()=>{var u,h,S,W,M;if(!I||ke)return;let l=(u=e.voiceRecognition)!=null?u:{};ke={backgroundColor:I.style.backgroundColor,color:I.style.color,borderColor:I.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat((M=(W=l.iconSize)!=null?W:(S=e.sendButton)==null?void 0:S.size)!=null?M:"40")||24}},zn=(l,u)=>{var M,j,le,de,ye;if(!I)return;let h=I.querySelector("svg");h&&h.remove();let S=(ye=ke==null?void 0:ke.iconSize)!=null?ye:parseFloat((de=(le=(M=e.voiceRecognition)==null?void 0:M.iconSize)!=null?le:(j=e.sendButton)==null?void 0:j.size)!=null?de:"40")||24,W=ie(l,S,u,1.5);W&&I.appendChild(W)},kn=()=>{I&&I.classList.remove("tvw-voice-recording","tvw-voice-processing","tvw-voice-speaking")},bn=()=>{var W,M;if(!I)return;Vn();let l=(W=e.voiceRecognition)!=null?W:{},u=(M=l.recordingBackgroundColor)!=null?M:"#ef4444",h=l.recordingIconColor,S=l.recordingBorderColor;if(kn(),I.classList.add("tvw-voice-recording"),I.style.backgroundColor=u,h){I.style.color=h;let j=I.querySelector("svg");j&&j.setAttribute("stroke",h)}S&&(I.style.borderColor=S),I.setAttribute("aria-label","Stop voice recognition")},_s=()=>{var le,de,ye,we,Me,J,E,ce;if(!I)return;Vn();let l=(le=e.voiceRecognition)!=null?le:{},u=T.getVoiceInterruptionMode(),h=(de=l.processingIconName)!=null?de:"loader",S=(we=(ye=l.processingIconColor)!=null?ye:ke==null?void 0:ke.color)!=null?we:"",W=(J=(Me=l.processingBackgroundColor)!=null?Me:ke==null?void 0:ke.backgroundColor)!=null?J:"",M=(ce=(E=l.processingBorderColor)!=null?E:ke==null?void 0:ke.borderColor)!=null?ce:"";kn(),I.classList.add("tvw-voice-processing"),I.style.backgroundColor=W,I.style.borderColor=M;let j=S||"currentColor";I.style.color=j,zn(h,j),I.setAttribute("aria-label","Processing voice input"),u==="none"&&(I.style.cursor="default")},Us=()=>{var ye,we,Me,J,E,ce,ge,Oe,me,Ye,ut,K;if(!I)return;Vn();let l=(ye=e.voiceRecognition)!=null?ye:{},u=T.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(we=l.speakingIconName)!=null?we:h,W=(ce=l.speakingIconColor)!=null?ce:u==="barge-in"?(J=(Me=l.recordingIconColor)!=null?Me:ke==null?void 0:ke.color)!=null?J:"":(E=ke==null?void 0:ke.color)!=null?E:"",M=(me=l.speakingBackgroundColor)!=null?me:u==="barge-in"?(ge=l.recordingBackgroundColor)!=null?ge:"#ef4444":(Oe=ke==null?void 0:ke.backgroundColor)!=null?Oe:"",j=(K=l.speakingBorderColor)!=null?K:u==="barge-in"?(Ye=l.recordingBorderColor)!=null?Ye:"":(ut=ke==null?void 0:ke.borderColor)!=null?ut:"";kn(),I.classList.add("tvw-voice-speaking"),I.style.backgroundColor=M,I.style.borderColor=j;let le=W||"currentColor";I.style.color=le,zn(S,le);let de=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";I.setAttribute("aria-label",de),u==="none"&&(I.style.cursor="default"),u==="barge-in"&&I.classList.add("tvw-voice-recording")},Gt=()=>{var l,u,h;I&&(kn(),ke&&(I.style.backgroundColor=(l=ke.backgroundColor)!=null?l:"",I.style.color=(u=ke.color)!=null?u:"",I.style.borderColor=(h=ke.borderColor)!=null?h:"",zn(ke.iconName,ke.color||"currentColor"),ke=null),I.style.cursor="",I.setAttribute("aria-label","Start voice recognition"))},Jn=()=>{var l,u;if(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=T.getVoiceStatus(),S=T.getVoiceInterruptionMode();if(S==="none"&&(h==="processing"||h==="speaking"))return;if(S==="cancel"&&(h==="processing"||h==="speaking")){T.stopVoicePlayback();return}if(T.isBargeInActive()){T.stopVoicePlayback(),T.deactivateBargeIn().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()});return}T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Ae.manuallyDeactivated=!T.isVoiceActive(),Dt(),Xt("user"),T.isVoiceActive()?bn():Gt()});return}if(Vt){let h=he.value.trim();Ae.manuallyDeactivated=!0,Dt(),tn("user"),h&&(he.value="",he.style.height="auto",T.sendMessage(h))}else Ae.manuallyDeactivated=!1,Dt(),Mn("user")};I&&(I.addEventListener("click",Jn),Ze.push(()=>{var l,u;((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(T.isVoiceActive()&&T.toggleVoice(),Gt()):tn("system"),I&&I.removeEventListener("click",Jn)}));let qs=s.on("assistant:complete",()=>{cs&&(Ae.active||Ae.manuallyDeactivated||cs==="assistant"&&!Ae.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!Ae.active&&!Ae.manuallyDeactivated&&(((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("auto"),T.isVoiceActive()&&bn()}):Mn("auto"))},600))});Ze.push(qs);let Vs=s.on("action:resubmit",()=>{setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)});Ze.push(Vs);let gn=()=>{ot(!P,"user")},Qe=null,et=null;if(y){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:e,defaultRenderer:()=>Ms(e,gn).element,onToggle:gn});u&&(et=u)}et||(Qe=Ms(e,gn))}Qe?n.appendChild(Qe.element):et&&n.appendChild(et),Tn(),wn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),us(),Un(T.isStreaming()),An(!0),Fs(),x&&(y?P&&setTimeout(()=>qn(),200):setTimeout(()=>qn(),0));let Cn=()=>{var h,S,W,M,j,le,de,ye;let l=(S=(h=e.launcher)==null?void 0:h.sidebarMode)!=null?S:!1,u=l||((M=(W=e.launcher)==null?void 0:W.fullHeight)!=null?M:!1);if(!y){ne.style.height="",ne.style.width="";return}if(!l){let we=(le=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?le:e==null?void 0:e.launcherWidth,Me=we!=null?we:"min(400px, calc(100vw - 24px))";ne.style.width=Me,ne.style.maxWidth=Me}if(!u){let we=window.innerHeight,Me=64,J=(ye=(de=e.launcher)==null?void 0:de.heightOffset)!=null?ye:0,E=Math.max(200,we-Me),ce=Math.min(640,E),ge=Math.max(200,ce-J);ne.style.height=`${ge}px`}};Cn(),window.addEventListener("resize",Cn),Ze.push(()=>window.removeEventListener("resize",Cn)),Sn=$e.scrollTop;let fs=()=>{let l=$e.scrollTop,u=$e.scrollHeight,h=$e.clientHeight,S=u-l-h,W=Math.abs(l-Sn);if(Sn=l,!jn&&!(W<=Bs)){if(!ln&&S<ls){dn=!1,ln=!0;return}ln&&S>ls&&(dn=!0,Dn=Date.now()+Hs,ln=!1)}};$e.addEventListener("scroll",fs,{passive:!0}),Ze.push(()=>$e.removeEventListener("scroll",fs)),Ze.push(()=>{cn&&cancelAnimationFrame(cn)});let vs=()=>{te&&(rn&&(te.removeEventListener("click",rn),rn=null),y?(te.style.display="",rn=()=>{P=!1,Tn()},te.addEventListener("click",rn)):te.style.display="none")};vs(),(()=>{let{clearChatButton:l}=xe;l&&l.addEventListener("click",()=>{T.clearMessages();try{localStorage.removeItem(is),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()})})(),bt.addEventListener("submit",ps),he.addEventListener("keydown",gs),he.addEventListener("paste",hs),Ze.push(()=>{bt.removeEventListener("submit",ps),he.removeEventListener("keydown",gs),he.removeEventListener("paste",hs)}),Ze.push(()=>{T.cancel()}),Qe?Ze.push(()=>{Qe==null||Qe.destroy()}):et&&Ze.push(()=>{et==null||et.remove()});let Lt={update(l){var po,go,ho,mo,fo,vo,wo,yo,bo,Co,xo,So,Ao,Eo,To,Mo,ko,Io,Lo,Wo,Po,Ro,Ho,Bo,Fo,$o,No,Oo,Do,jo,_o,Uo,qo,Vo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ei,ti,ni,si,ri,oi,ii,ai,li,ci,di,ui,pi,gi,hi,mi,fi,vi,wi,yi,bi,Ci,xi,Si,Ai,Ei,Ti,Mi,ki,Ii,Li,Wi,Pi,Ri,Hi,Bi,Fi,$i,Ni,Oi,Di,ji,_i,Ui,qi,Vi,zi,Ji;let u=e.toolCall,h=e.colorScheme;e={...e,...l},Qt(),cr(n,e),e.colorScheme!==h&&vn();let S=Ls.getForInstance(e.plugins);o.length=0,o.push(...S),y=(go=(po=e.launcher)==null?void 0:po.enabled)!=null?go:!0,A=(mo=(ho=e.launcher)==null?void 0:ho.autoExpand)!=null?mo:!1,V=(vo=(fo=e.features)==null?void 0:fo.showReasoning)!=null?vo:!0,X=(yo=(wo=e.features)==null?void 0:wo.showToolCalls)!=null?yo:!0;let W=_;if(_=(Co=(bo=e.features)==null?void 0:bo.showEventStreamToggle)!=null?Co:!1,_&&!W){if(N||(G=new Is(se),N=new ks(U,G),G.open().then(()=>N==null?void 0:N.restore()).catch(()=>{}),T.setSSEEventCallback((B,Ie)=>{N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:B,timestamp:Date.now(),payload:JSON.stringify(Ie)})})),!D&&Se){let B=(So=(xo=e.features)==null?void 0:xo.eventStream)==null?void 0:So.classNames,Ie="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(B!=null&&B.toggleButton?" "+B.toggleButton:"");D=g("button",Ie),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let tt=ie("activity","18px","currentColor",1.5);tt&&D.appendChild(tt);let be=xe.clearChatButtonWrapper,Be=xe.closeButtonWrapper,yt=be||Be;yt&&yt.parentNode===Se?Se.insertBefore(D,yt):Se.appendChild(D),D.addEventListener("click",()=>{fe?pe():Ge()})}}else!_&&W&&(pe(),D&&(D.remove(),D=null),N==null||N.clear(),G==null||G.destroy(),N=null,G=null);if(((Ao=e.launcher)==null?void 0:Ao.enabled)===!1&&Qe&&(Qe.destroy(),Qe=null),((Eo=e.launcher)==null?void 0:Eo.enabled)===!1&&et&&(et.remove(),et=null),((To=e.launcher)==null?void 0:To.enabled)!==!1&&!Qe&&!et){let B=o.find(Ie=>Ie.renderLauncher);if(B!=null&&B.renderLauncher){let Ie=B.renderLauncher({config:e,defaultRenderer:()=>Ms(e,gn).element,onToggle:gn});Ie&&(et=Ie,n.appendChild(et))}et||(Qe=Ms(e,gn),n.appendChild(Qe.element))}Qe&&Qe.update(e),xt&&((Mo=e.launcher)==null?void 0:Mo.title)!==void 0&&(xt.textContent=e.launcher.title),ve&&((ko=e.launcher)==null?void 0:ko.subtitle)!==void 0&&(ve.textContent=e.launcher.subtitle);let M=(Io=e.layout)==null?void 0:Io.header;if((M==null?void 0:M.layout)!==k&&Se){let B=M?Zn(e,M,{showClose:y,onClose:()=>ot(!1,"user")}):mn({config:e,showClose:y,onClose:()=>ot(!1,"user")});Se.replaceWith(B.header),Se=B.header,Pe=B.iconHolder,xt=B.headerTitle,ve=B.headerSubtitle,te=B.closeButton,k=M==null?void 0:M.layout}else if(M&&(Pe&&(Pe.style.display=M.showIcon===!1?"none":""),xt&&(xt.style.display=M.showTitle===!1?"none":""),ve&&(ve.style.display=M.showSubtitle===!1?"none":""),te&&(te.style.display=M.showCloseButton===!1?"none":""),xe.clearChatButtonWrapper)){let B=M.showClearChat;if(B!==void 0){xe.clearChatButtonWrapper.style.display=B?"":"none";let{closeButtonWrapper:Ie}=xe;Ie&&!Ie.classList.contains("tvw-absolute")&&(B?Ie.classList.remove("tvw-ml-auto"):Ie.classList.add("tvw-ml-auto"))}}let le=((Lo=e.layout)==null?void 0:Lo.showHeader)!==!1;Se&&(Se.style.display=le?"":"none");let de=((Wo=e.layout)==null?void 0:Wo.showFooter)!==!1;Je&&(Je.style.display=de?"":"none"),y!==Y?y?ot(A,"auto"):(P=!0,Tn()):A!==H&&ot(A,"auto"),H=A,Y=y,Cn(),vs(),JSON.stringify(l.toolCall)!==JSON.stringify(u)&&T&&En(ze,T.getMessages(),z);let J=(Po=e.launcher)!=null?Po:{},E=(Ro=J.headerIconHidden)!=null?Ro:!1,ce=(Bo=(Ho=e.layout)==null?void 0:Ho.header)==null?void 0:Bo.showIcon,ge=E||ce===!1,Oe=J.headerIconName,me=(Fo=J.headerIconSize)!=null?Fo:"48px";if(Pe){let B=He.querySelector(".tvw-border-b-cw-divider"),Ie=B==null?void 0:B.querySelector(".tvw-flex-col");if(ge)Pe.style.display="none",B&&Ie&&!B.contains(Ie)&&B.insertBefore(Ie,B.firstChild);else{if(Pe.style.display="",Pe.style.height=me,Pe.style.width=me,B&&Ie&&(B.contains(Pe)?Pe.nextSibling!==Ie&&(Pe.remove(),B.insertBefore(Pe,Ie)):B.insertBefore(Pe,Ie)),Oe){let be=parseFloat(me)||24,Be=ie(Oe,be*.6,"#ffffff",2);Be?Pe.replaceChildren(Be):Pe.textContent=($o=J.agentIconText)!=null?$o:"\u{1F4AC}"}else if(J.iconUrl){let be=Pe.querySelector("img");if(be)be.src=J.iconUrl,be.style.height=me,be.style.width=me;else{let Be=document.createElement("img");Be.src=J.iconUrl,Be.alt="",Be.className="tvw-rounded-xl tvw-object-cover",Be.style.height=me,Be.style.width=me,Pe.replaceChildren(Be)}}else{let be=Pe.querySelector("svg"),Be=Pe.querySelector("img");(be||Be)&&Pe.replaceChildren(),Pe.textContent=(No=J.agentIconText)!=null?No:"\u{1F4AC}"}let tt=Pe.querySelector("img");tt&&(tt.style.height=me,tt.style.width=me)}}let Ye=(Do=(Oo=e.layout)==null?void 0:Oo.header)==null?void 0:Do.showTitle,ut=(_o=(jo=e.layout)==null?void 0:jo.header)==null?void 0:_o.showSubtitle;if(xt&&(xt.style.display=Ye===!1?"none":""),ve&&(ve.style.display=ut===!1?"none":""),te){((qo=(Uo=e.layout)==null?void 0:Uo.header)==null?void 0:qo.showCloseButton)===!1?te.style.display="none":te.style.display="";let Ie=(Vo=J.closeButtonSize)!=null?Vo:"32px",tt=(zo=J.closeButtonPlacement)!=null?zo:"inline";te.style.height=Ie,te.style.width=Ie;let{closeButtonWrapper:be}=xe,Be=tt==="top-right",yt=be==null?void 0:be.classList.contains("tvw-absolute");if(be&&Be!==yt)if(be.remove(),Be)be.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",He.style.position="relative",He.appendChild(be);else{let Le=(Ko=(Jo=J.clearChat)==null?void 0:Jo.placement)!=null?Ko:"inline",Et=(Xo=(Yo=J.clearChat)==null?void 0:Yo.enabled)!=null?Xo:!0;be.className=Et&&Le==="inline"?"":"tvw-ml-auto";let Ut=He.querySelector(".tvw-border-b-cw-divider");Ut&&Ut.appendChild(be)}if(J.closeButtonColor?(te.style.color=J.closeButtonColor,te.classList.remove("tvw-text-cw-muted")):(te.style.color="",te.classList.add("tvw-text-cw-muted")),J.closeButtonBackgroundColor?(te.style.backgroundColor=J.closeButtonBackgroundColor,te.classList.remove("hover:tvw-bg-gray-100")):(te.style.backgroundColor="",te.classList.add("hover:tvw-bg-gray-100")),J.closeButtonBorderWidth||J.closeButtonBorderColor){let Le=J.closeButtonBorderWidth||"0px",Et=J.closeButtonBorderColor||"transparent";te.style.border=`${Le} solid ${Et}`,te.classList.remove("tvw-border-none")}else te.style.border="",te.classList.add("tvw-border-none");J.closeButtonBorderRadius?(te.style.borderRadius=J.closeButtonBorderRadius,te.classList.remove("tvw-rounded-full")):(te.style.borderRadius="",te.classList.add("tvw-rounded-full")),J.closeButtonPaddingX?(te.style.paddingLeft=J.closeButtonPaddingX,te.style.paddingRight=J.closeButtonPaddingX):(te.style.paddingLeft="",te.style.paddingRight=""),J.closeButtonPaddingY?(te.style.paddingTop=J.closeButtonPaddingY,te.style.paddingBottom=J.closeButtonPaddingY):(te.style.paddingTop="",te.style.paddingBottom="");let Pt=(Go=J.closeButtonIconName)!=null?Go:"x",zt=(Zo=J.closeButtonIconText)!=null?Zo:"\xD7";te.innerHTML="";let Nt=ie(Pt,"20px",J.closeButtonColor||"",2);Nt?te.appendChild(Nt):te.textContent=zt;let pt=(Qo=J.closeButtonTooltipText)!=null?Qo:"Close chat",Jt=(ei=J.closeButtonShowTooltip)!=null?ei:!0;if(te.setAttribute("aria-label",pt),be&&(be._cleanupTooltip&&(be._cleanupTooltip(),delete be._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!te)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let Cs=g("div");Cs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Cs);let Ln=te.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Ln.left+Ln.width/2}px`,Le.style.top=`${Ln.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};be.addEventListener("mouseenter",Et),be.addEventListener("mouseleave",Ut),te.addEventListener("focus",Et),te.addEventListener("blur",Ut),be._cleanupTooltip=()=>{Ut(),be&&(be.removeEventListener("mouseenter",Et),be.removeEventListener("mouseleave",Ut)),te&&(te.removeEventListener("focus",Et),te.removeEventListener("blur",Ut))}}}let{clearChatButton:K,clearChatButtonWrapper:Ue}=xe;if(K){let B=(ti=J.clearChat)!=null?ti:{},Ie=(ni=B.enabled)!=null?ni:!0,tt=(ri=(si=e.layout)==null?void 0:si.header)==null?void 0:ri.showClearChat,be=tt!==void 0?tt:Ie,Be=(oi=B.placement)!=null?oi:"inline";if(Ue){Ue.style.display=be?"":"none";let{closeButtonWrapper:yt}=xe;yt&&!yt.classList.contains("tvw-absolute")&&(be?yt.classList.remove("tvw-ml-auto"):yt.classList.add("tvw-ml-auto"));let Pt=Be==="top-right",zt=Ue.classList.contains("tvw-absolute");if(Pt!==zt&&be){if(Ue.remove(),Pt)Ue.className="tvw-absolute tvw-top-4 tvw-z-50",Ue.style.right="48px",He.style.position="relative",He.appendChild(Ue);else{Ue.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",Ue.style.right="";let pt=He.querySelector(".tvw-border-b-cw-divider"),Jt=xe.closeButtonWrapper;pt&&Jt&&Jt.parentElement===pt?pt.insertBefore(Ue,Jt):pt&&pt.appendChild(Ue)}let Nt=xe.closeButtonWrapper;Nt&&!Nt.classList.contains("tvw-absolute")&&(Pt?Nt.classList.add("tvw-ml-auto"):Nt.classList.remove("tvw-ml-auto"))}}if(be){let yt=(ii=B.size)!=null?ii:"32px";K.style.height=yt,K.style.width=yt;let Pt=(ai=B.iconName)!=null?ai:"refresh-cw",zt=(li=B.iconColor)!=null?li:"";K.innerHTML="";let Nt=ie(Pt,"20px",zt||"",2);if(Nt&&K.appendChild(Nt),zt?(K.style.color=zt,K.classList.remove("tvw-text-cw-muted")):(K.style.color="",K.classList.add("tvw-text-cw-muted")),B.backgroundColor?(K.style.backgroundColor=B.backgroundColor,K.classList.remove("hover:tvw-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:tvw-bg-gray-100")),B.borderWidth||B.borderColor){let Le=B.borderWidth||"0px",Et=B.borderColor||"transparent";K.style.border=`${Le} solid ${Et}`,K.classList.remove("tvw-border-none")}else K.style.border="",K.classList.add("tvw-border-none");B.borderRadius?(K.style.borderRadius=B.borderRadius,K.classList.remove("tvw-rounded-full")):(K.style.borderRadius="",K.classList.add("tvw-rounded-full")),B.paddingX?(K.style.paddingLeft=B.paddingX,K.style.paddingRight=B.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),B.paddingY?(K.style.paddingTop=B.paddingY,K.style.paddingBottom=B.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let pt=(ci=B.tooltipText)!=null?ci:"Clear chat",Jt=(di=B.showTooltip)!=null?di:!0;if(K.setAttribute("aria-label",pt),Ue&&(Ue._cleanupTooltip&&(Ue._cleanupTooltip(),delete Ue._cleanupTooltip),Jt&&pt)){let Le=null,Et=()=>{if(Le||!K)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=pt;let Cs=g("div");Cs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(Cs);let Ln=K.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Ln.left+Ln.width/2}px`,Le.style.top=`${Ln.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ut=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};Ue.addEventListener("mouseenter",Et),Ue.addEventListener("mouseleave",Ut),K.addEventListener("focus",Et),K.addEventListener("blur",Ut),Ue._cleanupTooltip=()=>{Ut(),Ue&&(Ue.removeEventListener("mouseenter",Et),Ue.removeEventListener("mouseleave",Ut)),K&&(K.removeEventListener("focus",Et),K.removeEventListener("blur",Ut))}}}}let on=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ws],_t=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Nn.message,Nn.messageAndClick];C=Ps({parsers:on,handlers:_t,getSessionMetadata:v,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),z=Ra(e,C,ue),T.updateConfig(e),En(ze,T.getMessages(),z),wn.render(e.suggestionChips,T,he,void 0,e.suggestionChipsConfig),us(),Un(T.isStreaming());let nn=((ui=e.voiceRecognition)==null?void 0:ui.enabled)===!0,In=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),zs=((gi=(pi=e.voiceRecognition)==null?void 0:pi.provider)==null?void 0:gi.type)==="runtype";if(nn&&(In||zs))if(!I||!nt){let B=js(e.voiceRecognition,e.sendButton);B&&(I=B.micButton,nt=B.micButtonWrapper,qt.insertBefore(nt,ct),I.addEventListener("click",Jn),I.disabled=T.isStreaming())}else{let B=(hi=e.voiceRecognition)!=null?hi:{},Ie=(mi=e.sendButton)!=null?mi:{},tt=(fi=B.iconName)!=null?fi:"mic",be=(vi=Ie.size)!=null?vi:"40px",Be=(wi=B.iconSize)!=null?wi:be,yt=parseFloat(Be)||24;I.style.width=Be,I.style.height=Be,I.style.minWidth=Be,I.style.minHeight=Be;let Pt=(bi=(yi=B.iconColor)!=null?yi:Ie.textColor)!=null?bi:"currentColor";I.innerHTML="";let zt=ie(tt,yt,Pt,2);zt?I.appendChild(zt):I.textContent="\u{1F3A4}";let Nt=(Ci=B.backgroundColor)!=null?Ci:Ie.backgroundColor;Nt?(I.style.backgroundColor=Nt,I.classList.remove("tvw-bg-cw-primary")):(I.style.backgroundColor="",I.classList.add("tvw-bg-cw-primary")),Pt?(I.style.color=Pt,I.classList.remove("tvw-text-white")):!Pt&&!Ie.textColor&&(I.style.color="",I.classList.add("tvw-text-white")),B.borderWidth?(I.style.borderWidth=B.borderWidth,I.style.borderStyle="solid"):(I.style.borderWidth="",I.style.borderStyle=""),B.borderColor?I.style.borderColor=B.borderColor:I.style.borderColor="",B.paddingX?(I.style.paddingLeft=B.paddingX,I.style.paddingRight=B.paddingX):(I.style.paddingLeft="",I.style.paddingRight=""),B.paddingY?(I.style.paddingTop=B.paddingY,I.style.paddingBottom=B.paddingY):(I.style.paddingTop="",I.style.paddingBottom="");let pt=nt==null?void 0:nt.querySelector(".tvw-send-button-tooltip"),Jt=(xi=B.tooltipText)!=null?xi:"Start voice recognition";if(((Si=B.showTooltip)!=null?Si:!1)&&Jt)if(pt)pt.textContent=Jt,pt.style.display="";else{let Et=document.createElement("div");Et.className="tvw-send-button-tooltip",Et.textContent=Jt,nt==null||nt.insertBefore(Et,I)}else pt&&(pt.style.display="none");nt.style.display="",I.disabled=T.isStreaming()}else I&&nt&&(nt.style.display="none",((Ei=(Ai=e.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype"?T.isVoiceActive()&&T.toggleVoice():Vt&&tn());if(((Ti=e.attachments)==null?void 0:Ti.enabled)===!0)if(!Q||!O){let B=(Mi=e.attachments)!=null?Mi:{},tt=(Ii=((ki=e.sendButton)!=null?ki:{}).size)!=null?Ii:"40px";Ne||(Ne=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),Ne.style.display="none",bt.insertBefore(Ne,he)),re||(re=document.createElement("input"),re.type="file",re.accept=((Li=B.allowedTypes)!=null?Li:xn).join(","),re.multiple=((Wi=B.maxFiles)!=null?Wi:4)>1,re.style.display="none",re.setAttribute("aria-label","Attach files"),bt.insertBefore(re,he)),Q=g("div","tvw-send-button-wrapper"),O=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),O.type="button",O.setAttribute("aria-label",(Pi=B.buttonTooltipText)!=null?Pi:"Attach file");let be=(Ri=B.buttonIconName)!=null?Ri:"paperclip",Be=tt,yt=parseFloat(Be)||40,Pt=Math.round(yt*.6);O.style.width=Be,O.style.height=Be,O.style.minWidth=Be,O.style.minHeight=Be,O.style.fontSize="18px",O.style.lineHeight="1",O.style.backgroundColor="transparent",O.style.color="var(--cw-primary, #111827)",O.style.border="none",O.style.borderRadius="6px",O.style.transition="background-color 0.15s ease",O.addEventListener("mouseenter",()=>{O.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),O.addEventListener("mouseleave",()=>{O.style.backgroundColor="transparent"});let zt=ie(be,Pt,"currentColor",1.5);zt?O.appendChild(zt):O.textContent="\u{1F4CE}",O.addEventListener("click",Jt=>{Jt.preventDefault(),re==null||re.click()}),Q.appendChild(O);let Nt=(Hi=B.buttonTooltipText)!=null?Hi:"Attach file",pt=g("div","tvw-send-button-tooltip");pt.textContent=Nt,Q.appendChild(pt),It.append(Q),!oe&&re&&Ne&&(oe=Bn.fromConfig(B),oe.setPreviewsContainer(Ne),re.addEventListener("change",async()=>{oe&&(re!=null&&re.files)&&(await oe.handleFileSelect(re.files),re.value="")}))}else{Q.style.display="";let B=(Bi=e.attachments)!=null?Bi:{};re&&(re.accept=((Fi=B.allowedTypes)!=null?Fi:xn).join(","),re.multiple=(($i=B.maxFiles)!=null?$i:4)>1),oe&&oe.updateConfig({allowedTypes:B.allowedTypes,maxFileSize:B.maxFileSize,maxFiles:B.maxFiles})}else Q&&(Q.style.display="none"),oe&&oe.clearAttachments();let mt=(Ni=e.sendButton)!=null?Ni:{},Kn=(Oi=mt.useIcon)!=null?Oi:!1,Yn=(Di=mt.iconText)!=null?Di:"\u2191",uo=mt.iconName,Lr=(ji=mt.tooltipText)!=null?ji:"Send message",_a=(_i=mt.showTooltip)!=null?_i:!1,ws=(Ui=mt.size)!=null?Ui:"40px",Js=mt.backgroundColor,an=mt.textColor;if(Kn){if(Z.style.width=ws,Z.style.height=ws,Z.style.minWidth=ws,Z.style.minHeight=ws,Z.style.fontSize="18px",Z.style.lineHeight="1",Z.innerHTML="",uo){let B=parseFloat(ws)||24,Ie=an&&typeof an=="string"&&an.trim()?an.trim():"currentColor",tt=ie(uo,B,Ie,2);tt?(Z.appendChild(tt),Z.style.color=Ie):(Z.textContent=Yn,an?Z.style.color=an:Z.classList.add("tvw-text-white"))}else Z.textContent=Yn,an?Z.style.color=an:Z.classList.add("tvw-text-white");Z.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Js?(Z.style.backgroundColor=Js,Z.classList.remove("tvw-bg-cw-primary")):Z.classList.add("tvw-bg-cw-primary")}else Z.textContent=(Vi=(qi=e.copy)==null?void 0:qi.sendButtonLabel)!=null?Vi:"Send",Z.style.width="",Z.style.height="",Z.style.minWidth="",Z.style.minHeight="",Z.style.fontSize="",Z.style.lineHeight="",Z.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",Js?(Z.style.backgroundColor=Js,Z.classList.remove("tvw-bg-cw-accent")):Z.classList.add("tvw-bg-cw-accent"),an?Z.style.color=an:Z.classList.add("tvw-text-white");mt.borderWidth?(Z.style.borderWidth=mt.borderWidth,Z.style.borderStyle="solid"):(Z.style.borderWidth="",Z.style.borderStyle=""),mt.borderColor?Z.style.borderColor=mt.borderColor:Z.style.borderColor="",mt.paddingX?(Z.style.paddingLeft=mt.paddingX,Z.style.paddingRight=mt.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),mt.paddingY?(Z.style.paddingTop=mt.paddingY,Z.style.paddingBottom=mt.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let ys=ct==null?void 0:ct.querySelector(".tvw-send-button-tooltip");if(_a&&Lr)if(ys)ys.textContent=Lr,ys.style.display="";else{let B=document.createElement("div");B.className="tvw-send-button-tooltip",B.textContent=Lr,ct==null||ct.insertBefore(B,Z)}else ys&&(ys.style.display="none");let bs=(zi=e.statusIndicator)!=null?zi:{},Ua=(Ji=bs.visible)!=null?Ji:!0;if(kt.style.display=Ua?"":"none",T){let B=T.getStatus(),Ie=tt=>{var be,Be,yt,Pt;return tt==="idle"?(be=bs.idleText)!=null?be:Rt.idle:tt==="connecting"?(Be=bs.connectingText)!=null?Be:Rt.connecting:tt==="connected"?(yt=bs.connectedText)!=null?yt:Rt.connected:tt==="error"?(Pt=bs.errorText)!=null?Pt:Rt.error:Rt[tt]};kt.textContent=Ie(B)}},open(){y&&ot(!0,"api")},close(){y&&ot(!1,"api")},toggle(){y&&ot(!P,"api")},clearChat(){T.clearMessages();try{localStorage.removeItem(is),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${is}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==is)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let u=i.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}a={},C.syncFromMetadata(),N==null||N.clear(),ee==null||ee.update()},setMessage(l){return!he||T.isStreaming()?!1:(!P&&y&&ot(!0,"system"),he.value=l,he.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(T.isStreaming())return!1;let u=(l==null?void 0:l.trim())||he.value.trim();return u?(!P&&y&&ot(!0,"system"),he.value="",he.style.height="auto",T.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return T.isStreaming()?!1:((h=(u=e.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(T.isVoiceActive()||(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),T.toggleVoice().then(()=>{Ae.active=T.isVoiceActive(),Xt("user"),T.isVoiceActive()&&bn()})),!0):Vt?!0:ms()?(!P&&y&&ot(!0,"system"),Ae.manuallyDeactivated=!1,Dt(),Mn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=e.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?T.isVoiceActive()?(T.toggleVoice().then(()=>{Ae.active=!1,Ae.manuallyDeactivated=!0,Dt(),Xt("user"),Gt()}),!0):!1:Vt?(Ae.manuallyDeactivated=!0,Dt(),tn("user"),!0):!1},injectMessage(l){return!P&&y&&ot(!0,"system"),T.injectMessage(l)},injectAssistantMessage(l){!P&&y&&ot(!0,"system");let u=T.injectAssistantMessage(l);return L&&(L=!1,F&&(clearTimeout(F),F=null),setTimeout(()=>{T&&!T.isStreaming()&&T.continueConversation()},100)),u},injectUserMessage(l){return!P&&y&&ot(!0,"system"),T.injectUserMessage(l)},injectSystemMessage(l){return!P&&y&&ot(!0,"system"),T.injectSystemMessage(l)},injectMessageBatch(l){return!P&&y&&ot(!0,"system"),T.injectMessageBatch(l)},injectTestMessage(l){!P&&y&&ot(!0,"system"),T.injectTestEvent(l)},async connectStream(l,u){return T.connectStream(l,u)},__pushEventStreamEvent(l){N&&N.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!_||!N||Ge()},hideEventStream(){fe&&pe()},isEventStreamVisible(){return fe},focusInput(){return y&&!P||!he?!1:(he.focus(),!0)},async resolveApproval(l,u){let S=T.getMessages().find(W=>{var M;return W.variant==="approval"&&((M=W.approval)==null?void 0:M.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return T.resolveApproval(S.approval,u)},getMessages(){return T.getMessages()},getStatus(){return T.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return y&&P},isVoiceActive(){return Ae.active},getState(){return{open:y&&P,launcherEnabled:y,voiceActive:Ae.active,streaming:T.isStreaming()}},showCSATFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=vr({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitCSATFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!P&&y&&ot(!0,"system");let u=ze.querySelector(".tvw-feedback-container");u&&u.remove();let h=wr({onSubmit:async(S,W)=>{var M;T.isClientTokenMode()&&await T.submitNPSFeedback(S,W),(M=l==null?void 0:l.onSubmit)==null||M.call(l,S,W)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return T.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return T.submitNPSFeedback(l,u)},destroy(){Ze.forEach(l=>l()),je.remove(),Qe==null||Qe.destroy(),et==null||et.remove(),rn&&te.removeEventListener("click",rn)}};if((((ro=r==null?void 0:r.debugTools)!=null?ro:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:h=>h?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=u,Ze.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=n.getAttribute("data-persona-instance")||n.id||"persona-"+Math.random().toString(36).slice(2,8),u=h=>{let S=h.detail;(!(S!=null&&S.instanceId)||S.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",u),Ze.push(()=>{window.removeEventListener("persona:focusInput",u)}),_){let h=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.showEventStream()},S=W=>{let M=W.detail;(!(M!=null&&M.instanceId)||M.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",h),window.addEventListener("persona:hideEventStream",S),Ze.push(()=>{window.removeEventListener("persona:showEventStream",h),window.removeEventListener("persona:hideEventStream",S)})}}let $t=jl(e.persistState);if($t&&y){let l=_l($t.storage),u=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,S=`${$t.keyPrefix}widget-voice-mode`;if(l){let W=((oo=$t.persist)==null?void 0:oo.openState)&&l.getItem(u)==="true",M=((io=$t.persist)==null?void 0:io.voiceState)&&l.getItem(h)==="true",j=((ao=$t.persist)==null?void 0:ao.voiceState)&&l.getItem(S)==="true";if(W&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(M||j)Lt.startVoiceRecognition();else if((le=$t.persist)!=null&&le.focusInput){let de=n.querySelector("textarea");de&&de.focus()}},100)},0),(lo=$t.persist)!=null&&lo.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(co=$t.persist)!=null&&co.voiceState&&(s.on("voice:state",le=>{l.setItem(h,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(S,le.viaVoice?"true":"false")})),$t.clearOnChatClear){let le=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(S)},de=()=>le();window.addEventListener("persona:clear-chat",de),Ze.push(()=>{window.removeEventListener("persona:clear-chat",de)})}}}return Lt};var Zr={},Ul=n=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof n=="string"){let t=document.querySelector(n);if(!t)throw new Error(`Chat widget target "${n}" was not found`);return t}return n},ql=()=>{try{if(typeof Zr!="undefined"&&Zr.url)return new URL("../widget.css",Zr.url).href}catch{}return null},Ha=n=>{let t=ql(),r=()=>{if(!(n instanceof ShadowRoot)||n.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);n.insertBefore(o,n.firstChild)};if(n instanceof ShadowRoot)if(t){let e=document.createElement("link");e.rel="stylesheet",e.href=t,e.setAttribute("data-persona","true"),n.insertBefore(e,n.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&t){let o=document.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},Qr=n=>{var c,v,p,m;let t=Ul(n.target),r=document.createElement("div");r.className="persona-host";let e=(p=(v=(c=n.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?p:!0;e||(r.style.height="100%"),t.appendChild(r);let o=n.useShadowDom===!0,s,i;if(o){let w=r.attachShadow({mode:"open"});i=w,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),w.appendChild(s),Ha(w)}else i=r,s=document.createElement("div"),s.id="persona-root",e||(s.style.height="100%",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1",s.style.minHeight="0"),r.appendChild(s),Ha(r);t.id&&s.setAttribute("data-persona-instance",t.id);let a=yr(s,n.config,{debugTools:n.debugTools});(m=n.onReady)==null||m.call(n);let d={...a,host:r,destroy(){a.destroy(),r.remove(),n.windowKey&&typeof window!="undefined"&&delete window[n.windowKey]}};return n.windowKey&&typeof window!="undefined"&&(window[n.windowKey]=d),d};var Ba={name:"@runtypelabs/persona",version:"1.48.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var On=Ba.version;function fn(n){if(n!==void 0)return typeof n=="string"?n:Array.isArray(n)?`[${n.map(t=>t.toString()).join(", ")}]`:n.toString()}function zl(n){if(n)return{getHeaders:fn(n.getHeaders),onFeedback:fn(n.onFeedback),onCopy:fn(n.onCopy),requestMiddleware:fn(n.requestMiddleware),actionHandlers:fn(n.actionHandlers),actionParsers:fn(n.actionParsers),postprocessMessage:fn(n.postprocessMessage),contextProviders:fn(n.contextProviders),streamParser:fn(n.streamParser)}}var Fa=`({ text, message }: any) => {
61
61
  const jsonSource = (message as any).rawContent || text || message.content;
62
62
  if (!jsonSource || typeof jsonSource !== 'string') return null;
63
63
  let cleanJson = jsonSource
@@ -70,7 +70,7 @@
70
70
  if (parsed.action) return { type: parsed.action, payload: parsed };
71
71
  } catch (e) { return null; }
72
72
  return null;
73
- }`,La=`function(ctx) {
73
+ }`,$a=`function(ctx) {
74
74
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
75
75
  if (!jsonSource || typeof jsonSource !== 'string') return null;
76
76
  var cleanJson = jsonSource
@@ -83,7 +83,7 @@
83
83
  if (parsed.action) return { type: parsed.action, payload: parsed };
84
84
  } catch (e) { return null; }
85
85
  return null;
86
- }`,Wa=`(action: any, context: any) => {
86
+ }`,Na=`(action: any, context: any) => {
87
87
  if (action.type !== 'nav_then_click') return;
88
88
  const payload = action.payload || action.raw || {};
89
89
  const url = payload?.page;
@@ -100,7 +100,7 @@
100
100
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
101
101
  window.location.href = targetUrl;
102
102
  return { handled: true, displayText: text };
103
- }`,Pa=`function(action, context) {
103
+ }`,Oa=`function(action, context) {
104
104
  if (action.type !== 'nav_then_click') return;
105
105
  var payload = action.payload || action.raw || {};
106
106
  var url = payload.page;
@@ -117,24 +117,24 @@
117
117
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
118
118
  window.location.href = targetUrl;
119
119
  return { handled: true, displayText: text };
120
- }`,Dl=`(parsed: any) => {
120
+ }`,Jl=`(parsed: any) => {
121
121
  if (!parsed || typeof parsed !== 'object') return null;
122
122
  if (parsed.action === 'nav_then_click') return 'Navigating...';
123
123
  if (parsed.action === 'message') return parsed.text || '';
124
124
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
125
125
  return parsed.text || null;
126
- }`,jl=`function(parsed) {
126
+ }`,Kl=`function(parsed) {
127
127
  if (!parsed || typeof parsed !== 'object') return null;
128
128
  if (parsed.action === 'nav_then_click') return 'Navigating...';
129
129
  if (parsed.action === 'message') return parsed.text || '';
130
130
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
131
131
  return parsed.text || null;
132
- }`;function _l(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function vr(n){var t,r;return(r=(t=n.parserType)!=null?t:_l(n.streamParser))!=null?r:"plain"}function yr(n,t){let r=[];return n.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${t} ${e}: "${o}",`)}),r.push(`${t}},`)),r}function br(n,t,r){let e=[],o=n.messageActions&&Object.entries(n.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(e.push(`${t}messageActions: {`),n.messageActions&&Object.entries(n.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${t} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${t} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${t} onCopy: ${r.onCopy},`),e.push(`${t}},`)),e}function Cr(n,t){let r=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,o=n.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${t}markdown: {`),e&&(r.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function xr(n,t){let r=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),o=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${t}layout: {`),e&&(r.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${t} avatar: {`),Object.entries(i).forEach(([a,u])=>{typeof u=="string"?r.push(`${t} ${a}: "${u}",`):typeof u=="boolean"&&r.push(`${t} ${a}: ${u},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([u])=>u!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?r.push(`${t} ${u}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${u}: ${c},`))}),r.push(`${t} },`)):typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function Zr(n,t){let r=[];return n&&(n.getHeaders&&r.push(`${t}getHeaders: ${n.getHeaders},`),n.requestMiddleware&&r.push(`${t}requestMiddleware: ${n.requestMiddleware},`),n.actionParsers&&r.push(`${t}actionParsers: ${n.actionParsers},`),n.actionHandlers&&r.push(`${t}actionHandlers: ${n.actionHandlers},`),n.contextProviders&&r.push(`${t}contextProviders: ${n.contextProviders},`),n.streamParser&&r.push(`${t}streamParser: ${n.streamParser},`)),r}function Ra(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Nl(r.hooks)}:void 0;return t==="esm"?Vl(e,o):t==="script-installer"?zl(e):t==="script-advanced"?Kl(e,o):t==="react-component"?Ul(e,o):t==="react-advanced"?ql(e,o):Jl(e,o)}function Vl(n,t){let r=t==null?void 0:t.hooks,e=vr(n),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...yr(n," ")),s.push(...br(n," ",r)),s.push(...Cr(n," ")),s.push(...xr(n," ")),s.push(...Zr(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function Ul(n,t){let r=t==null?void 0:t.hooks,e=vr(n),o=e!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...yr(n," ")),s.push(...br(n," ",r)),s.push(...Cr(n," ")),s.push(...xr(n," ")),s.push(...Zr(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
- `)}function ql(n,t){let r=t==null?void 0:t.hooks,e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&e.push(` clientToken: "${n.clientToken}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...yr(n," ")),e.push(...br(n," ",r)),e.push(...Cr(n," ")),e.push(...xr(n," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Dl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${Ia}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${Ia}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${Wa}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${Wa}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
135
- `)}function Ha(n){var o;let t=vr(n),r=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.clientToken&&(e.clientToken=n.clientToken),n.flowId&&(e.flowId=n.flowId),r&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((o=n.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.layout.header).forEach(([a,u])=>{a!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.header=i)}if(n.layout.messages){let i={};Object.entries(n.layout.messages).forEach(([a,u])=>{if(a!=="renderUserMessage"&&a!=="renderAssistantMessage")if(a==="avatar"&&typeof u=="object"&&u!==null)i.avatar=u;else if(a==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([v,d])=>{v!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[v]=d)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(i[a]=u)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function zl(n){let t=Ha(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/install.global.js" data-config='${r}'></script>`}function Jl(n,t){let r=t==null?void 0:t.hooks,e=vr(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...yr(n," ")),s.push(...br(n," ",r)),s.push(...Cr(n," ")),s.push(...xr(n," ")),s.push(...Zr(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
- `)}function Kl(n,t){let r=t==null?void 0:t.hooks,e=Ha(n),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,null,2).split(`
132
+ }`;function Yl(n){if(!n)return null;let t=n.toString();return t.includes("createJsonStreamParser")||t.includes("partial-json")?"json":t.includes("createRegexJsonParser")||t.includes("regex")?"regex-json":t.includes("createXmlParser")||t.includes("<text>")?"xml":null}function br(n){var t,r;return(r=(t=n.parserType)!=null?t:Yl(n.streamParser))!=null?r:"plain"}function Cr(n,t){let r=[];return n.toolCall&&(r.push(`${t}toolCall: {`),Object.entries(n.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${t} ${e}: "${o}",`)}),r.push(`${t}},`)),r}function xr(n,t,r){let e=[],o=n.messageActions&&Object.entries(n.messageActions).some(([i,a])=>i!=="onFeedback"&&i!=="onCopy"&&a!==void 0),s=(r==null?void 0:r.onFeedback)||(r==null?void 0:r.onCopy);return(o||s)&&(e.push(`${t}messageActions: {`),n.messageActions&&Object.entries(n.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${t} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${t} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${t} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${t} onCopy: ${r.onCopy},`),e.push(`${t}},`)),e}function Sr(n,t){let r=[];if(n.markdown){let e=n.markdown.options&&Object.keys(n.markdown.options).length>0,o=n.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${t}markdown: {`),e&&(r.push(`${t} options: {`),Object.entries(n.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`)}),r.push(`${t} },`)),o&&r.push(`${t} disableDefaultStyles: ${n.markdown.disableDefaultStyles},`),r.push(`${t}},`))}return r}function Ar(n,t){let r=[];if(n.layout){let e=n.layout.header&&Object.keys(n.layout.header).some(s=>s!=="render"),o=n.layout.messages&&Object.keys(n.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${t}layout: {`),e&&(r.push(`${t} header: {`),Object.entries(n.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),o&&(r.push(`${t} messages: {`),Object.entries(n.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${t} avatar: {`),Object.entries(i).forEach(([a,d])=>{typeof d=="string"?r.push(`${t} ${a}: "${d}",`):typeof d=="boolean"&&r.push(`${t} ${a}: ${d},`)}),r.push(`${t} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([d])=>d!=="format")&&(r.push(`${t} timestamp: {`),Object.entries(i).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?r.push(`${t} ${d}: "${c}",`):typeof c=="boolean"&&r.push(`${t} ${d}: ${c},`))}),r.push(`${t} },`)):typeof i=="string"?r.push(`${t} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${t} ${s}: ${i},`))}),r.push(`${t} },`)),r.push(`${t}},`))}return r}function eo(n,t){let r=[];return n&&(n.getHeaders&&r.push(`${t}getHeaders: ${n.getHeaders},`),n.requestMiddleware&&r.push(`${t}requestMiddleware: ${n.requestMiddleware},`),n.actionParsers&&r.push(`${t}actionParsers: ${n.actionParsers},`),n.actionHandlers&&r.push(`${t}actionHandlers: ${n.actionHandlers},`),n.contextProviders&&r.push(`${t}contextProviders: ${n.contextProviders},`),n.streamParser&&r.push(`${t}streamParser: ${n.streamParser},`)),r}function Da(n,t="esm",r){let e={...n};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:zl(r.hooks)}:void 0;return t==="esm"?Xl(e,o):t==="script-installer"?Ql(e):t==="script-advanced"?tc(e,o):t==="react-component"?Gl(e,o):t==="react-advanced"?Zl(e,o):ec(e,o)}function Xl(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
+ `)}function Gl(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push(""),s.push(" // Cleanup on unmount"),s.push(" return () => {"),s.push(" if (handle) {"),s.push(" handle.destroy();"),s.push(" }"),s.push(" };"),s.push(" }, []);"),s.push(""),s.push(" return null; // Widget injects itself into the DOM"),s.push("}"),s.push(""),s.push("// Usage in your app:"),s.push("// import { ChatWidget } from './components/ChatWidget';"),s.push("//"),s.push("// export default function App() {"),s.push("// return ("),s.push("// <div>"),s.push("// {/* Your app content */}"),s.push("// <ChatWidget />"),s.push("// </div>"),s.push("// );"),s.push("// }"),s.join(`
134
+ `)}function Zl(n,t){let r=t==null?void 0:t.hooks,e=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&e.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&e.push(` clientToken: "${n.clientToken}",`),n.flowId&&e.push(` flowId: "${n.flowId}",`),n.theme&&(e.push(" theme: {"),Object.entries(n.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.launcher&&(e.push(" launcher: {"),Object.entries(n.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.copy&&(e.push(" copy: {"),Object.entries(n.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),n.sendButton&&(e.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(n.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"?e.push(` ${o}: ${s},`):typeof s=="number"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),n.features&&(e.push(" features: {"),Object.entries(n.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(e.push(" suggestionChips: ["),n.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),n.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...Cr(n," ")),e.push(...xr(n," ",r)),e.push(...Sr(n," ")),e.push(...Ar(n," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),n.debug&&e.push(` debug: ${n.debug},`),e.push(" initialMessages: loadSavedMessages(),"),r!=null&&r.streamParser?e.push(` streamParser: ${r.streamParser},`):(e.push(" // Flexible JSON stream parser for handling structured actions"),e.push(` streamParser: () => createFlexibleJsonStreamParser(${Jl}),`)),r!=null&&r.actionParsers?(e.push(" // Action parsers (custom merged with defaults)"),e.push(` actionParsers: [...(${r.actionParsers}), defaultJsonActionParser,`),e.push(" // Built-in parser for markdown-wrapped JSON"),e.push(` ${Fa}`),e.push(" ],")):(e.push(" // Action parsers to detect JSON actions in responses"),e.push(" actionParsers: ["),e.push(" defaultJsonActionParser,"),e.push(" // Parser for markdown-wrapped JSON"),e.push(` ${Fa}`),e.push(" ],")),r!=null&&r.actionHandlers?(e.push(" // Action handlers (custom merged with defaults)"),e.push(` actionHandlers: [...(${r.actionHandlers}),`),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Built-in handler for nav_then_click action"),e.push(` ${Na}`),e.push(" ],")):(e.push(" // Action handlers for navigation and other actions"),e.push(" actionHandlers: ["),e.push(" defaultActionHandlers.message,"),e.push(" defaultActionHandlers.messageAndClick,"),e.push(" // Handler for nav_then_click action"),e.push(` ${Na}`),e.push(" ],")),r!=null&&r.postprocessMessage?e.push(` postprocessMessage: ${r.postprocessMessage},`):e.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),r!=null&&r.requestMiddleware?(e.push(" // Request middleware (custom merged with DOM context)"),e.push(" requestMiddleware: ({ payload, config }) => {"),e.push(` const customResult = (${r.requestMiddleware})({ payload, config });`),e.push(" const merged = customResult || payload;"),e.push(" return {"),e.push(" ...merged,"),e.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),e.push(" };"),e.push(" }")):(e.push(" requestMiddleware: ({ payload }) => {"),e.push(" return {"),e.push(" ...payload,"),e.push(" metadata: collectDOMContext()"),e.push(" };"),e.push(" }")),e.push(" }"),e.push(" });"),e.push(""),e.push(" // Save state on message events"),e.push(" const handleMessage = () => {"),e.push(" const session = handle?.getSession?.();"),e.push(" if (session) {"),e.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),e.push(" messages: session.messages,"),e.push(" timestamp: new Date().toISOString()"),e.push(" }));"),e.push(" }"),e.push(" };"),e.push(""),e.push(" // Clear state on clear chat"),e.push(" const handleClearChat = () => {"),e.push(" localStorage.removeItem(STORAGE_KEY);"),e.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),e.push(" };"),e.push(""),e.push(" window.addEventListener('persona:message', handleMessage);"),e.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),e.push(""),e.push(" // Cleanup on unmount"),e.push(" return () => {"),e.push(" window.removeEventListener('persona:message', handleMessage);"),e.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),e.push(" if (handle) {"),e.push(" handle.destroy();"),e.push(" }"),e.push(" };"),e.push(" }, []);"),e.push(""),e.push(" return null; // Widget injects itself into the DOM"),e.push("}"),e.push(""),e.push("// Usage: Collects DOM context for AI-powered navigation"),e.push("// Features:"),e.push("// - Extracts page elements (products, buttons, links)"),e.push("// - Persists chat history across page loads"),e.push("// - Handles navigation actions (nav_then_click)"),e.push("// - Processes structured JSON actions from AI"),e.push("//"),e.push("// Example usage in Next.js:"),e.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),e.push("//"),e.push("// export default function RootLayout({ children }) {"),e.push("// return ("),e.push('// <html lang="en">'),e.push("// <body>"),e.push("// {children}"),e.push("// <ChatWidgetAdvanced />"),e.push("// </body>"),e.push("// </html>"),e.push("// );"),e.push("// }"),e.join(`
135
+ `)}function ja(n){var o;let t=br(n),r=t!=="plain",e={};if(n.apiUrl&&(e.apiUrl=n.apiUrl),n.clientToken&&(e.clientToken=n.clientToken),n.flowId&&(e.flowId=n.flowId),r&&(e.parserType=t),n.theme&&(e.theme=n.theme),n.launcher&&(e.launcher=n.launcher),n.copy&&(e.copy=n.copy),n.sendButton&&(e.sendButton=n.sendButton),n.voiceRecognition&&(e.voiceRecognition=n.voiceRecognition),n.statusIndicator&&(e.statusIndicator=n.statusIndicator),n.features&&(e.features=n.features),((o=n.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=n.suggestionChips),n.suggestionChipsConfig&&(e.suggestionChipsConfig=n.suggestionChipsConfig),n.debug&&(e.debug=n.debug),n.toolCall){let s={};Object.entries(n.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(n.messageActions){let s={};Object.entries(n.messageActions).forEach(([i,a])=>{i!=="onFeedback"&&i!=="onCopy"&&a!==void 0&&(typeof a=="string"||typeof a=="boolean")&&(s[i]=a)}),Object.keys(s).length>0&&(e.messageActions=s)}if(n.markdown){let s={};n.markdown.options&&(s.options=n.markdown.options),n.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=n.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(n.layout){let s={};if(n.layout.header){let i={};Object.entries(n.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(n.layout.messages){let i={};Object.entries(n.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 c={};Object.entries(d).forEach(([v,p])=>{v!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[v]=p)}),Object.keys(c).length>0&&(i.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(i[a]=d)}),Object.keys(i).length>0&&(s.messages=i)}Object.keys(s).length>0&&(e.layout=s)}return e}function Ql(n){let t=ja(n),r=JSON.stringify(t,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/install.global.js" data-config='${r}'></script>`}function ec(n,t){let r=t==null?void 0:t.hooks,e=br(n),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return n.apiUrl&&s.push(` apiUrl: "${n.apiUrl}",`),n.clientToken&&s.push(` clientToken: "${n.clientToken}",`),n.flowId&&s.push(` flowId: "${n.flowId}",`),o&&s.push(` parserType: "${e}",`),n.theme&&(s.push(" theme: {"),Object.entries(n.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.launcher&&(s.push(" launcher: {"),Object.entries(n.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.copy&&(s.push(" copy: {"),Object.entries(n.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),n.sendButton&&(s.push(" sendButton: {"),Object.entries(n.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(n.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(" },")),n.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(n.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),n.features&&(s.push(" features: {"),Object.entries(n.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),n.suggestionChips&&n.suggestionChips.length>0&&(s.push(" suggestionChips: ["),n.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),n.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),n.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${n.suggestionChipsConfig.fontFamily}",`),n.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${n.suggestionChipsConfig.fontWeight}",`),n.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${n.suggestionChipsConfig.paddingX}",`),n.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${n.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Cr(n," ")),s.push(...xr(n," ",r)),s.push(...Sr(n," ")),s.push(...Ar(n," ")),s.push(...eo(r," ")),n.debug&&s.push(` debug: ${n.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
136
+ `)}function tc(n,t){let r=t==null?void 0:t.hooks,e=ja(n),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(e,null,2).split(`
137
137
  `).map((i,a)=>a===0?i:" "+i).join(`
138
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${jl});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${La}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${La}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Pa}`),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(` ${Pa}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
- `)}var Yl=Gr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createVoiceProvider,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
138
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${On}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return r!=null&&r.getHeaders&&(s.push(` widgetConfig.getHeaders = ${r.getHeaders};`),s.push("")),r!=null&&r.contextProviders&&(s.push(` widgetConfig.contextProviders = ${r.contextProviders};`),s.push("")),r!=null&&r.streamParser?s.push(` widgetConfig.streamParser = ${r.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${Kl});`),s.push(" };")),s.push(""),r!=null&&r.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${r.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$a}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${$a}`),s.push(" ];")),s.push(""),r!=null&&r.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${r.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${Oa}`),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(` ${Oa}`),s.push(" ];")),s.push(""),r!=null&&r.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${r.requestMiddleware})(ctx);`),s.push(" var merged = customResult || ctx.payload;"),s.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),s.push(" };")):(s.push(" // Send DOM context with each request"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),s.push(" };")),s.push(""),r!=null&&r.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${r.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(r!=null&&r.onFeedback||r!=null&&r.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),r!=null&&r.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${r.onFeedback};`),r!=null&&r.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${r.onCopy};`),s.push("")),s.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,"," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),s.join(`
139
+ `)}var nc=Qr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createVoiceProvider,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
140
140
  //# sourceMappingURL=index.cjs.map