@runtypelabs/persona 1.46.1 → 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 Ca=Object.create;var zs=Object.defineProperty;var Sa=Object.getOwnPropertyDescriptor;var Aa=Object.getOwnPropertyNames;var Ea=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var Ma=(t,n)=>{for(var r in n)zs(t,r,{get:n[r],enumerable:!0})},Ti=(t,n,r,e)=>{if(n&&typeof n=="object"||typeof n=="function")for(let o of Aa(n))!Ta.call(t,o)&&o!==r&&zs(t,o,{get:()=>n[o],enumerable:!(e=Sa(n,o))||e.enumerable});return t};var La=(t,n,r)=>(r=t!=null?Ca(Ea(t)):{},Ti(n||!t||!t.__esModule?zs(r,"default",{value:t,enumerable:!0}):r,t)),Ia=t=>Ti(zs({},"__esModule",{value:!0}),t);var Rl={};Ma(Rl,{AgentWidgetClient:()=>Mn,AgentWidgetSession:()=>_n,AttachmentManager:()=>In,DEFAULT_DARK_THEME:()=>Dr,DEFAULT_LIGHT_THEME:()=>Nr,DEFAULT_WIDGET_CONFIG:()=>tt,VERSION:()=>Hn,attachHeaderToContainer:()=>kn,buildComposer:()=>qn,buildDefaultHeader:()=>Mr,buildExpandedHeader:()=>Ir,buildHeader:()=>cn,buildHeaderWithLayout:()=>jn,buildMinimalHeader:()=>Lr,componentRegistry:()=>Yn,createActionManager:()=>ks,createAgentExperience:()=>gr,createBubbleWithLayout:()=>ea,createCSATFeedback:()=>ur,createComponentMiddleware:()=>da,createComponentStreamParser:()=>ar,createDirectivePostprocessor:()=>Wi,createFlexibleJsonStreamParser:()=>Ri,createImagePart:()=>_i,createJsonStreamParser:()=>Gs,createLocalStorageAdapter:()=>ir,createMarkdownProcessor:()=>Cs,createMarkdownProcessorFromConfig:()=>Ss,createMessageActions:()=>Pr,createNPSFeedback:()=>pr,createPlainTextParser:()=>Vs,createRegexJsonParser:()=>Xs,createStandardBubble:()=>Un,createTextPart:()=>er,createTypingIndicator:()=>Wn,createXmlParser:()=>Qs,default:()=>Bl,defaultActionHandlers:()=>Pn,defaultJsonActionParser:()=>Is,directivePostprocessor:()=>Pi,escapeHtml:()=>Js,extractComponentDirectiveFromMessage:()=>cr,fileToImagePart:()=>ji,generateAssistantMessageId:()=>Ln,generateCodeSnippet:()=>va,generateMessageId:()=>Fi,generateUserMessageId:()=>Dn,getDisplayText:()=>Oi,getHeaderLayout:()=>kr,getImageParts:()=>Di,hasComponentDirective:()=>dr,hasImages:()=>Ni,headerLayouts:()=>rr,initAgentWidget:()=>zr,isComponentDirectiveType:()=>la,markdownPostprocessor:()=>Sr,mergeWithDefaults:()=>or,normalizeContent:()=>$i,pluginRegistry:()=>Ls,renderComponentDirective:()=>lr,renderLoadingIndicatorWithFallback:()=>Wr,validateImageFile:()=>qi});module.exports=Ia(Rl);var Li=require("marked"),ka=t=>{if(t)return t},Cs=t=>{var o,s;let n=t==null?void 0:t.markedOptions,r=new Li.Marked({gfm:(o=n==null?void 0:n.gfm)!=null?o:!0,breaks:(s=n==null?void 0:n.breaks)!=null?s:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),e=ka(t==null?void 0:t.renderer);return e&&r.use({renderer:e}),i=>r.parse(i)},Ss=t=>t?Cs({markedOptions:t.options,renderer:t.renderer}):Cs(),Wa=Cs(),Sr=t=>Wa(t),Js=t=>t.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Ii=t=>t.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Mi=t=>`%%FORM_PLACEHOLDER_${t}%%`,ki=(t,n)=>{let r=t;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=Mi(n.length);return n.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=Mi(n.length);return n.push({token:s,type:o}),s}),r},Wi=t=>{let n=Ss(t);return r=>{let e=[],o=ki(r,e),s=n(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="${Ii(a)}"></div>`;s=s.replace(u,v)}),s}},Pi=t=>{let n=[],r=ki(t,n),e=Sr(r);return n.forEach(({token:o,type:s})=>{let i=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="tvw-form-directive" data-tv-form="${Ii(s)}"></div>`;e=e.replace(i,u)}),e};var dn=require("partial-json"),Ks=t=>t.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),As=t=>{if(t===null)return"null";if(t===void 0)return"";if(typeof t=="string")return t;if(typeof t=="number"||typeof t=="boolean")return String(t);try{return JSON.stringify(t,null,2)}catch{return String(t)}},Pa=t=>{var i,a;let n=(i=t.completedAt)!=null?i:Date.now(),r=(a=t.startedAt)!=null?a:n,o=(t.durationMs!==void 0?t.durationMs:Math.max(0,n-r))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Hi=t=>t.status==="complete"?Pa(t):t.status==="pending"?"Waiting":"",Ha=t=>{var o,s,i;let r=(typeof t.duration=="number"?t.duration:typeof t.durationMs=="number"?t.durationMs:Math.max(0,((o=t.completedAt)!=null?o:Date.now())-((i=(s=t.startedAt)!=null?s:t.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 Bi=t=>t.status==="complete"?Ha(t):"Using tool...",Ba=()=>{let t=null,n=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:()=>t,processChunk:async e=>{if(e.length<=n)return t!==null?{text:t,raw:e}:null;let o=e.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=r(e);return s!==null&&(t=s),n=e.length,t!==null?{text:t,raw:e}:null},close:async()=>{}}},Ys=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Vs=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Xs=()=>{var n;let t=Ba();return{processChunk:async r=>{let e=r.trim();return!e.startsWith("{")&&!e.startsWith("[")?null:t.processChunk(r)},getExtractedText:t.getExtractedText.bind(t),close:(n=t.close)==null?void 0:n.bind(t)}},Gs=()=>{let t=null,n=0;return{getExtractedText:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t!==null||t===""?{text:t||"",raw:r}:null;try{let o=(0,dn.parse)(r,dn.STR|dn.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Ks(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Ks(o.text)))}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Ri=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Ks(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Ks(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return i(s.on_load_text)||i(s.text)||null;case"message":case"message_and_click":case"checkout":return i(s.text)||null;default:return i(s.text)||i(s.display_text)||i(s.message)||null}return i(s.text)||i(s.display_text)||i(s.message)||i(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let i=s.trim();if(!i.startsWith("{")&&!i.startsWith("["))return null;if(s.length<=r)return n!==null?{text:n,raw:s}:null;try{let a=(0,dn.parse)(s,dn.STR|dn.OBJ),u=o(a);u!==null&&(n=u)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Qs=()=>{let t=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let e=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return e&&e[1]?(t=e[1],{text:t,raw:n}):null},getExtractedText:()=>t}};var Ra="https://api.runtype.com/v1/dispatch",Ar="https://api.runtype.com",Er=t=>!!(t.contentParts&&t.contentParts.length>0||t.llmContent&&t.llmContent.trim().length>0||t.rawContent&&t.rawContent.trim().length>0||t.content&&t.content.trim().length>0);function Fa(t){switch(t){case"json":return Gs;case"regex-json":return Xs;case"xml":return Qs;case"plain":default:return Vs}}var Mn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Ra,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Fa(n.parserType),this.contextProviders=(o=n.contextProviders)!=null?o:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var e;let r=((e=this.config.apiUrl)==null?void 0:e.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ar;return n==="init"?`${r}/v1/client/init`:`${r}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let e=await this.sessionInitPromise;return this.clientSession=e,(r=(n=this.config).onSessionInit)==null||r.call(n,e),e}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,i;let n=((i=(s=this.config).getStoredSessionId)==null?void 0:i.call(s))||null,r={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},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$/,""))||Ar}/v1/client/feedback`}async sendFeedback(n){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!o.ok){let a=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(a.error||"Failed to submit feedback")}}async submitMessageFeedback(n,r){let e=this.getClientSession();if(!e)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:e.sessionId,messageId:n,type:r})}async submitCSATFeedback(n,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:n,comment:r})}async submitNPSFeedback(n,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:n,comment:r})}async dispatch(n,r){return this.isAgentMode()?this.dispatchAgent(n,r):this.isClientTokenMode()?this.dispatchClientToken(n,r):this.dispatchProxy(n,r)}async dispatchClientToken(n,r){var o,s,i,a;let e=new AbortController;n.signal&&n.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 h=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:h}),h}let c=await this.buildPayload(n.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([h])=>h!=="sessionId"&&h!=="session_id")):void 0,d={sessionId:u.sessionId,messages:n.messages.filter(Er).map(h=>{var C,b,E;return{id:h.id,role:h.role,content:(E=(b=(C=h.contentParts)!=null?C:h.llmContent)!=null?b:h.rawContent)!=null?E:h.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...v&&Object.keys(v).length>0&&{metadata:v},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:e.signal});if(!f.ok){let h=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(a=(i=this.config).onSessionExpired)==null||a.call(i);let b=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:b}),b}if(f.status===429){let b=new Error(h.hint||"Message limit reached for this session.");throw r({type:"error",error:b}),b}let C=new Error(h.error||"Failed to send message");throw r({type:"error",error:C}),C}if(!f.body){let h=new Error("No response body received");throw r({type:"error",error:h}),h}r({type:"status",status:"connected"});try{await this.streamResponse(f.body,r,n.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(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildPayload(n.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let a=await this.getHeaders();s={...s,...a}}catch(a){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",a)}let i;if(this.customFetch)try{i=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal: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(n,r){let e=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>e.abort()),r({type:"status",status:"connecting"});let o=await this.buildAgentPayload(n.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,n.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(n,r,e){r({type:"status",status:"connected"});try{await this.streamResponse(n,r,e)}finally{r({type:"status",status:"idle"})}}async resolveApproval(n,r){var i;let o=`${((i=this.config.apiUrl)==null?void 0:i.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ar}/v1/agents/${n.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:n.executionId,approvalId:n.approvalId,decision:r,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let r=n.slice().filter(Er).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:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(e.context=o)}return e}async buildPayload(n){let e={messages:n.slice().filter(Er).sort((o,s)=>{let i=new Date(o.createdAt).getTime(),a=new Date(s.createdAt).getTime();return i-a}).map(o=>{var s,i,a;return{role:o.role,content:(a=(i=(s=o.contentParts)!=null?s:o.llmContent)!=null?i:o.rawContent)!=null?a:o.content,createdAt:o.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let i=await s({messages:n,config:this.config});i&&typeof i=="object"&&Object.assign(o,i)}catch(i){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",i)}})),Object.keys(o).length&&(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(n,r,e,o,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);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(n,r,e){var fe,He,St,ht,Et,Ht,Oe,te,ye,Be,Fe,ze,Ot,de,G,ot,wt,Tt,vt,zt,ee,ke,yt,ce,xe,Je,Bt,Mt,_t,z,et,F,Q,se,$e,U,Ee,je,Ce,D,Te,Xe,lt,vn,pn,ut,Xt,Gn,gn,Gt,O,mn,tn,yn,Qn,nn,sn,Bn,Rn,Ws,Ps,Hs,Zn,Fn,Ke,es,ts,rn,Bs,Rs,ns,bn,on,Fs,$s,Os,yr,xn,Cn,nt,$n,On,ss,rs,os,is,Rt,jt,an,Qt,as,Sn,Kt,Ns,Nn,Ds,_s,ln,Ge,Qe,fn,ls,ds,br,Lt,xr,Ft,cs,us,ps,gs,ms,fs,hs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=j=>{let Ie=j.reasoning?{...j.reasoning,chunks:[...j.reasoning.chunks]}:void 0,De=j.toolCall?{...j.toolCall,chunks:j.toolCall.chunks?[...j.toolCall.chunks]:void 0}:void 0,it=j.tools?j.tools.map(pt=>({...pt,chunks:pt.chunks?[...pt.chunks]:void 0})):void 0;return{...j,reasoning:Ie,toolCall:De,tools:it}},d=j=>{r({type:"message",message:v(j)})},f=null,h={current:null},C=new Map,b=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},P=j=>{if(j==null)return null;try{return String(j)}catch{return null}},Y=j=>{var Ie,De,it,pt,At;return P((At=(pt=(it=(De=(Ie=j.stepId)!=null?Ie:j.step_id)!=null?De:j.step)!=null?it:j.parentId)!=null?pt:j.flowStepId)!=null?At:j.flow_step_id)},T=j=>{var Ie,De,it,pt,At,st,m;return P((m=(st=(At=(pt=(it=(De=(Ie=j.callId)!=null?Ie:j.call_id)!=null?De:j.requestId)!=null?it:j.request_id)!=null?pt:j.toolCallId)!=null?At:j.tool_call_id)!=null?st:j.stepId)!=null?m:j.step_id)},I=()=>f||(f={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(f),f),M=(j,Ie)=>{E.lastId=Ie,j&&E.byStep.set(j,Ie)},R=(j,Ie)=>{var At;let De=(At=j.reasoningId)!=null?At:j.id,it=Y(j);if(De){let st=String(De);return M(it,st),st}if(it){let st=E.byStep.get(it);if(st)return E.lastId=st,st}if(E.lastId&&!Ie)return E.lastId;if(!Ie)return null;let pt=`reason-${c()}`;return M(it,pt),pt},ie=j=>{let Ie=C.get(j);if(Ie)return Ie;let De={id:`reason-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:j,status:"streaming",chunks:[]}};return C.set(j,De),d(De),De},K=(j,Ie)=>{x.lastId=Ie,j&&x.byCall.set(j,Ie)},q=(j,Ie)=>{var At;let De=(At=j.toolId)!=null?At:j.id,it=T(j);if(De){let st=String(De);return K(it,st),st}if(it){let st=x.byCall.get(it);if(st)return x.lastId=st,st}if(x.lastId&&!Ie)return x.lastId;if(!Ie)return null;let pt=`tool-${c()}`;return K(it,pt),pt},V=j=>{let Ie=b.get(j);if(Ie)return Ie;let De={id:`tool-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:j,status:"pending"}};return b.set(j,De),d(De),De},N=j=>{if(typeof j=="number"&&Number.isFinite(j))return j;if(typeof j=="string"){let Ie=Number(j);if(!Number.isNaN(Ie)&&Number.isFinite(Ie))return Ie;let De=Date.parse(j);if(!Number.isNaN(De))return De}return Date.now()},me=j=>{if(typeof j=="string")return j;if(j==null)return"";try{return JSON.stringify(j)}catch{return String(j)}},_=new Map,J=new Map,X=null,$=new Map,ae=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:j,value:Ie}=await o.read();if(j)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=(He=De.pop())!=null?He:"";for(let it of De){let pt=it.split(`
7
- `),At="message",st="";for(let B of pt)B.startsWith("event:")?At=B.replace("event:","").trim():B.startsWith("data:")&&(st+=B.replace("data:","").trim());if(!st)continue;let m;try{m=JSON.parse(st)}catch(B){r({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let We=At!=="message"?At:(St=m.type)!=null?St:"message";if((ht=this.onSSEEvent)==null||ht.call(this,We,m),this.parseSSEEvent){h.current=f;let B=await this.handleCustomSSEEvent(m,r,h,d,c);if(h.current&&!f&&(f=h.current),B)continue}if(We==="reason_start"){let B=(Et=R(m,!0))!=null?Et:`reason-${c()}`,y=ie(B);y.reasoning=(Ht=y.reasoning)!=null?Ht:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(te=y.reasoning.startedAt)!=null?te:N((Oe=m.startedAt)!=null?Oe:m.timestamp),y.reasoning.completedAt=void 0,y.reasoning.durationMs=void 0,y.streaming=!0,y.reasoning.status="streaming",d(y)}else if(We==="reason_delta"||We==="reason_chunk"){let B=(Be=(ye=R(m,!1))!=null?ye:R(m,!0))!=null?Be:`reason-${c()}`,y=ie(B);y.reasoning=(Fe=y.reasoning)!=null?Fe:{id:B,status:"streaming",chunks:[]},y.reasoning.startedAt=(Ot=y.reasoning.startedAt)!=null?Ot:N((ze=m.startedAt)!=null?ze:m.timestamp);let L=(ot=(G=(de=m.reasoningText)!=null?de:m.text)!=null?G:m.delta)!=null?ot:"";if(L&&m.hidden!==!0&&y.reasoning.chunks.push(String(L)),y.reasoning.status=m.done?"complete":"streaming",m.done){y.reasoning.completedAt=N((wt=m.completedAt)!=null?wt:m.timestamp);let oe=(Tt=y.reasoning.startedAt)!=null?Tt:Date.now();y.reasoning.durationMs=Math.max(0,((vt=y.reasoning.completedAt)!=null?vt:Date.now())-oe)}y.streaming=y.reasoning.status!=="complete",d(y)}else if(We==="reason_complete"){let B=(ee=(zt=R(m,!1))!=null?zt:R(m,!0))!=null?ee:`reason-${c()}`,y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N((ke=m.completedAt)!=null?ke:m.timestamp);let oe=(yt=y.reasoning.startedAt)!=null?yt:Date.now();y.reasoning.durationMs=Math.max(0,((ce=y.reasoning.completedAt)!=null?ce:Date.now())-oe),y.streaming=!1,d(y)}let L=Y(m);L&&E.byStep.delete(L)}else if(We==="tool_start"){let B=(xe=q(m,!0))!=null?xe:`tool-${c()}`,y=V(B),L=(Je=y.toolCall)!=null?Je:{id:B,status:"pending"};L.name=(Bt=m.toolName)!=null?Bt:L.name,L.status="running",m.args!==void 0?L.args=m.args:m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=(_t=L.startedAt)!=null?_t:N((Mt=m.startedAt)!=null?Mt:m.timestamp),L.completedAt=void 0,L.durationMs=void 0,y.toolCall=L,y.streaming=!0;let oe=m.agentContext;(oe||m.executionId)&&(y.agentMetadata={executionId:(z=oe==null?void 0:oe.executionId)!=null?z:m.executionId,iteration:(et=oe==null?void 0:oe.iteration)!=null?et:m.iteration}),d(y)}else if(We==="tool_chunk"||We==="tool_delta"){let B=(Q=(F=q(m,!1))!=null?F:q(m,!0))!=null?Q:`tool-${c()}`,y=V(B),L=(se=y.toolCall)!=null?se:{id:B,status:"running"};L.startedAt=(U=L.startedAt)!=null?U:N(($e=m.startedAt)!=null?$e:m.timestamp);let oe=(Ce=(je=(Ee=m.text)!=null?Ee:m.delta)!=null?je:m.message)!=null?Ce:"";oe&&(L.chunks=(D=L.chunks)!=null?D:[],L.chunks.push(String(oe))),L.status="running",y.toolCall=L,y.streaming=!0;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(lt=y.agentMetadata)!=null?lt:{executionId:(Te=Se==null?void 0:Se.executionId)!=null?Te:m.executionId,iteration:(Xe=Se==null?void 0:Se.iteration)!=null?Xe:m.iteration}),d(y)}else if(We==="tool_complete"){let B=(pn=(vn=q(m,!1))!=null?vn:q(m,!0))!=null?pn:`tool-${c()}`,y=V(B),L=(ut=y.toolCall)!=null?ut:{id:B,status:"running"};L.status="complete",m.result!==void 0&&(L.result=m.result),typeof m.duration=="number"&&(L.duration=m.duration),L.completedAt=N((Xt=m.completedAt)!=null?Xt:m.timestamp);let oe=(Gn=m.duration)!=null?Gn:m.executionTime;if(typeof oe=="number")L.durationMs=oe;else{let It=(gn=L.startedAt)!=null?gn:Date.now();L.durationMs=Math.max(0,((Gt=L.completedAt)!=null?Gt:Date.now())-It)}y.toolCall=L,y.streaming=!1;let Se=m.agentContext;(Se||m.executionId)&&(y.agentMetadata=(tn=y.agentMetadata)!=null?tn:{executionId:(O=Se==null?void 0:Se.executionId)!=null?O:m.executionId,iteration:(mn=Se==null?void 0:Se.iteration)!=null?mn:m.iteration}),d(y);let Ye=T(m);Ye&&x.byCall.delete(Ye)}else if(We==="step_chunk"||We==="step_delta"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=I(),oe=(sn=(nn=(Qn=(yn=m.text)!=null?yn:m.delta)!=null?Qn:m.content)!=null?nn:m.chunk)!=null?sn:"";if(oe){let Ye=((Bn=J.get(L.id))!=null?Bn:"")+oe;L.rawContent=Ye,_.has(L.id)||_.set(L.id,this.createStreamParser());let It=_.get(L.id),rt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(rt&&J.set(L.id,Ye),It.__isPlainTextParser===!0){L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L);continue}let gt=It.processChunk(Ye);if(gt instanceof Promise)gt.then(Ne=>{var dt;let qe=typeof Ne=="string"?Ne:(dt=Ne==null?void 0:Ne.text)!=null?dt:null;if(qe!==null&&qe.trim()!==""){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content=qe,d(Ue))}else if(!rt&&!Ye.trim().startsWith("<")){let Ue=f;Ue&&Ue.id===L.id&&(Ue.content+=oe,J.delete(Ue.id),_.delete(Ue.id),Ue.rawContent=void 0,d(Ue))}}).catch(()=>{L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L)});else{let Ne=typeof gt=="string"?gt:(Rn=gt==null?void 0:gt.text)!=null?Rn:null;Ne!==null&&Ne.trim()!==""?(L.content=Ne,d(L)):!rt&&!Ye.trim().startsWith("<")&&(L.content+=oe,J.delete(L.id),_.delete(L.id),L.rawContent=void 0,d(L))}}if(m.isComplete){let Se=(Ps=(Ws=m.result)==null?void 0:Ws.response)!=null?Ps:L.content;if(Se){let Ye=J.get(L.id),It=Ye!=null?Ye:me(Se);L.rawContent=It;let rt=_.get(L.id),bt=null,gt=!1;if(rt&&(bt=rt.getExtractedText(),bt===null&&(bt=Ys(It)),bt===null)){let Ne=rt.processChunk(It);Ne instanceof Promise?(gt=!0,Ne.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===L.id&&(xt.content=dt,xt.streaming=!1,_.delete(xt.id),J.delete(xt.id),d(xt))}})):bt=typeof Ne=="string"?Ne:(Hs=Ne==null?void 0:Ne.text)!=null?Hs:null}if(!gt){bt!==null&&bt.trim()!==""?L.content=bt:J.has(L.id)||(L.content=me(Se));let Ne=_.get(L.id);if(Ne){let qe=(Zn=Ne.close)==null?void 0:Zn.call(Ne);qe instanceof Promise&&qe.catch(()=>{}),_.delete(L.id)}J.delete(L.id),L.streaming=!1,d(L)}}}}else if(We==="step_complete"){let B=m.stepType,y=m.executionType;if(B==="tool"||y==="context")continue;let L=(Fn=m.result)==null?void 0:Fn.response,oe=I();if(L!=null){let Se=_.get(oe.id),Ye=!1,It=!1;if(Se){let rt=Se.getExtractedText(),bt=J.get(oe.id),gt=bt!=null?bt:me(L);if(oe.rawContent=gt,rt!==null&&rt.trim()!=="")oe.content=rt,Ye=!0;else{let Ne=Ys(gt);if(Ne!==null)oe.content=Ne,Ye=!0;else{let qe=Se.processChunk(gt);if(qe instanceof Promise)It=!0,qe.then(dt=>{var xt;let Ue=typeof dt=="string"?dt:(xt=dt==null?void 0:dt.text)!=null?xt:null;if(Ue!==null&&Ue.trim()!==""){let Nt=f;Nt&&Nt.id===oe.id&&(Nt.content=Ue,Nt.streaming=!1,_.delete(Nt.id),J.delete(Nt.id),d(Nt))}else{let Nt=Se.getExtractedText(),Jt=f;Jt&&Jt.id===oe.id&&(Nt!==null&&Nt.trim()!==""?Jt.content=Nt:J.has(Jt.id)||(Jt.content=me(L)),Jt.streaming=!1,_.delete(Jt.id),J.delete(Jt.id),d(Jt))}});else{let dt=typeof qe=="string"?qe:(Ke=qe==null?void 0:qe.text)!=null?Ke:null;if(dt!==null&&dt.trim()!=="")oe.content=dt,Ye=!0;else{let Ue=Se.getExtractedText();Ue!==null&&Ue.trim()!==""&&(oe.content=Ue,Ye=!0)}}}}}if(!It){if(!oe.rawContent){let rt=J.get(oe.id);oe.rawContent=rt!=null?rt:me(L)}if(!Ye&&!J.has(oe.id)&&(oe.content=me(L)),Se){let rt=(es=Se.close)==null?void 0:es.call(Se);rt instanceof Promise&&rt.catch(()=>{})}_.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}}else _.delete(oe.id),J.delete(oe.id),oe.streaming=!1,d(oe)}else if(We==="flow_complete"){let B=(ts=m.result)==null?void 0:ts.response;if(B!=null){let y=I(),L=J.get(y.id),oe=L!=null?L:me(B);y.rawContent=oe;let Se=me(B),Ye=_.get(y.id);if(Ye){let bt=Ys(oe);if(bt!==null)Se=bt;else{let gt=Ye.processChunk(oe);gt instanceof Promise&&gt.then(qe=>{var Ue;let dt=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(dt!==null){let xt=f;xt&&xt.id===y.id&&(xt.content=dt,xt.streaming=!1,d(xt))}});let Ne=Ye.getExtractedText();Ne!==null&&(Se=Ne)}}_.delete(y.id),J.delete(y.id);let It=Se!==y.content,rt=y.streaming!==!1;It&&(y.content=Se),y.streaming=!1,(It||rt)&&d(y)}else if(f!==null){let y=f;_.delete(y.id),J.delete(y.id),y.streaming!==!1&&(y.streaming=!1,d(y))}r({type:"status",status:"idle"})}else if(We==="agent_start")X={executionId:m.executionId,agentId:(rn=m.agentId)!=null?rn:"virtual",agentName:(Bs=m.agentName)!=null?Bs:"",status:"running",currentIteration:0,maxIterations:(Rs=m.maxIterations)!=null?Rs:1,startedAt:N(m.startedAt)};else if(We==="agent_iteration_start"){if(X&&(X.currentIteration=m.iteration),ae==="separate"&&m.iteration>1){let B=f;B&&(B.streaming=!1,d(B),$.set(m.iteration-1,B),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(m.contentType==="text"){let B=I();B.content+=(ns=m.delta)!=null?ns:"",B.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:X==null?void 0:X.agentName},d(B)}else if(m.contentType==="thinking"){let B=(bn=m.turnId)!=null?bn:`agent-think-${m.iteration}`,y=ie(B);y.reasoning=(on=y.reasoning)!=null?on:{id:B,status:"streaming",chunks:[]},y.reasoning.chunks.push((Fs=m.delta)!=null?Fs:""),y.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},d(y)}else if(m.contentType==="tool_input"){let B=($s=m.toolCallId)!=null?$s:x.lastId;if(B){let y=b.get(B);y!=null&&y.toolCall&&(y.toolCall.chunks=(Os=y.toolCall.chunks)!=null?Os:[],y.toolCall.chunks.push((yr=m.delta)!=null?yr:""),d(y))}}}else if(We==="agent_turn_complete"){let B=m.turnId;if(B){let y=C.get(B);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=N(m.completedAt);let L=(xn=y.reasoning.startedAt)!=null?xn:Date.now();y.reasoning.durationMs=Math.max(0,((Cn=y.reasoning.completedAt)!=null?Cn:Date.now())-L),y.streaming=!1,d(y)}}}else if(We==="agent_tool_start"){let B=(nt=m.toolCallId)!=null?nt:`agent-tool-${c()}`;K(T(m),B);let y=V(B),L=($n=y.toolCall)!=null?$n:{id:B,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=(On=m.toolName)!=null?On:L.name,L.status="running",m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=N((ss=m.startedAt)!=null?ss:m.timestamp),y.toolCall=L,y.streaming=!0,y.agentMetadata={executionId:m.executionId,iteration:m.iteration},d(y)}else if(We==="agent_tool_delta"){let B=(rs=m.toolCallId)!=null?rs:x.lastId;if(B){let y=(os=b.get(B))!=null?os:V(B);y.toolCall&&(y.toolCall.chunks=(is=y.toolCall.chunks)!=null?is:[],y.toolCall.chunks.push((Rt=m.delta)!=null?Rt:""),y.toolCall.status="running",y.streaming=!0,d(y))}}else if(We==="agent_tool_complete"){let B=(jt=m.toolCallId)!=null?jt:x.lastId;if(B){let y=(an=b.get(B))!=null?an:V(B);if(y.toolCall){y.toolCall.status="complete",m.result!==void 0&&(y.toolCall.result=m.result),typeof m.executionTime=="number"&&(y.toolCall.durationMs=m.executionTime),y.toolCall.completedAt=N((Qt=m.completedAt)!=null?Qt:m.timestamp),y.streaming=!1,d(y);let L=T(m);L&&x.byCall.delete(L)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let B=`agent-reflection-${m.executionId}-${m.iteration}`,y={id:B,role:"assistant",content:(as=m.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(Sn=m.reflection)!=null?Sn:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};d(y)}else if(We==="agent_complete"){X&&(X.status=m.success?"complete":"error",X.completedAt=N(m.completedAt),X.stopReason=m.stopReason);let B=f;B&&(B.streaming=!1,d(B)),r({type:"status",status:"idle"})}else if(We==="agent_error"){let B=typeof m.error=="string"?m.error:(Ns=(Kt=m.error)==null?void 0:Kt.message)!=null?Ns:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):r({type:"error",error:new Error(B)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let B=(Nn=m.approvalId)!=null?Nn:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Ds=X==null?void 0:X.agentId)!=null?Ds:"virtual",executionId:(ln=(_s=m.executionId)!=null?_s:X==null?void 0:X.executionId)!=null?ln:"",toolName:(Ge=m.toolName)!=null?Ge:"",toolType:m.toolType,description:(fn=m.description)!=null?fn:`Execute ${(Qe=m.toolName)!=null?Qe:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="step_await"&&m.awaitReason==="approval_required"){let B=(ls=m.approvalId)!=null?ls:`approval-${c()}`,y={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(ds=X==null?void 0:X.agentId)!=null?ds:"virtual",executionId:(Lt=(br=m.executionId)!=null?br:X==null?void 0:X.executionId)!=null?Lt:"",toolName:(xr=m.toolName)!=null?xr:"",toolType:m.toolType,description:(cs=m.description)!=null?cs:`Execute ${(Ft=m.toolName)!=null?Ft:"tool"}`,parameters:m.parameters}};d(y)}else if(We==="agent_approval_complete"){let B=m.approvalId;if(B){let L={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(us=m.decision)!=null?us:"approved",agentId:(ps=X==null?void 0:X.agentId)!=null?ps:"virtual",executionId:(ms=(gs=m.executionId)!=null?gs:X==null?void 0:X.executionId)!=null?ms:"",toolName:(fs=m.toolName)!=null?fs:"",description:(hs=m.description)!=null?hs:"",resolvedAt:Date.now()}};d(L)}}else We==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}}};function Fi(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${t}_${n}`}function Dn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${t}_${n}`}function Ln(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${t}_${n}`}var Zs="[Image]";function $i(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Oi(t){return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}function Ni(t){return typeof t=="string"?!1:t.some(n=>n.type==="image")}function Di(t){return typeof t=="string"?[]:t.filter(n=>n.type==="image")}function er(t){return{type:"text",text:t}}function _i(t,n){return{type:"image",image:t,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function ji(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;n({type:"image",image:o,mimeType:t.type,alt:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function qi(t,n=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Ui=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],$a=["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"],wn=[...Ui,...$a];function Oa(t){return Ui.includes(t)||t.startsWith("image/")}function tr(t){return Oa(t.type)}async function zi(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;tr(t)?n({type:"image",image:o,mimeType:t.type,alt:t.name}):n({type:"file",data:o,mimeType:t.type,filename:t.name})},e.onerror=()=>r(new Error("Failed to read file")),e.readAsDataURL(t)})}function Ji(t,n=wn,r=10*1024*1024){return n.includes(t.type)?t.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${t.type}". Accepted types: ${n.join(", ")}`}}function Na(t){let n=t.split(".");return n.length>1?n.pop().toLowerCase():""}function Ki(t,n){let r=Na(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[t]||r||"FILE"}var _n=class{constructor(n={},r){this.config=n;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.handleEvent=n=>{var r,e,o,s,i,a,u;n.type==="message"?(this.upsertMessage(n.message),(r=n.message.agentMetadata)!=null&&r.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(e=n.message.agentMetadata.agentName)!=null?e:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxIterations:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.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,n.error))};var e;this.messages=[...(e=n.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 Mn(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}async initClientSession(){var n,r;if(!this.isClientTokenMode())return null;try{let e=await this.client.initSession();return this.setClientSession(e),e}catch(e){return(r=(n=this.callbacks).onError)==null||r.call(n,e instanceof Error?e:new Error(String(e))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,r){return this.client.submitMessageFeedback(n,r)}async submitCSATFeedback(n,r){return this.client.submitCSATFeedback(n,r)}async submitNPSFeedback(n,r){return this.client.submitNPSFeedback(n,r)}updateConfig(n){let r=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Mn(this.config),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:r,content:e,llmContent:o,contentParts:s,id:i,createdAt:a,sequence:u,streaming:c=!1}=n,d={id:i!=null?i:r==="user"?Dn():r==="assistant"?Ln():`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}};return this.upsertMessage(d),d}injectAssistantMessage(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let r=[];for(let e of n){let{role:o,content:s,llmContent:i,contentParts:a,id:u,createdAt:c,sequence:v,streaming:d=!1}=e,h={id:u!=null?u:o==="user"?Dn():o==="assistant"?Ln():`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(h)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,d,f,h;let e=n.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Dn(),s=Ln(),i={id:o,role:"user",content:e||Zs,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(C){let b=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!b){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(C instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,C):(h=(f=this.callbacks).onError)==null||h.call(f,new Error(String(C))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Ln();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:n},this.handleEvent)}catch(c){let v={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(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(n,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(n,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(n,r){var u,c,v;let e=`approval-${n.id}`,o={...n,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:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},r):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},r),d){let f=null;if(d instanceof Response){if(!d.ok){let h=await d.json().catch(()=>null);throw new Error((u=h==null?void 0:h.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):r==="denied"&&this.appendMessage({id:`denial-${n.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 n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateMessages(n){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(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(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){this.streaming!==n&&(this.streaming=n,this.callbacks.onStreamingChanged(n))}appendMessage(n){let r=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let r=this.ensureSequence(n),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(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].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 p=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Da=La(require("lucide"),1),re=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Da[o];return s?_a(s,n,r,e):(console.warn(`Lucide icon "${t}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${t}":`,o),null}};function _a(t,n,r,e){if(!t||!Array.isArray(t))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(n)),o.setAttribute("height",String(n)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",r),o.setAttribute("stroke-width",String(e)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),t.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 nr={allowedTypes:wn,maxFileSize:10*1024*1024,maxFiles:4};function ja(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function qa(t){return t==="application/pdf"||t.startsWith("text/")||t.includes("word")?"file-text":t.includes("excel")||t.includes("spreadsheet")?"file-spreadsheet":t==="application/json"?"file-json":"file"}var In=class t{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:nr.allowedTypes,maxFileSize:(e=n.maxFileSize)!=null?e:nr.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:nr.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:nr.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var r,e,o,s,i,a,u;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(e=(r=this.config).onFileRejected)==null||e.call(r,c,"count");continue}let v=Ji(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 zi(c),f=tr(c)?URL.createObjectURL(c):null,h={id:ja(),file:c,previewUrl:f,contentPart:d};this.attachments.push(h),this.renderPreview(h)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(n){var s,i,a;let r=this.attachments.findIndex(u=>u.id===n);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="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(a=(i=this.config).onAttachmentsChange)==null||a.call(i,this.getAttachments())}clearAttachments(){var n,r;for(let e of this.attachments)e.previewUrl&&URL.revokeObjectURL(e.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(n=this.config).onAttachmentsChange)==null||r.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let r=tr(n.file),e=p("div","tvw-attachment-preview tvw-relative tvw-inline-block");if(e.setAttribute("data-attachment-id",n.id),e.style.width="48px",e.style.height="48px",r&&n.previewUrl){let i=p("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",e.appendChild(i)}else{let i=p("div");i.style.width="48px",i.style.height="48px",i.style.borderRadius="8px",i.style.backgroundColor="var(--cw-container, #f3f4f6)",i.style.border="1px solid var(--cw-border, #e5e7eb)",i.style.display="flex",i.style.flexDirection="column",i.style.alignItems="center",i.style.justifyContent="center",i.style.gap="2px",i.style.overflow="hidden";let a=qa(n.file.type),u=re(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=p("span");c.textContent=Ki(n.file.type,n.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=p("button","tvw-attachment-remove tvw-absolute tvw-flex tvw-items-center tvw-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="rgba(0, 0, 0, 0.6)",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=re("x",10,"#ffffff",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="#ffffff",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",i=>{i.preventDefault(),i.stopPropagation(),this.removeAttachment(n.id)}),e.appendChild(o),this.previewsContainer.appendChild(e)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,r){return new t({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:r})}};var Tr=()=>{var t;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((t=window.matchMedia)!=null&&t.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Ua=t=>{var s,i,a;let n=(s=t==null?void 0:t.colorScheme)!=null?s:"light",r=(i=t==null?void 0:t.theme)!=null?i:{},e=(a=t==null?void 0:t.darkTheme)!=null?a:r;return n==="light"?r:n==="dark"||Tr()==="dark"?e:r},Yi=t=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Tr())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),e=()=>t(Tr());r.addEventListener?(r.addEventListener("change",e),n.push(()=>r.removeEventListener("change",e))):r.addListener&&(r.addListener(e),n.push(()=>r.removeListener(e)))}return()=>{n.forEach(r=>r())}},sr=(t,n)=>{let r=Ua(n);Object.entries(r).forEach(([e,o])=>{if(o==null||o==="")return;let s=e.replace(/[A-Z]/g,i=>`-${i.toLowerCase()}`);t.style.setProperty(`--cw-${s}`,String(o))})};var Vi=require("idiomorph"),Xi=(t,n,r={})=>{let{preserveTypingAnimation:e=!0}=r;Vi.Idiomorph.morph(t,n.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 Pt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Vt={"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 Es=(t,n)=>{let r=p("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,24 +12,24 @@
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",n);let e=s=>{var x,P,Y,T,I,M,R,ie,K,q,V,N;let i=(x=s.launcher)!=null?x:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(P=i.title)!=null?P:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.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 me=(T=i.agentIconSize)!=null?T:"40px";if(v.style.height=me,v.style.width=me,v.innerHTML="",i.agentIconName){let _=parseFloat(me)||24,J=re(i.agentIconName,_*.6,"#ffffff",2);J?(v.appendChild(J),v.style.display=""):(v.textContent=(I=i.agentIconText)!=null?I:"\u{1F4AC}",v.style.display="")}else i.iconUrl?v.style.display="none":(v.textContent=(M=i.agentIconText)!=null?M:"\u{1F4AC}",v.style.display="")}let d=r.querySelector("[data-role='launcher-image']");if(d){let me=(R=i.agentIconSize)!=null?R:"40px";d.style.height=me,d.style.width=me,i.iconUrl&&!i.agentIconName&&!i.agentIconHidden?(d.src=i.iconUrl,d.style.display="block"):d.style.display="none"}let f=r.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let me=(ie=i.callToActionIconSize)!=null?ie:"32px";f.style.height=me,f.style.width=me,i.callToActionIconBackgroundColor?(f.style.backgroundColor=i.callToActionIconBackgroundColor,f.classList.remove("tvw-bg-cw-primary")):(f.style.backgroundColor="",f.classList.add("tvw-bg-cw-primary"));let _=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,_=(parseFloat(i.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),i.callToActionIconHidden)f.style.display="none";else if(f.style.display="",f.innerHTML="",i.callToActionIconName){let J=parseFloat(me)||24,X=Math.max(J-_,8),$=re(i.callToActionIconName,X,"currentColor",2);$?f.appendChild($):f.textContent=(K=i.callToActionIconText)!=null?K:"\u2197"}else f.textContent=(q=i.callToActionIconText)!=null?q:"\u2197"}let h=i.position&&Vt[i.position]?Vt[i.position]:Vt["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} ${h}`;let b="1px solid #e5e7eb",E="0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)";r.style.border=(V=i.border)!=null?V:b,r.style.boxShadow=(N=i.shadow)!=null?N:E},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var cn=t=>{var q,V,N,me,_,J,X,$,ae,fe,He,St,ht,Et,Ht,Oe,te,ye,Be,Fe,ze,Ot,de,G,ot,wt,Tt,vt,zt,ee,ke,yt;let{config:n,showClose:r=!0}=t,e=p("div","tvw-widget-header tvw-flex tvw-items-center tvw-gap-3 tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),o=(q=n==null?void 0:n.launcher)!=null?q:{},s=(V=o.headerIconSize)!=null?V:"48px",i=(N=o.closeButtonSize)!=null?N:"32px",a=(me=o.closeButtonPlacement)!=null?me:"inline",u=(_=o.headerIconHidden)!=null?_:!1,c=o.headerIconName,v=p("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 ce=parseFloat(s)||24,xe=re(c,ce*.6,"#ffffff",1);xe?v.replaceChildren(xe):v.textContent=(X=(J=n==null?void 0:n.launcher)==null?void 0:J.agentIconText)!=null?X:"\u{1F4AC}"}else if(($=n==null?void 0:n.launcher)!=null&&$.iconUrl){let ce=p("img");ce.src=n.launcher.iconUrl,ce.alt="",ce.className="tvw-rounded-xl tvw-object-cover",ce.style.height=s,ce.style.width=s,v.replaceChildren(ce)}else v.textContent=(fe=(ae=n==null?void 0:n.launcher)==null?void 0:ae.agentIconText)!=null?fe:"\u{1F4AC}";let d=p("div","tvw-flex tvw-flex-col"),f=p("span","tvw-text-base tvw-font-semibold");f.textContent=(St=(He=n==null?void 0:n.launcher)==null?void 0:He.title)!=null?St:"Chat Assistant";let h=p("span","tvw-text-xs tvw-text-cw-muted");h.textContent=(Et=(ht=n==null?void 0:n.launcher)==null?void 0:ht.subtitle)!=null?Et:"Here to help you get answers fast",d.append(f,h),u?e.append(d):e.append(v,d);let C=(Ht=o.clearChat)!=null?Ht:{},b=(Oe=C.enabled)!=null?Oe:!0,E=(te=C.placement)!=null?te:"inline",x=null,P=null;if(b){let ce=(ye=C.size)!=null?ye:"32px",xe=(Be=C.iconName)!=null?Be:"refresh-cw",Je=(Fe=C.iconColor)!=null?Fe:"",Bt=(ze=C.backgroundColor)!=null?ze:"",Mt=(Ot=C.borderWidth)!=null?Ot:"",_t=(de=C.borderColor)!=null?de:"",z=(G=C.borderRadius)!=null?G:"",et=(ot=C.paddingX)!=null?ot:"",F=(wt=C.paddingY)!=null?wt:"",Q=(Tt=C.tooltipText)!=null?Tt:"Clear chat",se=(vt=C.showTooltip)!=null?vt:!0;P=p("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(P.style.right="48px"),x=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none"),x.style.height=ce,x.style.width=ce,x.type="button",x.setAttribute("aria-label",Q);let $e=re(xe,"20px",Je||"",1);if($e&&x.appendChild($e),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")),Mt||_t){let U=Mt||"0px",Ee=_t||"transparent";x.style.border=`${U} solid ${Ee}`,x.classList.remove("tvw-border-none")}if(z&&(x.style.borderRadius=z,x.classList.remove("tvw-rounded-full")),et?(x.style.paddingLeft=et,x.style.paddingRight=et):(x.style.paddingLeft="",x.style.paddingRight=""),F?(x.style.paddingTop=F,x.style.paddingBottom=F):(x.style.paddingTop="",x.style.paddingBottom=""),P.appendChild(x),se&&Q&&x&&P){let U=null,Ee=()=>{if(U||!x)return;U=p("div","tvw-clear-chat-tooltip"),U.textContent=Q;let Ce=p("div");Ce.className="tvw-clear-chat-tooltip-arrow",U.appendChild(Ce);let D=x.getBoundingClientRect();U.style.position="fixed",U.style.left=`${D.left+D.width/2}px`,U.style.top=`${D.top-8}px`,U.style.transform="translate(-50%, -100%)",document.body.appendChild(U)},je=()=>{U&&U.parentNode&&(U.parentNode.removeChild(U),U=null)};P.addEventListener("mouseenter",Ee),P.addEventListener("mouseleave",je),x.addEventListener("focus",Ee),x.addEventListener("blur",je),P._cleanupTooltip=()=>{je(),P&&(P.removeEventListener("mouseenter",Ee),P.removeEventListener("mouseleave",je)),x&&(x.removeEventListener("focus",Ee),x.removeEventListener("blur",je))}}E==="inline"&&e.appendChild(P)}let Y=p("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":b&&E==="inline"?"":"tvw-ml-auto"),T=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");T.style.height=i,T.style.width=i,T.type="button";let I=(zt=o.closeButtonTooltipText)!=null?zt:"Close chat",M=(ee=o.closeButtonShowTooltip)!=null?ee:!0;T.setAttribute("aria-label",I),T.style.display=r?"":"none";let R=(ke=o.closeButtonIconName)!=null?ke:"x",ie=(yt=o.closeButtonIconText)!=null?yt:"\xD7",K=re(R,"20px",o.closeButtonColor||"",1);if(K?T.appendChild(K):T.textContent=ie,o.closeButtonColor?(T.style.color=o.closeButtonColor,T.classList.remove("tvw-text-cw-muted")):(T.style.color="",T.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(T.style.backgroundColor=o.closeButtonBackgroundColor,T.classList.remove("hover:tvw-bg-gray-100")):(T.style.backgroundColor="",T.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let ce=o.closeButtonBorderWidth||"0px",xe=o.closeButtonBorderColor||"transparent";T.style.border=`${ce} solid ${xe}`,T.classList.remove("tvw-border-none")}else T.style.border="",T.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(T.style.borderRadius=o.closeButtonBorderRadius,T.classList.remove("tvw-rounded-full")):(T.style.borderRadius="",T.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(T.style.paddingLeft=o.closeButtonPaddingX,T.style.paddingRight=o.closeButtonPaddingX):(T.style.paddingLeft="",T.style.paddingRight=""),o.closeButtonPaddingY?(T.style.paddingTop=o.closeButtonPaddingY,T.style.paddingBottom=o.closeButtonPaddingY):(T.style.paddingTop="",T.style.paddingBottom=""),Y.appendChild(T),M&&I){let ce=null,xe=()=>{if(ce)return;ce=p("div","tvw-clear-chat-tooltip"),ce.textContent=I;let Bt=p("div");Bt.className="tvw-clear-chat-tooltip-arrow",ce.appendChild(Bt);let Mt=T.getBoundingClientRect();ce.style.position="fixed",ce.style.left=`${Mt.left+Mt.width/2}px`,ce.style.top=`${Mt.top-8}px`,ce.style.transform="translate(-50%, -100%)",document.body.appendChild(ce)},Je=()=>{ce&&ce.parentNode&&(ce.parentNode.removeChild(ce),ce=null)};Y.addEventListener("mouseenter",xe),Y.addEventListener("mouseleave",Je),T.addEventListener("focus",xe),T.addEventListener("blur",Je),Y._cleanupTooltip=()=>{Je(),Y.removeEventListener("mouseenter",xe),Y.removeEventListener("mouseleave",Je),T.removeEventListener("focus",xe),T.removeEventListener("blur",Je)}}return a!=="top-right"&&e.appendChild(Y),{header:e,iconHolder:v,headerTitle:f,headerSubtitle:h,closeButton:T,closeButtonWrapper:Y,clearChatButton:x,clearChatButtonWrapper:P}},kn=(t,n,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";t.appendChild(n.header),o==="top-right"&&(t.style.position="relative",t.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(t.style.position="relative",t.appendChild(n.clearChatButtonWrapper))};var Mr=t=>cn({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),Lr=t=>{var C,b,E,x;let{config:n,showClose:r=!0,onClose:e}=t,o=(C=n==null?void 0:n.launcher)!=null?C:{},s=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-bg-cw-surface tvw-px-6 tvw-py-4 tvw-border-b-cw-divider"),i=p("span","tvw-text-base tvw-font-semibold");i.textContent=(b=o.title)!=null?b:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",u=p("div",""),c=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");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=re(v,"20px",o.closeButtonColor||"",2);d?c.appendChild(d):c.textContent="\xD7",e&&c.addEventListener("click",e),u.appendChild(c),s.appendChild(u);let f=p("div");f.style.display="none";let h=p("span");return h.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:h,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Ir=t=>{var T,I,M,R,ie,K,q,V;let{config:n,showClose:r=!0,onClose:e,onClearChat:o}=t,s=(T=n==null?void 0:n.launcher)!=null?T:{},i=p("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=p("div","tvw-flex tvw-items-center tvw-gap-3"),u=(I=s.headerIconSize)!=null?I:"56px",c=p("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 N=parseFloat(u)||24,me=re(v,N*.5,"#ffffff",2);me?c.replaceChildren(me):c.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}"}else if(s.iconUrl){let N=p("img");N.src=s.iconUrl,N.alt="",N.className="tvw-rounded-xl tvw-object-cover",N.style.height=u,N.style.width=u,c.replaceChildren(N)}else c.textContent=(R=s.agentIconText)!=null?R:"\u{1F4AC}";let d=p("div","tvw-flex tvw-flex-col tvw-flex-1"),f=p("span","tvw-text-lg tvw-font-semibold");f.textContent=(ie=s.title)!=null?ie:"Chat Assistant";let h=p("span","tvw-text-sm tvw-text-cw-muted");h.textContent=(K=s.subtitle)!=null?K:"Here to help you get answers fast",d.append(f,h),a.append(c,d);let C=(q=s.closeButtonSize)!=null?q:"32px",b=p("div",""),E=p("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=C,E.style.width=C,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let x=(V=s.closeButtonIconName)!=null?V:"x",P=re(x,"20px",s.closeButtonColor||"",2);P?E.appendChild(P):E.textContent="\xD7",e&&E.addEventListener("click",e),b.appendChild(E),a.appendChild(b),i.appendChild(a);let Y=p("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:f,headerSubtitle:h,closeButton:E,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}},rr={default:Mr,minimal:Lr,expanded:Ir},kr=t=>{var n;return(n=rr[t])!=null?n:rr.default},jn=(t,n,r)=>{var i,a,u;if(n!=null&&n.render){let c=n.render({config:t,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat}),v=p("div");v.style.display="none";let d=p("span"),f=p("span"),h=p("button");h.style.display="none";let C=p("div");return C.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:f,closeButton:h,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=n==null?void 0:n.layout)!=null?i:"default",s=kr(e)({config:t,showClose:(u=(a=n==null?void 0:n.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 n&&(n.showIcon===!1&&(s.iconHolder.style.display="none"),n.showTitle===!1&&(s.headerTitle.style.display="none"),n.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(s.closeButton.style.display="none"),n.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var za=t=>{switch(t){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},qn=t=>{var Ht,Oe,te,ye,Be,Fe,ze,Ot,de,G,ot,wt,Tt,vt,zt,ee,ke,yt,ce,xe,Je,Bt,Mt,_t,z,et,F,Q,se,$e;let{config:n}=t,r=p("div","tvw-widget-footer tvw-border-t-cw-divider tvw-bg-cw-surface tvw-px-6 tvw-py-4"),e=p("div","tvw-mb-3 tvw-flex tvw-flex-wrap tvw-gap-2"),o=p("form","tvw-widget-composer tvw-flex tvw-flex-col tvw-gap-2 tvw-rounded-2xl tvw-border tvw-border-gray-200 tvw-bg-cw-input-background tvw-px-4 tvw-py-3");o.style.outline="none";let s=p("textarea");s.placeholder=(Oe=(Ht=n==null?void 0:n.copy)==null?void 0:Ht.inputPlaceholder)!=null?Oe:"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=(ye=(te=n==null?void 0:n.theme)==null?void 0:te.inputFontFamily)!=null?ye:"sans-serif",a=(Fe=(Be=n==null?void 0:n.theme)==null?void 0:Be.inputFontWeight)!=null?Fe:"400";s.style.fontFamily=za(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 U=Math.min(s.scrollHeight,v);s.style.height=`${U}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 f=(ze=n==null?void 0:n.sendButton)!=null?ze:{},h=(Ot=f.useIcon)!=null?Ot:!1,C=(de=f.iconText)!=null?de:"\u2191",b=f.iconName,E=(G=f.tooltipText)!=null?G:"Send message",x=(ot=f.showTooltip)!=null?ot:!1,P=(wt=f.size)!=null?wt:"40px",Y=f.backgroundColor,T=f.textColor,I=p("div","tvw-send-button-wrapper"),M=p("button",h?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(M.type="submit",h){if(M.style.width=P,M.style.height=P,M.style.minWidth=P,M.style.minHeight=P,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",b){let U=parseFloat(P)||24,Ee=T&&typeof T=="string"&&T.trim()?T.trim():"currentColor",je=re(b,U,Ee,2);je?(M.appendChild(je),M.style.color=Ee):(M.textContent=C,T?M.style.color=T:M.classList.add("tvw-text-white"))}else M.textContent=C,T?M.style.color=T:M.classList.add("tvw-text-white");Y?M.style.backgroundColor=Y:M.classList.add("tvw-bg-cw-primary")}else M.textContent=(vt=(Tt=n==null?void 0:n.copy)==null?void 0:Tt.sendButtonLabel)!=null?vt:"Send",T?M.style.color=T:M.classList.add("tvw-text-white");if(f.borderWidth&&(M.style.borderWidth=f.borderWidth,M.style.borderStyle="solid"),f.borderColor&&(M.style.borderColor=f.borderColor),f.paddingX?(M.style.paddingLeft=f.paddingX,M.style.paddingRight=f.paddingX):(M.style.paddingLeft="",M.style.paddingRight=""),f.paddingY?(M.style.paddingTop=f.paddingY,M.style.paddingBottom=f.paddingY):(M.style.paddingTop="",M.style.paddingBottom=""),x&&E){let U=p("div","tvw-send-button-tooltip");U.textContent=E,I.appendChild(U)}I.appendChild(M);let R=(zt=n==null?void 0:n.voiceRecognition)!=null?zt:{},ie=R.enabled===!0,K=null,q=null,V=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ie&&V){q=p("div","tvw-send-button-wrapper"),K=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),K.type="button",K.setAttribute("aria-label","Start voice recognition");let U=(ee=R.iconName)!=null?ee:"mic",Ee=(ke=R.iconSize)!=null?ke:P,je=parseFloat(Ee)||24,Ce=(yt=R.backgroundColor)!=null?yt:Y,D=(ce=R.iconColor)!=null?ce:T;K.style.width=Ee,K.style.height=Ee,K.style.minWidth=Ee,K.style.minHeight=Ee,K.style.fontSize="18px",K.style.lineHeight="1";let Te=D||"currentColor",Xe=re(U,je,Te,1.5);Xe?(K.appendChild(Xe),K.style.color=Te):(K.textContent="\u{1F3A4}",K.style.color=Te),Ce?K.style.backgroundColor=Ce:K.classList.add("tvw-bg-cw-primary"),D?K.style.color=D:!D&&!T&&K.classList.add("tvw-text-white"),R.borderWidth&&(K.style.borderWidth=R.borderWidth,K.style.borderStyle="solid"),R.borderColor&&(K.style.borderColor=R.borderColor),R.paddingX&&(K.style.paddingLeft=R.paddingX,K.style.paddingRight=R.paddingX),R.paddingY&&(K.style.paddingTop=R.paddingY,K.style.paddingBottom=R.paddingY),q.appendChild(K);let lt=(xe=R.tooltipText)!=null?xe:"Start voice recognition";if(((Je=R.showTooltip)!=null?Je:!1)&&lt){let pn=p("div","tvw-send-button-tooltip");pn.textContent=lt,q.appendChild(pn)}}let N=(Bt=n==null?void 0:n.attachments)!=null?Bt:{},me=N.enabled===!0,_=null,J=null,X=null,$=null;if(me){$=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$.style.display="none",X=p("input"),X.type="file",X.accept=((Mt=N.allowedTypes)!=null?Mt:wn).join(","),X.multiple=((_t=N.maxFiles)!=null?_t:4)>1,X.style.display="none",X.setAttribute("aria-label","Attach files"),J=p("div","tvw-send-button-wrapper"),_=p("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",(z=N.buttonTooltipText)!=null?z:"Attach file");let U=(et=N.buttonIconName)!=null?et:"paperclip",Ee=P,je=parseFloat(Ee)||40,Ce=Math.round(je*.6);_.style.width=Ee,_.style.height=Ee,_.style.minWidth=Ee,_.style.minHeight=Ee,_.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 D=re(U,Ce,"currentColor",1.5);D?_.appendChild(D):_.textContent="\u{1F4CE}",_.addEventListener("click",lt=>{lt.preventDefault(),X==null||X.click()}),J.appendChild(_);let Te=(F=N.buttonTooltipText)!=null?F:"Attach file",Xe=p("div","tvw-send-button-tooltip");Xe.textContent=Te,J.appendChild(Xe)}o.addEventListener("click",U=>{U.target!==M&&U.target!==I&&U.target!==K&&U.target!==q&&U.target!==_&&U.target!==J&&s.focus()}),$&&($.style.gap="8px",o.append($)),X&&o.append(X),o.append(s);let ae=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),fe=p("div","tvw-flex tvw-items-center tvw-gap-2");J&&fe.append(J);let He=p("div","tvw-flex tvw-items-center tvw-gap-1");q&&He.append(q),He.append(I),ae.append(fe,He),o.append(ae);let St=p("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),ht=(Q=n==null?void 0:n.statusIndicator)!=null?Q:{},Et=(se=ht.visible)!=null?se:!0;return St.style.display=Et?"":"none",St.textContent=($e=ht.idleText)!=null?$e:"Online",r.append(e,o,St),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:M,sendButtonWrapper:I,micButton:K,micButtonWrapper:q,statusText:St,attachmentButton:_,attachmentButtonWrapper:J,attachmentInput:X,attachmentPreviewsContainer:$,actionsRow:ae,leftActions:fe,rightActions:He}};var Gi=t=>{var u,c,v,d,f,h,C;if(!((c=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?c:!0)){let b=p("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=p("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),x=(d=(v=t==null?void 0:t.launcher)==null?void 0:v.width)!=null?d:"100%";return b.style.width=x,E.style.width="100%",b.appendChild(E),{wrapper:b,panel:E}}let r=(f=t==null?void 0:t.launcher)!=null?f:{},e=r.position&&Vt[r.position]?Vt[r.position]:Vt["bottom-right"],o=p("div",`tvw-widget-wrapper tvw-fixed ${e} tvw-z-50 tvw-transition`),s=p("div","tvw-widget-panel tvw-relative tvw-min-h-[320px]"),i=(C=(h=t==null?void 0:t.launcher)==null?void 0:h.width)!=null?C:t==null?void 0:t.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}},Qi=(t,n=!0)=>{var h,C,b,E,x,P,Y;let r=p("div","tvw-widget-container tvw-flex tvw-h-full tvw-w-full tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-bg-cw-surface tvw-text-cw-primary tvw-rounded-2xl tvw-overflow-hidden tvw-border tvw-border-cw-border"),e=(h=t==null?void 0:t.layout)==null?void 0:h.header,o=((C=t==null?void 0:t.layout)==null?void 0:C.showHeader)!==!1,s=e?jn(t,e,{showClose:n}):cn({config:t,showClose:n}),i=p("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=p("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),u=p("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(E=(b=t==null?void 0:t.copy)==null?void 0:b.welcomeTitle)!=null?E:"Hello \u{1F44B}";let c=p("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(P=(x=t==null?void 0:t.copy)==null?void 0:x.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",a.append(u,c);let v=p("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=qn({config:t}),f=((Y=t==null?void 0:t.layout)==null?void 0:Y.showFooter)!==!1;return o?kn(r,s,t):(s.header.style.display="none",kn(r,s,t)),r.append(i),f||(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 Ja=320,Ka=320,Ya=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Va=(t,n,r)=>{if(t.length===0)return null;try{let e=p("div","tvw-flex tvw-flex-col tvw-gap-2");e.setAttribute("data-message-attachments","images"),n&&(e.style.marginBottom="8px");let o=0,s=!1,i=()=>{s||(s=!0,e.remove(),r==null||r())};return t.forEach((a,u)=>{var d;let c=p("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=`${Ja}px`,c.style.maxHeight=`${Ka}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}},Wn=()=>{let t=document.createElement("div");t.className="tvw-flex tvw-items-center tvw-space-x-1 tvw-h-5 tvw-mt-2";let n=document.createElement("div");n.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",n.style.animationDelay="0ms";let r=document.createElement("div");r.className="tvw-bg-cw-primary tvw-animate-typing tvw-rounded-full tvw-h-1.5 tvw-w-1.5",r.style.animationDelay="250ms";let 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",t.appendChild(n),t.appendChild(r),t.appendChild(e),t.appendChild(o),t},Wr=(t,n,r)=>{let e={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:Wn};if(n){let o=n(e);if(o!==null)return o}return Wn()},Xa=(t,n)=>{let r=p("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=n==="user"?t.userAvatar:t.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=p("img");o.src=e,o.alt=n==="user"?"User":"Assistant",o.className="tvw-w-full tvw-h-full tvw-rounded-full tvw-object-cover",r.appendChild(o)}else r.textContent=e,r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");else r.textContent=n==="user"?"U":"A",r.classList.add(n==="user"?"tvw-bg-cw-accent":"tvw-bg-cw-primary","tvw-text-white");return r},Zi=(t,n)=>{let r=p("div","tvw-text-xs tvw-text-cw-muted"),e=new Date(t.createdAt);return n.format?r.textContent=n.format(e):r.textContent=e.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Ga=(t,n="bubble")=>{let r=["vanilla-message-bubble","tvw-max-w-[85%]"];switch(n){case"flat":t==="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"),t==="user"?r.push("vanilla-message-user-bubble","tvw-ml-auto","tvw-bg-cw-accent","tvw-text-white","tvw-px-3","tvw-py-2","tvw-rounded-lg"):r.push("vanilla-message-assistant-bubble","tvw-bg-cw-surface","tvw-text-cw-primary","tvw-px-3","tvw-py-2","tvw-rounded-lg");break;case"bubble":default:r.push("tvw-rounded-2xl","tvw-text-sm","tvw-leading-relaxed","tvw-shadow-sm"),t==="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},Pr=(t,n,r)=>{var h,C,b,E,x,P;let e=(h=n.showCopy)!=null?h:!0,o=(C=n.showUpvote)!=null?C:!0,s=(b=n.showDownvote)!=null?b:!0,i=(E=n.visibility)!=null?E:"hover",a=(x=n.align)!=null?x:"right",u=(P=n.layout)!=null?P:"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=p("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-${t.id}`,d.setAttribute("data-actions-for",t.id);let f=(Y,T,I)=>{let M=document.createElement("button");M.className="tvw-message-action-btn",M.setAttribute("aria-label",T),M.setAttribute("title",T),M.setAttribute("data-action",I);let R=re(Y,14,"currentColor",2);return R&&M.appendChild(R),M};return e&&d.appendChild(f("copy","Copy message","copy")),o&&d.appendChild(f("thumbs-up","Upvote","upvote")),s&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},Un=(t,n,r,e,o,s)=>{var q,V,N,me,_,J,X;let i=r!=null?r:{},a=(q=i.layout)!=null?q:"bubble",u=i.avatar,c=i.timestamp,v=(V=u==null?void 0:u.show)!=null?V:!1,d=(N=c==null?void 0:c.show)!=null?N:!1,f=(me=u==null?void 0:u.position)!=null?me:"left",h=(_=c==null?void 0:c.position)!=null?_:"below",C=Ga(t.role,a),b=p("div",C.join(" "));b.id=`bubble-${t.id}`,b.setAttribute("data-message-id",t.id);let E=Ya(t),x=(X=(J=t.content)==null?void 0:J.trim())!=null?X:"",Y=E.length>0&&x===Zs,T=document.createElement("div"),I=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),M=null;if(Y?(M=document.createElement("div"),M.innerHTML=I,M.style.display="none",T.appendChild(M)):T.innerHTML=I,d&&h==="inline"&&t.createdAt){let $=Zi(t,c);$.classList.add("tvw-ml-2","tvw-inline"),T.appendChild($)}if(E.length>0){let $=Va(E,!Y&&!!x,()=>{Y&&M&&(M.style.display="")});$?b.appendChild($):Y&&M&&(M.style.display="")}if(b.appendChild(T),d&&h==="below"&&t.createdAt){let $=Zi(t,c);$.classList.add("tvw-mt-1"),b.appendChild($)}if(t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let $=Wr("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);$&&b.appendChild($)}if(t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let $=Pr(t,e,o);b.appendChild($)}if(!v||t.role==="system")return b;let ie=p("div",`tvw-flex tvw-gap-2 ${t.role==="user"?"tvw-flex-row-reverse":""}`),K=Xa(u,t.role);return f==="right"||f==="left"&&t.role==="user"?ie.append(b,K):ie.append(K,b),b.classList.remove("tvw-max-w-[85%]"),b.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ie},ea=(t,n,r,e,o,s)=>{let i=r!=null?r:{};return t.role==="user"&&i.renderUserMessage?i.renderUserMessage({message:t,config:{},streaming:!!t.streaming}):t.role==="assistant"&&i.renderAssistantMessage?i.renderAssistantMessage({message:t,config:{},streaming:!!t.streaming}):Un(t,n,r,e,o,s)};var zn=new Set,ta=(t,n)=>{let r=zn.has(t),e=n.querySelector('button[data-expand-header="true"]'),o=n.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=re(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},Hr=t=>{let n=t.reasoning,r=p("div",["vanilla-message-bubble","vanilla-reasoning-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(r.id=`bubble-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let e=zn.has(t.id),o=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=p("div","tvw-flex tvw-flex-col tvw-text-left"),i=p("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=p("span","tvw-text-xs tvw-text-cw-primary");a.textContent=Hi(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let u=p("div","tvw-flex tvw-items-center"),v=re(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=p("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let f=p("div","tvw-border-t tvw-px-4 tvw-py-3");f.style.display=e?"":"none";let h=n.chunks.join(""),C=p("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return C.textContent=h||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(C),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let x=re(e?"chevron-up":"chevron-down",16,"currentColor",2);x?u.appendChild(x):u.textContent=e?"Hide":"Show",f.style.display=e?"":"none"})(),r.append(o,f),r};var Jn=new Set,na=(t,n,r)=>{var c;let e=Jn.has(t),o=(c=r==null?void 0:r.toolCall)!=null?c:{},s=n.querySelector('button[data-expand-header="true"]'),i=n.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=re(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Br=(t,n)=>{var b;let r=t.toolCall,e=(b=n==null?void 0:n.toolCall)!=null?b:{},o=p("div",["vanilla-message-bubble","vanilla-tool-bubble","tvw-w-full","tvw-max-w-[85%]","tvw-rounded-2xl","tvw-bg-cw-surface","tvw-border","tvw-border-cw-message-border","tvw-text-cw-primary","tvw-shadow-sm","tvw-overflow-hidden","tvw-px-0","tvw-py-0"].join(" "));if(o.id=`bubble-${t.id}`,o.setAttribute("data-message-id",t.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=Jn.has(t.id),i=p("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),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=p("div","tvw-flex tvw-flex-col tvw-text-left"),u=p("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Bi(r),a.appendChild(u);let c=p("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=re(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):c.textContent=s?"Hide":"Show";let f=p("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(c),i.append(a,f);let h=p("div","tvw-border-t tvw-space-y-3 tvw-px-4 tvw-py-3");if(h.style.display=s?"":"none",e.contentBackgroundColor&&(h.style.backgroundColor=e.contentBackgroundColor),e.contentTextColor&&(h.style.color=e.contentTextColor),e.contentPaddingX&&(h.style.paddingLeft=e.contentPaddingX,h.style.paddingRight=e.contentPaddingX),e.contentPaddingY&&(h.style.paddingTop=e.contentPaddingY,h.style.paddingBottom=e.contentPaddingY),r.name){let E=p("div","tvw-text-xs tvw-text-cw-muted tvw-italic");e.contentTextColor?E.style.color=e.contentTextColor:e.headerTextColor&&(E.style.color=e.headerTextColor),E.textContent=r.name,h.appendChild(E)}if(r.args!==void 0){let E=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Arguments";let P=p("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(P.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(P.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(P.style.color=e.codeBlockTextColor),P.textContent=As(r.args),E.append(x,P),h.appendChild(E)}if(r.chunks&&r.chunks.length){let E=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Activity";let P=p("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(P.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(P.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(P.style.color=e.codeBlockTextColor),P.textContent=r.chunks.join(`
16
- `),E.append(x,P),h.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=p("div","tvw-space-y-1"),x=p("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(x.style.color=e.labelTextColor),x.textContent="Result";let P=p("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");P.style.fontSize="0.75rem",P.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(P.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(P.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(P.style.color=e.codeBlockTextColor),P.textContent=As(r.result),E.append(x,P),h.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=p("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(E.style.color=e.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,h.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=e.toggleTextColor||e.headerTextColor||"currentColor",x=re(s?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",h.style.display=s?"":"none"})(),o.append(i,h),o};var Rr=(t,n)=>{var b,E,x,P,Y,T,I,M,R,ie,K;let r=t.approval,e=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(r==null?void 0:r.status)==="pending",s=p("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-${t.id}`,s.setAttribute("data-message-id",t.id),e!=null&&e.backgroundColor&&(s.style.backgroundColor=e.backgroundColor),e!=null&&e.borderColor&&(s.style.borderColor=e.borderColor),!r)return s;let i=p("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=p("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":(b=e==null?void 0:e.titleColor)!=null?b:"currentColor",v=re(u,20,c,2);v&&a.appendChild(v);let d=p("div","tvw-flex-1 tvw-min-w-0"),f=p("div","tvw-flex tvw-items-center tvw-gap-2"),h=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary");if(e!=null&&e.titleColor&&(h.style.color=e.titleColor),h.textContent=(E=e==null?void 0:e.title)!=null?E:"Approval Required",f.appendChild(h),!o){let q=p("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");q.setAttribute("data-approval-status",r.status),r.status==="approved"?(q.className+=" tvw-approval-badge-approved",q.textContent="Approved"):r.status==="denied"?(q.className+=" tvw-approval-badge-denied",q.textContent="Denied"):r.status==="timeout"&&(q.className+=" tvw-approval-badge-timeout",q.textContent="Timeout"),f.appendChild(q)}d.appendChild(f);let C=p("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,d.appendChild(C),r.parameters){let q=p("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&&(q.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(q.style.color=e.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=As(r.parameters),d.appendChild(q)}if(o){let q=p("div","tvw-flex tvw-gap-2 tvw-mt-2");q.setAttribute("data-approval-buttons","true");let V=p("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");V.type="button",V.style.backgroundColor=(x=e==null?void 0:e.approveButtonColor)!=null?x:"#16a34a",V.style.color=(P=e==null?void 0:e.approveButtonTextColor)!=null?P:"#ffffff",V.setAttribute("data-approval-action","approve");let N=re("shield-check",14,(Y=e==null?void 0:e.approveButtonTextColor)!=null?Y:"#ffffff",2);N&&(N.style.marginRight="4px",V.appendChild(N));let me=document.createTextNode((T=e==null?void 0:e.approveLabel)!=null?T:"Approve");V.appendChild(me);let _=p("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");_.type="button",_.style.backgroundColor=(I=e==null?void 0:e.denyButtonColor)!=null?I:"transparent",_.style.color=(M=e==null?void 0:e.denyButtonTextColor)!=null?M:"#dc2626",_.style.border=`1px solid ${(R=e==null?void 0:e.denyButtonTextColor)!=null?R:"#fca5a5"}`,_.setAttribute("data-approval-action","deny");let J=re("shield-x",14,(ie=e==null?void 0:e.denyButtonTextColor)!=null?ie:"#dc2626",2);J&&(J.style.marginRight="4px",_.appendChild(J));let X=document.createTextNode((K=e==null?void 0:e.denyLabel)!=null?K:"Deny");_.appendChild(X),q.append(V,_),d.appendChild(q)}return i.append(a,d),s.appendChild(i),s};var sa=t=>{let n=[];return{buttons:n,render:(e,o,s,i,a)=>{if(t.innerHTML="",n.length=0,!e||!e.length||(i!=null?i:o?o.getMessages():[]).some(h=>h.role==="user"))return;let v=document.createDocumentFragment(),d=o?o.isStreaming():!1,f=h=>{switch(h){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(h=>{let C=p("button","tvw-rounded-button tvw-bg-cw-surface tvw-px-3 tvw-py-1.5 tvw-text-xs tvw-font-medium tvw-text-cw-muted hover:tvw-opacity-90 tvw-cursor-pointer tvw-border tvw-border-gray-200");C.type="button",C.textContent=h,C.disabled=d,a!=null&&a.fontFamily&&(C.style.fontFamily=f(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(h))}),v.appendChild(C),n.push(C)}),t.appendChild(v)}}};var Ts=class{constructor(n=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=r}push(n){var r;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(r=this.store)==null||r.put(n)}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 n=await this.store.getAll();if(n.length===0)return 0;let r=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;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=n.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let r=this.getAll();return n>=r.length?r:r.slice(r.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ms=class{constructor(n="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=r}open(){return new Promise((n,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,n()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)e.put(o)}catch{}}getAll(){return new Promise((n,r)=>{if(!this.db){n([]);return}try{let i=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();i.onsuccess=()=>{n(i.result)},i.onerror=()=>{r(i.error)}}catch(e){r(e)}})}getCount(){return new Promise((n,r)=>{if(!this.db){n(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{n(s.result)},s.onerror=()=>{r(s.error)}}catch(e){r(e)}})}clear(){return new Promise((n,r)=>{if(!this.db){n();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{n()},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((n,r)=>{try{let e=indexedDB.deleteDatabase(this.dbName);e.onsuccess=()=>{n()},e.onerror=()=>{r(e.error)}}catch(e){r(e)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let e=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)e.put(o)}catch{}}};function Kn(t,n){n&&n.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Qa={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"}},Za={bg:"#f3f4f6",text:"#4b5563"},el=["flowName","stepName","reasoningText","text","name","tool","toolName"],tl=100;function nl(t,n){let r={...Qa,...n};if(r[t])return r[t];for(let e of Object.keys(r))if(e.endsWith("_")&&t.startsWith(e))return r[e];return Za}function sl(t,n){return`+${((t-n)/1e3).toFixed(3)}s`}function rl(t){let n=new Date(t),r=String(n.getHours()).padStart(2,"0"),e=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${r}:${e}:${o}.${s}`}function ol(t,n){try{let r=JSON.parse(t);if(typeof r!="object"||r===null)return null;for(let e of n){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 il(t){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(t):new Promise(r=>{let e=document.createElement("textarea");e.value=t,e.style.position="fixed",e.style.opacity="0",document.body.appendChild(e),e.select(),document.execCommand("copy"),document.body.removeChild(e),r()})}function al(t){let n;try{n=JSON.parse(t.payload)}catch{n=t.payload}return JSON.stringify({type:t.type,timestamp:new Date(t.timestamp).toISOString(),payload:n},null,2)}function ll(t,n,r){let e,o;try{o=JSON.parse(t.payload),e=JSON.stringify(o,null,2)}catch{o=t.payload,e=t.payload}let s=n.find(a=>a.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&r){let a=s.renderEventStreamPayload({event:t,config:r,defaultRenderer:()=>i(),parsedPayload:o});if(a)return a}return i();function i(){let a=p("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=p("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 Fr(t,n,r,e,o,s,i,a){var f;let u=o.has(t.id),c=p("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");Kn(c,(f=e.classNames)==null?void 0:f.eventRow);let v=i.find(h=>h.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let h=v.renderEventStreamRow({event:t,index:n,config:a,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>s(t.id)});if(h)return c.appendChild(h),c}return c.appendChild(d()),c;function d(){var N,me;let h=p("div",""),C=p("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",t.id);let b=p("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=re(u?"chevron-down":"chevron-right","14px","currentColor",2);E&&b.appendChild(E);let x=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),P=(N=e.timestampFormat)!=null?N:"relative";x.textContent=P==="relative"?sl(t.timestamp,r):rl(t.timestamp);let Y=null;e.showSequenceNumbers!==!1&&(Y=p("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),Y.textContent=String(n+1));let T=nl(t.type,e.badgeColors),I=p("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=T.bg,I.style.color=T.text,I.style.borderColor=T.text+"50",I.textContent=t.type;let M=(me=e.descriptionFields)!=null?me:el,R=ol(t.payload,M),ie=null;R&&(ie=p("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ie.textContent=R);let K=p("div","tvw-flex-1 tvw-min-w-0"),q=p("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"),V=re("clipboard","12px","currentColor",1.5);return V&&q.appendChild(V),q.addEventListener("click",async _=>{_.stopPropagation(),await il(al(t)),q.innerHTML="";let J=re("check","12px","currentColor",1.5);J&&q.appendChild(J),setTimeout(()=>{q.innerHTML="";let X=re("clipboard","12px","currentColor",1.5);X&&q.appendChild(X)},1500)}),C.appendChild(b),C.appendChild(x),Y&&C.appendChild(Y),C.appendChild(I),ie&&C.appendChild(ie),C.appendChild(K),C.appendChild(q),h.appendChild(C),u&&h.appendChild(ll(t,i,a)),h}}function ra(t){var c,v;let{buffer:n,getFullHistory:r,onClose:e,config:o,plugins:s=[]}=t,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:n.getAll(),defaultRenderer:()=>u().element,onClose:e});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return u();function u(){let d=i.classNames,f=p("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");Kn(f,d==null?void 0:d.panel);let h=[],C="",b="",E=null,x=[],P={},Y=0,T=!1,I=0,M=0,R=!1,ie=null,K=!1,q=0,V=new Set,N=new Map,me="",_="",J=null,X,$,ae,fe,He;function St(){let F=p("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),Q=p("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");Kn(Q,d==null?void 0:d.headerBar);let se=p("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");se.textContent="Events",X=p("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"),X.textContent="0";let $e=p("div","tvw-flex-1");$=p("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 U=p("option","");U.value="",U.textContent="All events",$.appendChild(U),ae=p("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"),ae.type="button",ae.title="Copy All";let je=re("clipboard-copy","12px","currentColor",1.5);je&&ae.appendChild(je);let Ce=p("span","tvw-text-xs");Ce.textContent="Copy All",ae.appendChild(Ce),Q.appendChild(se),Q.appendChild(X),Q.appendChild($e),Q.appendChild($),Q.appendChild(ae);let D=p("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");Kn(D,d==null?void 0:d.searchBar);let Te=re("search","14px","var(--cw-muted, #9ca3af)",1.5),Xe=p("span","tvw-absolute tvw-left-6 tvw-top-1/2 tvw--translate-y-1/2 tvw-pointer-events-none tvw-flex tvw-items-center");Te&&Xe.appendChild(Te),fe=p("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"),Kn(fe,d==null?void 0:d.searchInput),fe.type="text",fe.placeholder="Search event payloads...",He=p("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"),He.type="button",He.style.display="none";let lt=re("x","12px","currentColor",2);return lt&&He.appendChild(lt),D.appendChild(Xe),D.appendChild(fe),D.appendChild(He),F.appendChild(Q),F.appendChild(D),F}let ht,Et=s.find(F=>F.renderEventStreamToolbar);if(Et!=null&&Et.renderEventStreamToolbar&&o){let F=Et.renderEventStreamToolbar({config:o,defaultRenderer:()=>St(),eventCount:n.getSize(),filteredCount:0,onFilterChange:Q=>{C=Q,ot(),vt()},onSearchChange:Q=>{b=Q,ot(),vt()}});ht=F!=null?F:St()}else ht=St();let Ht=p("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 Oe=p("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),te=p("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");te.style.height="100%";let ye=p("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");Kn(ye,d==null?void 0:d.scrollIndicator),ye.style.display="none";let Be=re("arrow-down","12px","currentColor",2);Be&&ye.appendChild(Be);let Fe=p("span","");ye.appendChild(Fe);let ze=p("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");ze.style.display="none",Oe.appendChild(te),Oe.appendChild(ze),Oe.appendChild(ye),f.setAttribute("tabindex","0"),f.appendChild(ht),f.appendChild(Ht),f.appendChild(Oe);function Ot(){let F=n.getAll(),Q={};for(let Ce of F)Q[Ce.type]=(Q[Ce.type]||0)+1;let se=Object.keys(Q).sort(),$e=se.length!==x.length||!se.every((Ce,D)=>Ce===x[D]),U=!$e&&se.some(Ce=>Q[Ce]!==P[Ce]),Ee=F.length!==Object.values(P).reduce((Ce,D)=>Ce+D,0);if(!$e&&!U&&!Ee||(x=se,P=Q,!$))return;let je=$.value;if($.options[0].textContent="All events",$e){for(;$.options.length>1;)$.remove(1);for(let Ce of se){let D=p("option","");D.value=Ce,D.textContent=`${Ce} (${Q[Ce]||0})`,$.appendChild(D)}je&&se.includes(je)?$.value=je:je&&($.value="",C="")}else for(let Ce=1;Ce<$.options.length;Ce++){let D=$.options[Ce];D.textContent=`${D.value} (${Q[D.value]||0})`}}function de(){let F=n.getAll();if(C&&(F=F.filter(Q=>Q.type===C)),b){let Q=b.toLowerCase();F=F.filter(se=>se.type.toLowerCase().includes(Q)||se.payload.toLowerCase().includes(Q))}return F}function G(){return C!==""||b!==""}function ot(){Y=0,I=0,T=!1,ye.style.display="none"}function wt(F){V.has(F)?V.delete(F):V.add(F),J=F;let Q=te.scrollTop,se=T;K=!0,T=!0,vt(),te.scrollTop=Q,T=se,K=!1}function Tt(){return te.scrollHeight-te.scrollTop-te.clientHeight<=50}function vt(){M=Date.now(),R=!1,Ot();let F=n.getEvictedCount();F>0?(Ht.textContent=`${F.toLocaleString()} older events truncated`,Ht.style.display=""):Ht.style.display="none",h=de();let Q=h.length,se=n.getSize()>0;X&&(X.textContent=String(n.getSize())),Q===0&&se&&G()?(ze.textContent=b?`No events matching '${b}'`:"No events matching filter",ze.style.display="",te.style.display="none"):(ze.style.display="none",te.style.display=""),ae&&(ae.title=G()?`Copy Filtered (${Q})`:"Copy All"),T&&Q>Y&&(I+=Q-Y,Fe.textContent=`${I} new event${I===1?"":"s"}`,ye.style.display=""),Y=Q;let $e=n.getAll(),U=$e.length>0?$e[0].timestamp:0,Ee=new Set(h.map(D=>D.id));for(let D of V)Ee.has(D)||V.delete(D);let je=C!==me||b!==_,Ce=N.size===0&&h.length>0;if(je||Ce||h.length===0){te.innerHTML="",N.clear();let D=document.createDocumentFragment();for(let Te=0;Te<h.length;Te++){let Xe=Fr(h[Te],Te,U,i,V,wt,s,o);N.set(h[Te].id,Xe),D.appendChild(Xe)}te.appendChild(D),me=C,_=b,J=null}else{if(J!==null){let Te=N.get(J);if(Te&&Te.parentNode===te){let Xe=h.findIndex(lt=>lt.id===J);if(Xe>=0){let lt=Fr(h[Xe],Xe,U,i,V,wt,s,o);te.insertBefore(lt,Te),Te.remove(),N.set(J,lt)}}J=null}let D=new Set(h.map(Te=>Te.id));for(let[Te,Xe]of N)D.has(Te)||(Xe.remove(),N.delete(Te));for(let Te=0;Te<h.length;Te++){let Xe=h[Te];if(!N.has(Xe.id)){let lt=Fr(Xe,Te,U,i,V,wt,s,o);N.set(Xe.id,lt),te.appendChild(lt)}}}T||(te.scrollTop=te.scrollHeight)}function zt(){if(Date.now()-M>=tl){ie!==null&&(cancelAnimationFrame(ie),ie=null),vt();return}R||(R=!0,ie=requestAnimationFrame(()=>{ie=null,vt()}))}let ee=(F,Q)=>{if(!ae)return;ae.innerHTML="";let se=re(F,"12px","currentColor",1.5);se&&ae.appendChild(se);let $e=p("span","tvw-text-xs");$e.textContent="Copy All",ae.appendChild($e),setTimeout(()=>{ae.innerHTML="";let U=re("clipboard-copy","12px","currentColor",1.5);U&&ae.appendChild(U);let Ee=p("span","tvw-text-xs");Ee.textContent="Copy All",ae.appendChild(Ee),ae.disabled=!1},Q)},ke=async()=>{if(ae){ae.disabled=!0;try{let F;G()?F=h:r?(F=await r(),F.length===0&&(F=n.getAll())):F=n.getAll();let Q=F.map(se=>{try{return JSON.parse(se.payload)}catch{return se.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),ee("check",1500)}catch{ee("x",1500)}}},yt=()=>{$&&(C=$.value,ot(),vt())},ce=()=>{!fe||!He||(He.style.display=fe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{b=fe.value,ot(),vt()},150))},xe=()=>{!fe||!He||(fe.value="",b="",He.style.display="none",E&&clearTimeout(E),ot(),vt())},Je=()=>{if(K)return;let F=te.scrollTop,Q=F>q;q=F,Tt()&&Q?(T=!1,I=0,ye.style.display="none"):Tt()||(T=!0)},Bt=F=>{F.deltaY<0&&(T=!0)},Mt=()=>{te.scrollTop=te.scrollHeight,T=!1,I=0,ye.style.display="none"},_t=F=>{let Q=F.target;if(!Q||Q.closest("button"))return;let se=Q.closest("[data-event-id]");if(!se)return;let $e=se.getAttribute("data-event-id");$e&&wt($e)},z=F=>{if((F.metaKey||F.ctrlKey)&&F.key==="f"){F.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}F.key==="Escape"&&(fe&&document.activeElement===fe?(xe(),fe.blur(),f.focus()):e&&e())};ae&&ae.addEventListener("click",ke),$&&$.addEventListener("change",yt),fe&&fe.addEventListener("input",ce),He&&He.addEventListener("click",xe),te.addEventListener("scroll",Je),te.addEventListener("wheel",Bt,{passive:!0}),te.addEventListener("click",_t),ye.addEventListener("click",Mt),f.addEventListener("keydown",z);function et(){E&&clearTimeout(E),ie!==null&&(cancelAnimationFrame(ie),ie=null),R=!1,N.clear(),ae&&ae.removeEventListener("click",ke),$&&$.removeEventListener("change",yt),fe&&fe.removeEventListener("input",ce),He&&He.removeEventListener("click",xe),te.removeEventListener("scroll",Je),te.removeEventListener("wheel",Bt),te.removeEventListener("click",_t),ye.removeEventListener("click",Mt),f.removeEventListener("keydown",z)}return{element:f,update:zt,destroy:et}}}var oa={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"}},$r=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,b,E;if(s.dataset.enhanced==="true")return;let i=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let a=(b=oa[i])!=null?b:oa.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=p("div","tvw-space-y-1"),c=p("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let x=p("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 M,R;let P=p("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");P.htmlFor=`${n.id}-${i}-${x.name}`;let Y=p("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");Y.textContent=x.label,P.appendChild(Y);let T=(M=x.type)!=null?M:"text",I;T==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=T),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=`${n.id}-${i}-${x.name}`,I.name=x.name,I.placeholder=(R=x.placeholder)!=null?R:"",x.required&&(I.required=!0),P.appendChild(I),v.appendChild(P)});let d=p("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=p("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),h=p("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");h.type="submit",h.textContent=(E=a.submitLabel)!=null?E:"Submit",d.appendChild(f),d.appendChild(h),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async x=>{var I,M;x.preventDefault();let P=(I=r.formEndpoint)!=null?I:"/form",Y=new FormData(v),T={};Y.forEach((R,ie)=>{T[ie]=R}),T.type=i,h.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(P,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let ie=await R.json();f.textContent=(M=ie.message)!=null?M:"Thanks! We'll be in touch soon.",ie.success&&ie.nextPrompt&&await e.sendMessage(String(ie.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{h.disabled=!1}})})};var Or=class{constructor(){this.plugins=new Map}register(n){var r;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(r=n.onRegister)==null||r.call(n)}unregister(n){var e;let r=this.plugins.get(n);r&&((e=r.onUnregister)==null||e.call(r),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,r)=>{var e,o;return((e=r.priority)!=null?e:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let r=this.getAll();if(!n||n.length===0)return r;let e=new Set(n.map(s=>s.id));return[...r.filter(s=>!e.has(s.id)),...n].sort((s,i)=>{var a,u;return((a=i.priority)!=null?a:0)-((u=s.priority)!=null?u:0)})}clear(){this.plugins.forEach(n=>{var r;return(r=n.onUnregister)==null?void 0:r.call(n)}),this.plugins.clear()}},Ls=new Or;var Nr={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"},Dr={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"},tt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Nr,darkTheme:Dr,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 or(t){var n,r,e,o,s,i,a,u,c,v,d,f,h,C,b,E,x,P,Y;return t?{...tt,...t,theme:{...tt.theme,...t.theme},darkTheme:{...tt.darkTheme,...t.darkTheme},launcher:{...tt.launcher,...t.launcher,clearChat:{...(n=tt.launcher)==null?void 0:n.clearChat,...(r=t.launcher)==null?void 0:r.clearChat}},copy:{...tt.copy,...t.copy},sendButton:{...tt.sendButton,...t.sendButton},statusIndicator:{...tt.statusIndicator,...t.statusIndicator},voiceRecognition:{...tt.voiceRecognition,...t.voiceRecognition},features:{...tt.features,...t.features},suggestionChips:(e=t.suggestionChips)!=null?e:tt.suggestionChips,suggestionChipsConfig:{...tt.suggestionChipsConfig,...t.suggestionChipsConfig},layout:{...tt.layout,...t.layout,header:{...(o=tt.layout)==null?void 0:o.header,...(s=t.layout)==null?void 0:s.header},messages:{...(i=tt.layout)==null?void 0:i.messages,...(a=t.layout)==null?void 0:a.messages,avatar:{...(c=(u=tt.layout)==null?void 0:u.messages)==null?void 0:c.avatar,...(d=(v=t.layout)==null?void 0:v.messages)==null?void 0:d.avatar},timestamp:{...(h=(f=tt.layout)==null?void 0:f.messages)==null?void 0:h.timestamp,...(b=(C=t.layout)==null?void 0:C.messages)==null?void 0:b.timestamp}},slots:{...(E=tt.layout)==null?void 0:E.slots,...(x=t.layout)==null?void 0:x.slots}},markdown:{...tt.markdown,...t.markdown,options:{...(P=tt.markdown)==null?void 0:P.options,...(Y=t.markdown)==null?void 0:Y.options}},messageActions:{...tt.messageActions,...t.messageActions}}:tt}var ia=()=>{let t=new Map,n=(o,s)=>(t.has(o)||t.set(o,new Set),t.get(o).add(s),()=>r(o,s)),r=(o,s)=>{var i;(i=t.get(o))==null||i.delete(s)};return{on:n,off:r,emit:(o,s)=>{var i;(i=t.get(o))==null||i.forEach(a=>{try{a(s)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var dl=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},cl=t=>{let n=t.trim(),r=n.indexOf("{");if(r===-1)return null;let e=0;for(let o=r;o<n.length;o+=1){let s=n[o];if(s==="{"&&(e+=1),s==="}"&&(e-=1,e===0))return n.slice(r,o+1)}return null},Is=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=dl(t),r=cl(n);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}},_r=t=>typeof t=="string"?t:t==null?"":String(t),Pn={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:_r(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=_r(r.element);if(e&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(e);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",e)}return{handled:!0,displayText:_r(r.text)}}},aa=t=>Array.isArray(t)?t.map(n=>String(n)):[],ks=t=>{let n=new Set(aa(t.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(aa(t.getSessionMetadata().processedActionMessageIds))},e=()=>{let s=Array.from(n);t.updateSessionMetadata(i=>({...i,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let i=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!i&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let a=i?t.parsers.reduce((c,v)=>c||(v==null?void 0:v({text:i,message:s.message}))||null,null):null;if(!a)return null;n.add(s.message.id),e();let u={action:a,message:s.message};t.emit("action:detected",u);for(let c of t.handlers)if(c)try{let v=()=>{t.emit("action:resubmit",u)},d=c(a,{message:s.message,metadata:t.getSessionMetadata(),updateMetadata:t.updateSessionMetadata,document:t.documentRef,triggerResubmit:v});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(v){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",v)}return{text:"",persist:!0}},syncFromMetadata:r}};var ul=t=>{if(!t)return null;try{return JSON.parse(t)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},pl=t=>t.map(n=>({...n,streaming:!1})),ir=(t="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ul(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?pl(r.messages):void 0};e.setItem(t,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let r=n();if(r)try{r.removeItem(t)}catch(e){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",e)}}}};var jr=class{constructor(){this.components=new Map}register(n,r){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,r)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([r,e])=>{this.register(r,e)})}},Yn=new jr;var Vn=require("partial-json");function gl(t){if(!t||typeof t!="object"||!("component"in t))return!1;let n=t.component;return typeof n=="string"&&n.length>0}function ml(t,n){if(!gl(t))return null;let r=t.props&&typeof t.props=="object"&&t.props!==null?t.props:{};return{component:t.component,props:r,raw:n}}function ar(){let t=null,n=0;return{getExtractedDirective:()=>t,processChunk:r=>{let e=r.trim();if(!e.startsWith("{")&&!e.startsWith("["))return null;if(r.length<=n)return t;try{let o=(0,Vn.parse)(r,Vn.STR|Vn.OBJ),s=ml(o,r);s&&(t=s)}catch{}return n=r.length,t},reset:()=>{t=null,n=0}}}function la(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function lr(t,n){let{config:r,message:e,onPropsUpdate:o}=n,s=Yn.get(t.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${t.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(t.props,i)}catch(a){return console.error(`[ComponentMiddleware] Error rendering component "${t.component}":`,a),null}}function da(){let t=ar();return{processChunk:n=>t.processChunk(n),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function dr(t){if(!t.rawContent)return!1;try{let n=JSON.parse(t.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function cr(t){if(!t.rawContent)return null;try{let n=JSON.parse(t.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:t.rawContent}}catch{}return null}var fl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ur(t){let{onSubmit:n,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=fl}=t,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,f=document.createElement("div");f.className="tvw-feedback-content";let h=document.createElement("div");h.className="tvw-feedback-header";let C=document.createElement("h3");C.className="tvw-feedback-title",C.textContent=e,h.appendChild(C);let b=document.createElement("p");b.className="tvw-feedback-subtitle",b.textContent=o,h.appendChild(b),f.appendChild(h);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let M=1;M<=5;M++){let R=document.createElement("button");R.type="button",R.className="tvw-feedback-rating-btn tvw-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${M} star${M>1?"s":""}: ${c[M-1]}`),R.title=c[M-1],R.dataset.rating=String(M),R.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
- `,R.addEventListener("click",()=>{d=M,x.forEach((ie,K)=>{let q=K<M;ie.classList.toggle("selected",q),ie.setAttribute("aria-checked",K===M-1?"true":"false")})}),x.push(R),E.appendChild(R)}f.appendChild(E);let P=null;if(u){let M=document.createElement("div");M.className="tvw-feedback-comment-container",P=document.createElement("textarea"),P.className="tvw-feedback-comment",P.placeholder=s,P.rows=3,P.setAttribute("aria-label","Additional comments"),M.appendChild(P),f.appendChild(M)}let Y=document.createElement("div");Y.className="tvw-feedback-actions";let T=document.createElement("button");T.type="button",T.className="tvw-feedback-btn tvw-feedback-btn-skip",T.textContent=a,T.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){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let M=(P==null?void 0:P.value.trim())||void 0;await n(d,M),v.remove()}catch(M){I.disabled=!1,I.textContent=i,console.error("[CSAT Feedback] Failed to submit:",M)}}),Y.appendChild(T),Y.appendChild(I),f.appendChild(Y),v.appendChild(f),v}function pr(t){let{onSubmit:n,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"}=t,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 f=null,h=document.createElement("div");h.className="tvw-feedback-content";let C=document.createElement("div");C.className="tvw-feedback-header";let b=document.createElement("h3");b.className="tvw-feedback-title",b.textContent=e,C.appendChild(b);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,C.appendChild(E),h.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 P=document.createElement("div");P.className="tvw-feedback-labels";let Y=document.createElement("span");Y.className="tvw-feedback-label-low",Y.textContent=c;let T=document.createElement("span");T.className="tvw-feedback-label-high",T.textContent=v,P.appendChild(Y),P.appendChild(T);let I=document.createElement("div");I.className="tvw-feedback-numbers";let M=[];for(let V=0;V<=10;V++){let N=document.createElement("button");N.type="button",N.className="tvw-feedback-rating-btn tvw-feedback-number-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`Rating ${V} out of 10`),N.textContent=String(V),N.dataset.rating=String(V),V<=6?N.classList.add("tvw-feedback-detractor"):V<=8?N.classList.add("tvw-feedback-passive"):N.classList.add("tvw-feedback-promoter"),N.addEventListener("click",()=>{f=V,M.forEach((me,_)=>{me.classList.toggle("selected",_===V),me.setAttribute("aria-checked",_===V?"true":"false")})}),M.push(N),I.appendChild(N)}x.appendChild(P),x.appendChild(I),h.appendChild(x);let R=null;if(u){let V=document.createElement("div");V.className="tvw-feedback-comment-container",R=document.createElement("textarea"),R.className="tvw-feedback-comment",R.placeholder=s,R.rows=3,R.setAttribute("aria-label","Additional comments"),V.appendChild(R),h.appendChild(V)}let ie=document.createElement("div");ie.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(),d.remove()});let q=document.createElement("button");return q.type="button",q.className="tvw-feedback-btn tvw-feedback-btn-submit",q.textContent=i,q.addEventListener("click",async()=>{if(f===null){I.classList.add("tvw-feedback-shake"),setTimeout(()=>I.classList.remove("tvw-feedback-shake"),500);return}q.disabled=!0,q.textContent="Submitting...";try{let V=(R==null?void 0:R.value.trim())||void 0;await n(f,V),d.remove()}catch(V){q.disabled=!1,q.textContent=i,console.error("[NPS Feedback] Failed to submit:",V)}}),ie.appendChild(K),ie.appendChild(q),h.appendChild(ie),d.appendChild(h),d}var Xn="persona-chat-history",hl=30*1e3,wl={"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 vl(t){var e,o,s;if(!t)return[];let n=[],r=Array.from((e=t.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){n.push(a);continue}let u=(o=wl[a.type])!=null?o:"png";n.push(new File([a],`clipboard-image-${Date.now()}.${u}`,{type:a.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let i of Array.from((s=t.files)!=null?s:[]))i.type.startsWith("image/")&&n.push(i);return n}function yl(t){var n,r,e,o,s,i,a,u,c;return t?t===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=t.storage)!=null?n:"session",keyPrefix:(r=t.keyPrefix)!=null?r:"persona-",persist:{openState:(o=(e=t.persist)==null?void 0:e.openState)!=null?o:!0,voiceState:(i=(s=t.persist)==null?void 0:s.voiceState)!=null?i:!0,focusInput:(u=(a=t.persist)==null?void 0:a.focusInput)!=null?u:!0},clearOnChatClear:(c=t.clearOnChatClear)!=null?c:!0}:null}function bl(t){try{let n=t==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var qr=t=>!t||typeof t!="object"?{}:{...t},ca=t=>t.map(n=>({...n,streaming:!1})),ua=(t,n,r)=>{let e=t!=null&&t.markdown?Ss(t.markdown):null;return o=>{var a,u,c;let s=(a=o.text)!=null?a:"",i=(u=o.message.rawContent)!=null?u:null;if(n){let v=n.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 t!=null&&t.postprocessMessage?t.postprocessMessage({...o,text:s,raw:(c=i!=null?i:o.text)!=null?c:""}):e?e(s):Js(s)}},gr=(t,n,r)=>{var cs,us,ps,gs,ms,fs,hs,j,Ie,De,it,pt,At,st,m,We,B,y,L,oe,Se,Ye,It,rt,bt,gt,Ne,qe,dt,Ue,xt,Nt,Jt;t.id&&t.id!=="persona-root"&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.id="persona-root";let e=or(n),o=Ls.getForInstance(e.plugins);e.components&&Yn.registerAll(e.components);let s=ia(),i=(cs=e.storageAdapter)!=null?cs:ir(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(g=>{let w=g!=null?g:{messages:[],metadata:{}};return c(w)});else{let g=l!=null?l:{messages:[],metadata:{}},w=c(g);w.metadata&&(a=qr(w.metadata)),(us=w.messages)!=null&&us.length&&(e={...e,initialMessages:w.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:{}});(ps=l.messages)!=null&&ps.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var w;a=(w=l({...a}))!=null?w:{},ns()},f=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Is],h=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Pn.message,Pn.messageAndClick],C=ks({parsers:f,handlers:h,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let b=(ms=(gs=e.launcher)==null?void 0:gs.enabled)!=null?ms:!0,E=(hs=(fs=e.launcher)==null?void 0:fs.autoExpand)!=null?hs:!1,x=(j=e.autoFocusInput)!=null?j:!1,P=E,Y=b,T=(De=(Ie=e.layout)==null?void 0:Ie.header)==null?void 0:De.layout,I=b?E:!0,M=!1,R=null,ie=()=>{M=!0,R&&clearTimeout(R),R=setTimeout(()=>{M&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),M=!1)},1e4)},K=ua(e,C,ie),q=(pt=(it=e.features)==null?void 0:it.showReasoning)!=null?pt:!0,V=(st=(At=e.features)==null?void 0:At.showToolCalls)!=null?st:!0,N=(We=(m=e.features)==null?void 0:m.showEventStreamToggle)!=null?We:!1,_=`${(y=typeof e.persistState=="object"?(B=e.persistState)==null?void 0:B.keyPrefix:void 0)!=null?y:"persona-"}event-stream`,J=N?new Ms(_):null,X=(Se=(oe=(L=e.features)==null?void 0:L.eventStream)==null?void 0:oe.maxEvents)!=null?Se:2e3,$=N?new Ts(X,J):null,ae=null,fe=!1,He=null,St=0;J==null||J.open().then(()=>$==null?void 0:$.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ht={onCopy:l=>{var g,w;s.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.id,"copy").catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(w=(g=e.messageActions)==null?void 0:g.onCopy)==null||w.call(g,l)},onFeedback:l=>{var g,w;s.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.messageId,l.type).catch(A=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(w=(g=e.messageActions)==null?void 0:g.onFeedback)==null||w.call(g,l)}},Et=(Ye=e.statusIndicator)!=null?Ye:{},Ht=l=>{var g,w,A,S;return l==="idle"?(g=Et.idleText)!=null?g:Pt.idle:l==="connecting"?(w=Et.connectingText)!=null?w:Pt.connecting:l==="connected"?(A=Et.connectedText)!=null?A:Pt.connected:l==="error"?(S=Et.errorText)!=null?S:Pt.error:Pt[l]},{wrapper:Oe,panel:te}=Gi(e),ye=Qi(e,b),{container:Be,body:Fe,messagesWrapper:ze,suggestions:Ot,textarea:de,sendButton:G,sendButtonWrapper:ot,composerForm:wt,statusText:Tt,introTitle:vt,introSubtitle:zt,closeButton:ee,iconHolder:ke,headerTitle:yt,headerSubtitle:ce,header:xe,footer:Je,actionsRow:Bt,leftActions:Mt,rightActions:_t}=ye,z=ye.micButton,et=ye.micButtonWrapper,F=ye.attachmentButton,Q=ye.attachmentButtonWrapper,se=ye.attachmentInput,$e=ye.attachmentPreviewsContainer,U=null;(It=e.attachments)!=null&&It.enabled&&se&&$e&&(U=In.fromConfig(e.attachments),U.setPreviewsContainer($e),se.addEventListener("change",l=>{let g=l.target;U==null||U.handleFileSelect(g.files),g.value=""}));let Ee=o.find(l=>l.renderHeader);if(Ee!=null&&Ee.renderHeader){let l=Ee.renderHeader({config:e,defaultRenderer:()=>{let g=cn({config:e,showClose:b});return kn(Be,g,e),g.header},onClose:()=>nt(!1,"user")});if(l){let g=Be.querySelector(".tvw-border-b-cw-divider");g&&(g.replaceWith(l),xe=l)}}let je=()=>{var g,w,A,S;if(!$)return;if(fe=!0,!ae&&$&&(ae=ra({buffer:$,getFullHistory:()=>$.getAllFromStore(),onClose:()=>Ce(),config:e,plugins:o})),ae&&(Fe.style.display="none",(g=Je.parentNode)==null||g.insertBefore(ae.element,Je),ae.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 H=(S=(A=(w=e.features)==null?void 0:w.eventStream)==null?void 0:A.classNames)==null?void 0:S.toggleButtonActive;H&&H.split(/\s+/).forEach(he=>he&&D.classList.add(he))}let l=()=>{if(!fe)return;let H=Date.now();H-St>=200&&(ae==null||ae.update(),St=H),He=requestAnimationFrame(l)};St=0,He=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ce=()=>{var l,g,w;if(fe){if(fe=!1,ae&&ae.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=(w=(g=(l=e.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:w.toggleButtonActive;A&&A.split(/\s+/).forEach(S=>S&&D.classList.remove(S))}He!==null&&(cancelAnimationFrame(He),He=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},D=null;if(N){let l=(bt=(rt=e.features)==null?void 0:rt.eventStream)==null?void 0:bt.classNames,g="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=p("button",g),D.style.width="28px",D.style.height="28px",D.type="button",D.setAttribute("aria-label","Event Stream"),D.title="Event Stream";let w=re("activity","18px","currentColor",1.5);w&&D.appendChild(w);let A=ye.clearChatButtonWrapper,S=ye.closeButtonWrapper,H=A||S;H&&H.parentNode===xe?xe.insertBefore(D,H):xe.appendChild(D),D.addEventListener("click",()=>{fe?Ce():je()})}let Te=o.find(l=>l.renderComposer);if(Te!=null&&Te.renderComposer){let l=Te.renderComposer({config:e,defaultRenderer:()=>qn({config:e}).footer,onSubmit:g=>{O&&!O.isStreaming()&&O.sendMessage(g)},disabled:!1});l&&(Je.replaceWith(l),Je=l)}(()=>{var A,S;let l=(S=(A=e.layout)==null?void 0:A.slots)!=null?S:{},g=H=>{switch(H){case"body-top":return Be.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return ze;case"footer-top":return Ot;case"composer":return wt;case"footer-bottom":return Tt;default:return null}},w=(H,he)=>{var le;switch(H){case"header-left":case"header-center":case"header-right":if(H==="header-left")xe.insertBefore(he,xe.firstChild);else if(H==="header-right")xe.appendChild(he);else{let ue=xe.querySelector(".tvw-flex-col");ue?(le=ue.parentNode)==null||le.insertBefore(he,ue.nextSibling):xe.appendChild(he)}break;case"body-top":{let ue=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ue?ue.replaceWith(he):Fe.insertBefore(he,Fe.firstChild);break}case"body-bottom":Fe.appendChild(he);break;case"footer-top":Ot.replaceWith(he);break;case"footer-bottom":Tt.replaceWith(he);break;default:break}};for(let[H,he]of Object.entries(l))if(he)try{let le=he({config:e,defaultContent:()=>g(H)});le&&w(H,le)}catch(le){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${H}":`,le)}})();let lt=l=>{let w=l.target.closest('button[data-expand-header="true"]');if(!w)return;let A=w.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let S=A.getAttribute("data-message-id");if(!S)return;let H=w.getAttribute("data-bubble-type");H==="reasoning"?(zn.has(S)?zn.delete(S):zn.add(S),ta(S,A)):H==="tool"&&(Jn.has(S)?Jn.delete(S):Jn.add(S),na(S,A,e))};ze.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lt(l))}),ze.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),lt(l))});let vn=new Map;ze.addEventListener("click",l=>{var he;let w=l.target.closest(".tvw-message-action-btn[data-action]");if(!w)return;l.preventDefault(),l.stopPropagation();let A=w.closest("[data-actions-for]");if(!A)return;let S=A.getAttribute("data-actions-for");if(!S)return;let H=w.getAttribute("data-action");if(H==="copy"){let ue=O.getMessages().find(be=>be.id===S);if(ue&&ht.onCopy){let be=ue.content||"";navigator.clipboard.writeText(be).then(()=>{w.classList.add("tvw-message-action-success");let pe=re("check",14,"currentColor",2);pe&&(w.innerHTML="",w.appendChild(pe)),setTimeout(()=>{w.classList.remove("tvw-message-action-success");let Ae=re("copy",14,"currentColor",2);Ae&&(w.innerHTML="",w.appendChild(Ae))},2e3)}).catch(pe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",pe)}),ht.onCopy(ue)}}else if(H==="upvote"||H==="downvote")if(((he=vn.get(S))!=null?he:null)===H)vn.delete(S),w.classList.remove("tvw-message-action-active");else{let be=H==="upvote"?"downvote":"upvote",pe=A.querySelector(`[data-action="${be}"]`);pe&&pe.classList.remove("tvw-message-action-active"),vn.set(S,H),w.classList.add("tvw-message-action-active");let ne=O.getMessages().find(k=>k.id===S);ne&&ht.onFeedback&&ht.onFeedback({type:H,messageId:ne.id,message:ne})}}),ze.addEventListener("click",l=>{let w=l.target.closest("button[data-approval-action]");if(!w)return;l.preventDefault(),l.stopPropagation();let A=w.closest(".vanilla-approval-bubble");if(!A)return;let S=A.getAttribute("data-message-id");if(!S)return;let H=w.getAttribute("data-approval-action");if(!H)return;let he=H==="approve"?"approved":"denied",ue=O.getMessages().find(pe=>pe.id===S);if(!(ue!=null&&ue.approval))return;let be=A.querySelector("[data-approval-buttons]");be&&be.querySelectorAll("button").forEach(Ae=>{Ae.disabled=!0,Ae.style.opacity="0.5",Ae.style.cursor="not-allowed"}),O.resolveApproval(ue.approval,he)}),te.appendChild(Be),t.appendChild(Oe);let pn=()=>{var ge,we,Ve,Pe,mt,Wt,Z,_e,Zt,Yt,hn,js,Cr,ct,qs,ws;let l=(we=(ge=e.launcher)==null?void 0:ge.sidebarMode)!=null?we:!1,g=l||((Pe=(Ve=e.launcher)==null?void 0:Ve.fullHeight)!=null?Pe:!1),w=(mt=e.theme)!=null?mt:{},A=(Z=(Wt=e.launcher)==null?void 0:Wt.position)!=null?Z:"bottom-left",S=A==="bottom-left"||A==="top-left",H=l?"none":"1px solid var(--tvw-cw-border)",he=l?S?"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",ue=(_e=w.panelBorder)!=null?_e:H,be=(Zt=w.panelShadow)!=null?Zt:he,pe=(Yt=w.panelBorderRadius)!=null?Yt:le;t.style.cssText="",Oe.style.cssText="",te.style.cssText="",Be.style.cssText="",Fe.style.cssText="",Je.style.cssText="";let Ae=(js=(hn=e==null?void 0:e.launcher)==null?void 0:hn.width)!=null?js:e==null?void 0:e.launcherWidth,ne=Ae!=null?Ae:"min(400px, calc(100vw - 24px))";l||(te.style.width=ne,te.style.maxWidth=ne),te.style.boxShadow=be,te.style.borderRadius=pe,Be.style.border=ue,Be.style.borderRadius=pe;let k=((Cr=e.launcher)==null?void 0:Cr.enabled)===!1;if(g&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",Oe.style.display="flex",Oe.style.flexDirection="column",Oe.style.flex="1 1 0%",Oe.style.minHeight="0",Oe.style.maxHeight="100%",Oe.style.height="100%",k&&(Oe.style.overflow="hidden"),te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.height="100%",te.style.overflow="hidden",Be.style.display="flex",Be.style.flexDirection="column",Be.style.flex="1 1 0%",Be.style.minHeight="0",Be.style.maxHeight="100%",Be.style.overflow="hidden",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",Je.style.flexShrink="0"),Oe.classList.remove("tvw-bottom-6","tvw-right-6","tvw-left-6","tvw-top-6","tvw-bottom-4","tvw-right-4","tvw-left-4","tvw-top-4"),!l&&!k&&((ct=Vt[A])!=null?ct:Vt["bottom-right"]).split(" ").forEach(En=>Oe.classList.add(En)),l){let An=(ws=(qs=e.launcher)==null?void 0:qs.sidebarWidth)!=null?ws:"420px";Oe.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: ${An} !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
- ${S?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
- `,te.style.cssText=`
31
+ ${W?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
32
+ `,ne.style.cssText=`
33
33
  position: relative !important;
34
34
  display: flex !important;
35
35
  flex-direction: column !important;
@@ -40,9 +40,9 @@
40
40
  min-height: 0 !important;
41
41
  margin: 0 !important;
42
42
  padding: 0 !important;
43
- box-shadow: ${be} !important;
44
- border-radius: ${pe} !important;
45
- `,te.style.setProperty("width","100%","important"),te.style.setProperty("max-width","100%","important"),Be.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: ${pe} !important;
55
- border: ${ue} !important;
54
+ border-radius: ${we} !important;
55
+ border: ${de} !important;
56
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(!k){let An="max-height: -moz-available !important; max-height: stretch !important;",En=l?"":"padding-top: 1.25em !important;";Oe.style.cssText+=An+En}};pn(),sr(t,e);let ut=[];N&&ut.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),ae==null||ae.destroy(),ae=null,$==null||$.destroy(),$=null,J=null});let Xt=null,Gn=()=>{Xt&&(Xt(),Xt=null),e.colorScheme==="auto"&&(Xt=Yi(()=>{sr(t,e)}))};Gn(),ut.push(()=>{Xt&&(Xt(),Xt=null)});let gn=sa(Ot),Gt=null,O,mn=!1,tn=!0,yn=0,Qn=0,nn=null,sn=!1,Bn=0,Rn=!1,Ws=125,Ps=2e3,Hs=5,Zn=50,Fn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},es=(Ne=(gt=e.voiceRecognition)==null?void 0:gt.autoResume)!=null?Ne:!1,ts=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},rn=()=>{d(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Bs=()=>{var A,S;if(((A=e.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=qr(a.voiceState),g=!!l.active,w=Number((S=l.timestamp)!=null?S:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-w<hl&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,Sn("restore"))},1e3)},Rs=()=>O?ca(O.getMessages()).filter(l=>!l.__skipPersist):[];function ns(l){if(!(i!=null&&i.save))return;let w={messages:l?ca(l):O?Rs():[],metadata:a};try{let A=i.save(w);A instanceof Promise&&A.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let bn=(l=!1)=>{if(!tn)return;let g=Date.now();sn&&g<Bn&&!l||(sn&&g>=Bn&&(sn=!1),!(!l&&!mn)&&(g-Qn<Ws||(Qn=g,nn&&cancelAnimationFrame(nn),nn=requestAnimationFrame(()=>{sn||!tn||(Rn=!0,Fe.scrollTop=Fe.scrollHeight,yn=Fe.scrollTop,requestAnimationFrame(()=>{Rn=!1}),nn=null)}))))},on=null,Fs=()=>Oe.querySelector("#persona-scroll-container")||Fe,$s=(l,g=500)=>{let w=l.scrollTop,A=l.clientHeight,S=l.scrollHeight,H=S-w;if(w+A>=S-2||Math.abs(H)<5)return;on!==null&&(cancelAnimationFrame(on),on=null);let le=performance.now(),ue=pe=>1-Math.pow(1-pe,3),be=pe=>{let Ae=l.scrollHeight;Ae!==S&&(S=Ae,H=S-w);let ne=pe-le,k=Math.min(ne/g,1),ge=ue(k),we=w+H*ge;l.scrollTop=we,k<1?on=requestAnimationFrame(be):(l.scrollTop=l.scrollHeight,on=null)};on=requestAnimationFrame(be)},Os=l=>{let g=new Map;l.forEach(w=>{let A=Fn.get(w.id);g.set(w.id,{streaming:w.streaming,role:w.role}),!A&&w.role==="assistant"&&s.emit("assistant:message",w),w.role==="assistant"&&(A!=null&&A.streaming)&&w.streaming===!1&&s.emit("assistant:complete",w),w.variant==="approval"&&w.approval&&(A?w.approval.status!=="pending"&&s.emit("approval:resolved",{approval:w.approval,decision:w.approval.status}):s.emit("approval:requested",{approval:w.approval,message:w}))}),Fn.clear(),g.forEach((w,A)=>{Fn.set(A,w)})},xn=(l,g,w)=>{var be,pe,Ae,ne;let A=document.createElement("div"),H=(()=>{var ge;let k=o.find(we=>we.renderLoadingIndicator);if(k!=null&&k.renderLoadingIndicator)return k.renderLoadingIndicator;if((ge=e.loadingIndicator)!=null&&ge.render)return e.loadingIndicator.render})();g.forEach(k=>{var mt,Wt;let ge=null,we=o.find(Z=>!!(k.variant==="reasoning"&&Z.renderReasoning||k.variant==="tool"&&Z.renderToolCall||k.variant==="approval"&&Z.renderApproval||!k.variant&&Z.renderMessage)),Ve=(mt=e.layout)==null?void 0:mt.messages;if(we)if(k.variant==="reasoning"&&k.reasoning&&we.renderReasoning){if(!q)return;ge=we.renderReasoning({message:k,defaultRenderer:()=>Hr(k),config:e})}else if(k.variant==="tool"&&k.toolCall&&we.renderToolCall){if(!V)return;ge=we.renderToolCall({message:k,defaultRenderer:()=>Br(k,e),config:e})}else if(k.variant==="approval"&&k.approval&&we.renderApproval){if(e.approval===!1)return;ge=we.renderApproval({message:k,defaultRenderer:()=>Rr(k,e),config:e})}else we.renderMessage&&(ge=we.renderMessage({message:k,defaultRenderer:()=>{let Z=Un(k,w,Ve,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e});return k.role!=="user"&&$r(Z,k,e,O),Z},config:e}));if(!ge&&k.role==="assistant"&&!k.variant&&e.enableComponentStreaming!==!1&&dr(k)){let _e=cr(k);if(_e){let Zt=lr(_e,{config:e,message:k,transform:w});if(Zt){let Yt=document.createElement("div");if(Yt.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(" "),Yt.id=`bubble-${k.id}`,Yt.setAttribute("data-message-id",k.id),k.content&&k.content.trim()){let hn=document.createElement("div");hn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",hn.innerHTML=w({text:k.content,message:k,streaming:!!k.streaming,raw:k.rawContent}),Yt.appendChild(hn)}Yt.appendChild(Zt),ge=Yt}}}if(!ge)if(k.variant==="reasoning"&&k.reasoning){if(!q)return;ge=Hr(k)}else if(k.variant==="tool"&&k.toolCall){if(!V)return;ge=Br(k,e)}else if(k.variant==="approval"&&k.approval){if(e.approval===!1)return;ge=Rr(k,e)}else{let Z=(Wt=e.layout)==null?void 0:Wt.messages;Z!=null&&Z.renderUserMessage&&k.role==="user"?ge=Z.renderUserMessage({message:k,config:e,streaming:!!k.streaming}):Z!=null&&Z.renderAssistantMessage&&k.role==="assistant"?ge=Z.renderAssistantMessage({message:k,config:e,streaming:!!k.streaming}):ge=Un(k,w,Z,e.messageActions,ht,{loadingIndicatorRenderer:H,widgetConfig:e}),k.role!=="user"&&ge&&$r(ge,k,e,O)}let Pe=document.createElement("div");Pe.className="tvw-flex",Pe.id=`wrapper-${k.id}`,Pe.setAttribute("data-wrapper-id",k.id),k.role==="user"&&Pe.classList.add("tvw-justify-end"),Pe.appendChild(ge),A.appendChild(Pe)});let he=g.some(k=>k.role==="assistant"&&k.streaming),le=g[g.length-1],ue=(le==null?void 0:le.role)==="assistant"&&!le.streaming&&le.variant!=="approval";if(mn&&g.some(k=>k.role==="user")&&!he&&!ue){let k={config:e,streaming:!0,location:"standalone",defaultRenderer:Wn},ge=o.find(Ve=>Ve.renderLoadingIndicator),we=null;if(ge!=null&&ge.renderLoadingIndicator&&(we=ge.renderLoadingIndicator(k)),we===null&&((be=e.loadingIndicator)!=null&&be.render)&&(we=e.loadingIndicator.render(k)),we===null&&(we=Wn()),we){let Ve=document.createElement("div"),Pe=((pe=e.loadingIndicator)==null?void 0:pe.showBubble)!==!1;Ve.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(" "),Ve.setAttribute("data-typing-indicator","true"),Ve.appendChild(we);let mt=document.createElement("div");mt.className="tvw-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(Ve),A.appendChild(mt)}}if(!mn&&g.length>0){let k=g[g.length-1],ge={config:e,lastMessage:k,messageCount:g.length},we=o.find(Pe=>Pe.renderIdleIndicator),Ve=null;if(we!=null&&we.renderIdleIndicator&&(Ve=we.renderIdleIndicator(ge)),Ve===null&&((Ae=e.loadingIndicator)!=null&&Ae.renderIdle)&&(Ve=e.loadingIndicator.renderIdle(ge)),Ve){let Pe=document.createElement("div"),mt=((ne=e.loadingIndicator)==null?void 0:ne.showBubble)!==!1;Pe.className=mt?["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(Ve);let Wt=document.createElement("div");Wt.className="tvw-flex",Wt.id="wrapper-idle-indicator",Wt.setAttribute("data-wrapper-id","idle-indicator"),Wt.appendChild(Pe),A.appendChild(Wt)}}Xi(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let k=Fs();$s(k)})})},Cn=()=>{b&&(I?(Oe.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-95","tvw-opacity-0"),te.classList.add("tvw-scale-100","tvw-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):(Oe.classList.add("tvw-pointer-events-none","tvw-opacity-0"),te.classList.remove("tvw-scale-100","tvw-opacity-100"),te.classList.add("tvw-scale-95","tvw-opacity-0"),Ge?Ge.element.style.display="":Qe&&(Qe.style.display="")))},nt=(l,g="user")=>{if(!b||I===l)return;let w=I;I=l,Cn(),I&&(fn(),bn(!0));let A={open:I,source:g,timestamp:Date.now()};I&&!w?s.emit("widget:opened",A):!I&&w&&s.emit("widget:closed",A),s.emit("widget:state",{open:I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()})},$n=l=>{G.disabled=l,z&&(z.disabled=l),gn.buttons.forEach(g=>{g.disabled=l})},On=()=>{Ke.active||de&&de.focus()};s.on("widget:opened",()=>{e.autoFocusInput&&setTimeout(()=>On(),200)});let ss=()=>{var S,H,he,le,ue,be,pe,Ae,ne,k,ge,we,Ve,Pe;vt.textContent=(H=(S=e.copy)==null?void 0:S.welcomeTitle)!=null?H:"Hello \u{1F44B}",zt.textContent=(le=(he=e.copy)==null?void 0:he.welcomeSubtitle)!=null?le:"Ask anything about your account or products.",de.placeholder=(be=(ue=e.copy)==null?void 0:ue.inputPlaceholder)!=null?be:"How can I help...",((Ae=(pe=e.sendButton)==null?void 0:pe.useIcon)!=null?Ae:!1)||(G.textContent=(k=(ne=e.copy)==null?void 0:ne.sendButtonLabel)!=null?k:"Send");let g=(we=(ge=e.theme)==null?void 0:ge.inputFontFamily)!=null?we:"sans-serif",w=(Pe=(Ve=e.theme)==null?void 0:Ve.inputFontWeight)!=null?Pe:"400",A=mt=>{switch(mt){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};de.style.fontFamily=A(g),de.style.fontWeight=w};e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(g=>({...g,sessionId:l}))}}),O=new _n(e,{onMessagesChanged(l){xn(ze,l,K),O&&(l.some(S=>S.role==="user")?gn.render([],O,de,l):gn.render(e.suggestionChips,O,de,l,e.suggestionChipsConfig)),bn(!mn),Os(l);let g=[...l].reverse().find(A=>A.role==="user"),w=Ke.lastUserMessageId;g&&g.id!==w&&(Ke.lastUserMessageId=g.id,s.emit("user:message",g)),Ke.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),ns(l)},onStatusChanged(l){var A;let g=(A=e.statusIndicator)!=null?A:{},w=S=>{var H,he,le,ue;return S==="idle"?(H=g.idleText)!=null?H:Pt.idle:S==="connecting"?(he=g.connectingText)!=null?he:Pt.connecting:S==="connected"?(le=g.connectedText)!=null?le:Pt.connected:S==="error"?(ue=g.errorText)!=null?ue:Pt.error:Pt[S]};Tt.textContent=w(l)},onStreamingChanged(l){mn=l,$n(l),O&&xn(ze,O.getMessages(),K),l||bn(!0)}}),e.clientToken&&O.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),$&&O.setSSEEventCallback((l,g)=>{$==null||$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),u&&u.then(l=>{var g;l&&(l.metadata&&(a=qr(l.metadata),C.syncFromMetadata()),(g=l.messages)!=null&&g.length&&O.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let rs=l=>{var S;l.preventDefault();let g=de.value.trim(),w=(S=U==null?void 0:U.hasAttachments())!=null?S:!1;if(!g&&!w)return;let A;w&&(A=[],A.push(...U.getContentParts()),g&&A.push(er(g))),de.value="",de.style.height="auto",O.sendMessage(g,{contentParts:A}),w&&U.clearAttachments()},os=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},is=async l=>{var w;if(((w=e.attachments)==null?void 0:w.enabled)!==!0||!U)return;let g=vl(l.clipboardData);g.length!==0&&(l.preventDefault(),await U.handleFiles(g))},Rt=null,jt=!1,an=null,Qt=null,as=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Sn=(l="user")=>{var H,he,le,ue;if(jt||O.isStreaming())return;let g=as();if(!g)return;Rt=new g;let A=(he=((H=e.voiceRecognition)!=null?H:{}).pauseDuration)!=null?he:2e3;Rt.continuous=!0,Rt.interimResults=!0,Rt.lang="en-US";let S=de.value;Rt.onresult=be=>{let pe="",Ae="";for(let k=0;k<be.results.length;k++){let ge=be.results[k],we=ge[0].transcript;ge.isFinal?pe+=we+" ":Ae=we}let ne=S+pe+Ae;de.value=ne,an&&clearTimeout(an),(pe||Ae)&&(an=window.setTimeout(()=>{let k=de.value.trim();k&&Rt&&jt&&(Kt(),de.value="",de.style.height="auto",O.sendMessage(k,{viaVoice:!0}))},A))},Rt.onerror=be=>{be.error!=="no-speech"&&Kt()},Rt.onend=()=>{if(jt){let be=de.value.trim();be&&be!==S.trim()&&(de.value="",de.style.height="auto",O.sendMessage(be,{viaVoice:!0})),Kt()}};try{if(Rt.start(),jt=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),ts(l),rn(),z){Qt={backgroundColor:z.style.backgroundColor,color:z.style.color,borderColor:z.style.borderColor};let be=(le=e.voiceRecognition)!=null?le:{},pe=(ue=be.recordingBackgroundColor)!=null?ue:"#ef4444",Ae=be.recordingIconColor,ne=be.recordingBorderColor;if(z.classList.add("tvw-voice-recording"),z.style.backgroundColor=pe,Ae){z.style.color=Ae;let k=z.querySelector("svg");k&&k.setAttribute("stroke",Ae)}ne&&(z.style.borderColor=ne),z.setAttribute("aria-label","Stop voice recognition")}}catch{Kt("system")}},Kt=(l="user")=>{if(jt){if(jt=!1,an&&(clearTimeout(an),an=null),Rt){try{Rt.stop()}catch{}Rt=null}if(Ke.active=!1,ts(l),rn(),z){if(z.classList.remove("tvw-voice-recording"),Qt){z.style.backgroundColor=Qt.backgroundColor,z.style.color=Qt.color,z.style.borderColor=Qt.borderColor;let g=z.querySelector("svg");g&&g.setAttribute("stroke",Qt.color||"currentColor"),Qt=null}z.setAttribute("aria-label","Start voice recognition")}}},Ns=(l,g)=>{var we,Ve,Pe,mt,Wt,Z,_e;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let A=p("div","tvw-send-button-wrapper"),S=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");S.type="button",S.setAttribute("aria-label","Start voice recognition");let H=(we=l==null?void 0:l.iconName)!=null?we:"mic",he=(Ve=g==null?void 0:g.size)!=null?Ve:"40px",le=(Pe=l==null?void 0:l.iconSize)!=null?Pe:he,ue=parseFloat(le)||24,be=(mt=l==null?void 0:l.backgroundColor)!=null?mt:g==null?void 0:g.backgroundColor,pe=(Wt=l==null?void 0:l.iconColor)!=null?Wt:g==null?void 0:g.textColor;S.style.width=le,S.style.height=le,S.style.minWidth=le,S.style.minHeight=le,S.style.fontSize="18px",S.style.lineHeight="1";let Ae=pe||"currentColor",ne=re(H,ue,Ae,1.5);ne?(S.appendChild(ne),S.style.color=Ae):(S.textContent="\u{1F3A4}",S.style.color=Ae),be?S.style.backgroundColor=be:S.classList.add("tvw-bg-cw-primary"),pe?S.style.color=pe:!pe&&!(g!=null&&g.textColor)&&S.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(S.style.borderWidth=l.borderWidth,S.style.borderStyle="solid"),l!=null&&l.borderColor&&(S.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(S.style.paddingLeft=l.paddingX,S.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(S.style.paddingTop=l.paddingY,S.style.paddingBottom=l.paddingY),A.appendChild(S);let k=(Z=l==null?void 0:l.tooltipText)!=null?Z:"Start voice recognition";if(((_e=l==null?void 0:l.showTooltip)!=null?_e:!1)&&k){let Zt=p("div","tvw-send-button-tooltip");Zt.textContent=k,A.appendChild(Zt)}return{micButton:S,micButtonWrapper:A}},Nn=()=>{if(jt){let l=de.value.trim();Ke.manuallyDeactivated=!0,rn(),Kt("user"),l&&(de.value="",de.style.height="auto",O.sendMessage(l))}else Ke.manuallyDeactivated=!1,rn(),Sn("user")};z&&(z.addEventListener("click",Nn),ut.push(()=>{Kt("system"),z&&z.removeEventListener("click",Nn)}));let Ds=s.on("assistant:complete",()=>{es&&(Ke.active||Ke.manuallyDeactivated||es==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&Sn("auto")},600))});ut.push(Ds);let _s=s.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});ut.push(_s);let ln=()=>{nt(!I,"user")},Ge=null,Qe=null;if(b){let l=o.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});g&&(Qe=g)}Qe||(Ge=Es(e,ln))}Ge?t.appendChild(Ge.element):Qe&&t.appendChild(Qe),Cn(),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming()),bn(!0),Bs(),x&&(b?I&&setTimeout(()=>On(),200):setTimeout(()=>On(),0));let fn=()=>{var w,A,S,H,he,le,ue,be;let l=(A=(w=e.launcher)==null?void 0:w.sidebarMode)!=null?A:!1,g=l||((H=(S=e.launcher)==null?void 0:S.fullHeight)!=null?H:!1);if(!b){te.style.height="",te.style.width="";return}if(!l){let pe=(le=(he=e==null?void 0:e.launcher)==null?void 0:he.width)!=null?le:e==null?void 0:e.launcherWidth,Ae=pe!=null?pe:"min(400px, calc(100vw - 24px))";te.style.width=Ae,te.style.maxWidth=Ae}if(!g){let pe=window.innerHeight,Ae=64,ne=(be=(ue=e.launcher)==null?void 0:ue.heightOffset)!=null?be:0,k=Math.max(200,pe-Ae),ge=Math.min(640,k),we=Math.max(200,ge-ne);te.style.height=`${we}px`}};fn(),window.addEventListener("resize",fn),ut.push(()=>window.removeEventListener("resize",fn)),yn=Fe.scrollTop;let ls=()=>{let l=Fe.scrollTop,g=Fe.scrollHeight,w=Fe.clientHeight,A=g-l-w,S=Math.abs(l-yn);if(yn=l,!Rn&&!(S<=Hs)){if(!tn&&A<Zn){sn=!1,tn=!0;return}tn&&A>Zn&&(sn=!0,Bn=Date.now()+Ps,tn=!1)}};Fe.addEventListener("scroll",ls,{passive:!0}),ut.push(()=>Fe.removeEventListener("scroll",ls)),ut.push(()=>{nn&&cancelAnimationFrame(nn)});let ds=()=>{ee&&(Gt&&(ee.removeEventListener("click",Gt),Gt=null),b?(ee.style.display="",Gt=()=>{I=!1,Cn()},ee.addEventListener("click",Gt)):ee.style.display="none")};ds(),(()=>{let{clearChatButton:l}=ye;l&&l.addEventListener("click",()=>{O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(w){console.error("[AgentWidget] Failed to clear default localStorage:",w)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(w){console.error("[AgentWidget] Failed to clear custom localStorage:",w)}let g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),i!=null&&i.clear)try{let w=i.clear();w instanceof Promise&&w.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(w){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()})})(),wt.addEventListener("submit",rs),de.addEventListener("keydown",os),de.addEventListener("paste",is),ut.push(()=>{wt.removeEventListener("submit",rs),de.removeEventListener("keydown",os),de.removeEventListener("paste",is)}),ut.push(()=>{O.cancel()}),Ge?ut.push(()=>{Ge==null||Ge.destroy()}):Qe&&ut.push(()=>{Qe==null||Qe.remove()});let Lt={update(l){var Kr,Yr,Vr,Xr,Gr,Qr,Zr,eo,to,no,so,ro,oo,io,ao,lo,co,uo,po,go,mo,fo,ho,wo,vo,yo,bo,xo,Co,So,Ao,Eo,To,Mo,Lo,Io,ko,Wo,Po,Ho,Bo,Ro,Fo,$o,Oo,No,Do,_o,jo,qo,Uo,zo,Jo,Ko,Yo,Vo,Xo,Go,Qo,Zo,ei,ti,ni,si,ri,oi,ii,ai,li,di,ci,ui,pi,gi,mi,fi,hi,wi,vi,yi,bi,xi,Ci,Si,Ai,Ei;let g=e.toolCall,w=e.colorScheme;e={...e,...l},pn(),sr(t,e),e.colorScheme!==w&&Gn();let A=Ls.getForInstance(e.plugins);o.length=0,o.push(...A),b=(Yr=(Kr=e.launcher)==null?void 0:Kr.enabled)!=null?Yr:!0,E=(Xr=(Vr=e.launcher)==null?void 0:Vr.autoExpand)!=null?Xr:!1,q=(Qr=(Gr=e.features)==null?void 0:Gr.showReasoning)!=null?Qr:!0,V=(eo=(Zr=e.features)==null?void 0:Zr.showToolCalls)!=null?eo:!0;let S=N;if(N=(no=(to=e.features)==null?void 0:to.showEventStreamToggle)!=null?no:!1,N&&!S){if($||(J=new Ms(_),$=new Ts(X,J),J.open().then(()=>$==null?void 0:$.restore()).catch(()=>{}),O.setSSEEventCallback((W,Me)=>{$.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:W,timestamp:Date.now(),payload:JSON.stringify(Me)})})),!D&&xe){let W=(ro=(so=e.features)==null?void 0:so.eventStream)==null?void 0:ro.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"+(W!=null&&W.toggleButton?" "+W.toggleButton:"");D=p("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=re("activity","18px","currentColor",1.5);Ze&&D.appendChild(Ze);let ve=ye.clearChatButtonWrapper,Re=ye.closeButtonWrapper,ft=ve||Re;ft&&ft.parentNode===xe?xe.insertBefore(D,ft):xe.appendChild(D),D.addEventListener("click",()=>{fe?Ce():je()})}}else!N&&S&&(Ce(),D&&(D.remove(),D=null),$==null||$.clear(),J==null||J.destroy(),$=null,J=null);if(((oo=e.launcher)==null?void 0:oo.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((io=e.launcher)==null?void 0:io.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((ao=e.launcher)==null?void 0:ao.enabled)!==!1&&!Ge&&!Qe){let W=o.find(Me=>Me.renderLauncher);if(W!=null&&W.renderLauncher){let Me=W.renderLauncher({config:e,defaultRenderer:()=>Es(e,ln).element,onToggle:ln});Me&&(Qe=Me,t.appendChild(Qe))}Qe||(Ge=Es(e,ln),t.appendChild(Ge.element))}Ge&&Ge.update(e),yt&&((lo=e.launcher)==null?void 0:lo.title)!==void 0&&(yt.textContent=e.launcher.title),ce&&((co=e.launcher)==null?void 0:co.subtitle)!==void 0&&(ce.textContent=e.launcher.subtitle);let H=(uo=e.layout)==null?void 0:uo.header;if((H==null?void 0:H.layout)!==T&&xe){let W=H?jn(e,H,{showClose:b,onClose:()=>nt(!1,"user")}):cn({config:e,showClose:b,onClose:()=>nt(!1,"user")});xe.replaceWith(W.header),xe=W.header,ke=W.iconHolder,yt=W.headerTitle,ce=W.headerSubtitle,ee=W.closeButton,T=H==null?void 0:H.layout}else if(H&&(ke&&(ke.style.display=H.showIcon===!1?"none":""),yt&&(yt.style.display=H.showTitle===!1?"none":""),ce&&(ce.style.display=H.showSubtitle===!1?"none":""),ee&&(ee.style.display=H.showCloseButton===!1?"none":""),ye.clearChatButtonWrapper)){let W=H.showClearChat;if(W!==void 0){ye.clearChatButtonWrapper.style.display=W?"":"none";let{closeButtonWrapper:Me}=ye;Me&&!Me.classList.contains("tvw-absolute")&&(W?Me.classList.remove("tvw-ml-auto"):Me.classList.add("tvw-ml-auto"))}}let le=((po=e.layout)==null?void 0:po.showHeader)!==!1;xe&&(xe.style.display=le?"":"none");let ue=((go=e.layout)==null?void 0:go.showFooter)!==!1;Je&&(Je.style.display=ue?"":"none"),b!==Y?b?nt(E,"auto"):(I=!0,Cn()):E!==P&&nt(E,"auto"),P=E,Y=b,fn(),ds(),JSON.stringify(l.toolCall)!==JSON.stringify(g)&&O&&xn(ze,O.getMessages(),K);let ne=(mo=e.launcher)!=null?mo:{},k=(fo=ne.headerIconHidden)!=null?fo:!1,ge=(wo=(ho=e.layout)==null?void 0:ho.header)==null?void 0:wo.showIcon,we=k||ge===!1,Ve=ne.headerIconName,Pe=(vo=ne.headerIconSize)!=null?vo:"48px";if(ke){let W=Be.querySelector(".tvw-border-b-cw-divider"),Me=W==null?void 0:W.querySelector(".tvw-flex-col");if(we)ke.style.display="none",W&&Me&&!W.contains(Me)&&W.insertBefore(Me,W.firstChild);else{if(ke.style.display="",ke.style.height=Pe,ke.style.width=Pe,W&&Me&&(W.contains(ke)?ke.nextSibling!==Me&&(ke.remove(),W.insertBefore(ke,Me)):W.insertBefore(ke,Me)),Ve){let ve=parseFloat(Pe)||24,Re=re(Ve,ve*.6,"#ffffff",2);Re?ke.replaceChildren(Re):ke.textContent=(yo=ne.agentIconText)!=null?yo:"\u{1F4AC}"}else if(ne.iconUrl){let ve=ke.querySelector("img");if(ve)ve.src=ne.iconUrl,ve.style.height=Pe,ve.style.width=Pe;else{let Re=document.createElement("img");Re.src=ne.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=Pe,Re.style.width=Pe,ke.replaceChildren(Re)}}else{let ve=ke.querySelector("svg"),Re=ke.querySelector("img");(ve||Re)&&ke.replaceChildren(),ke.textContent=(bo=ne.agentIconText)!=null?bo:"\u{1F4AC}"}let Ze=ke.querySelector("img");Ze&&(Ze.style.height=Pe,Ze.style.width=Pe)}}let mt=(Co=(xo=e.layout)==null?void 0:xo.header)==null?void 0:Co.showTitle,Wt=(Ao=(So=e.layout)==null?void 0:So.header)==null?void 0:Ao.showSubtitle;if(yt&&(yt.style.display=mt===!1?"none":""),ce&&(ce.style.display=Wt===!1?"none":""),ee){((To=(Eo=e.layout)==null?void 0:Eo.header)==null?void 0:To.showCloseButton)===!1?ee.style.display="none":ee.style.display="";let Me=(Mo=ne.closeButtonSize)!=null?Mo:"32px",Ze=(Lo=ne.closeButtonPlacement)!=null?Lo:"inline";ee.style.height=Me,ee.style.width=Me;let{closeButtonWrapper:ve}=ye,Re=Ze==="top-right",ft=ve==null?void 0:ve.classList.contains("tvw-absolute");if(ve&&Re!==ft)if(ve.remove(),Re)ve.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",Be.style.position="relative",Be.appendChild(ve);else{let Le=(ko=(Io=ne.clearChat)==null?void 0:Io.placement)!=null?ko:"inline",Ct=(Po=(Wo=ne.clearChat)==null?void 0:Wo.enabled)!=null?Po:!0;ve.className=Ct&&Le==="inline"?"":"tvw-ml-auto";let Dt=Be.querySelector(".tvw-border-b-cw-divider");Dt&&Dt.appendChild(ve)}if(ne.closeButtonColor?(ee.style.color=ne.closeButtonColor,ee.classList.remove("tvw-text-cw-muted")):(ee.style.color="",ee.classList.add("tvw-text-cw-muted")),ne.closeButtonBackgroundColor?(ee.style.backgroundColor=ne.closeButtonBackgroundColor,ee.classList.remove("hover:tvw-bg-gray-100")):(ee.style.backgroundColor="",ee.classList.add("hover:tvw-bg-gray-100")),ne.closeButtonBorderWidth||ne.closeButtonBorderColor){let Le=ne.closeButtonBorderWidth||"0px",Ct=ne.closeButtonBorderColor||"transparent";ee.style.border=`${Le} solid ${Ct}`,ee.classList.remove("tvw-border-none")}else ee.style.border="",ee.classList.add("tvw-border-none");ne.closeButtonBorderRadius?(ee.style.borderRadius=ne.closeButtonBorderRadius,ee.classList.remove("tvw-rounded-full")):(ee.style.borderRadius="",ee.classList.add("tvw-rounded-full")),ne.closeButtonPaddingX?(ee.style.paddingLeft=ne.closeButtonPaddingX,ee.style.paddingRight=ne.closeButtonPaddingX):(ee.style.paddingLeft="",ee.style.paddingRight=""),ne.closeButtonPaddingY?(ee.style.paddingTop=ne.closeButtonPaddingY,ee.style.paddingBottom=ne.closeButtonPaddingY):(ee.style.paddingTop="",ee.style.paddingBottom="");let kt=(Ho=ne.closeButtonIconName)!=null?Ho:"x",qt=(Bo=ne.closeButtonIconText)!=null?Bo:"\xD7";ee.innerHTML="";let $t=re(kt,"20px",ne.closeButtonColor||"",2);$t?ee.appendChild($t):ee.textContent=qt;let at=(Ro=ne.closeButtonTooltipText)!=null?Ro:"Close chat",Ut=(Fo=ne.closeButtonShowTooltip)!=null?Fo:!0;if(ee.setAttribute("aria-label",at),ve&&(ve._cleanupTooltip&&(ve._cleanupTooltip(),delete ve._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!ee)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=ee.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};ve.addEventListener("mouseenter",Ct),ve.addEventListener("mouseleave",Dt),ee.addEventListener("focus",Ct),ee.addEventListener("blur",Dt),ve._cleanupTooltip=()=>{Dt(),ve&&(ve.removeEventListener("mouseenter",Ct),ve.removeEventListener("mouseleave",Dt)),ee&&(ee.removeEventListener("focus",Ct),ee.removeEventListener("blur",Dt))}}}let{clearChatButton:Z,clearChatButtonWrapper:_e}=ye;if(Z){let W=($o=ne.clearChat)!=null?$o:{},Me=(Oo=W.enabled)!=null?Oo:!0,Ze=(Do=(No=e.layout)==null?void 0:No.header)==null?void 0:Do.showClearChat,ve=Ze!==void 0?Ze:Me,Re=(_o=W.placement)!=null?_o:"inline";if(_e){_e.style.display=ve?"":"none";let{closeButtonWrapper:ft}=ye;ft&&!ft.classList.contains("tvw-absolute")&&(ve?ft.classList.remove("tvw-ml-auto"):ft.classList.add("tvw-ml-auto"));let kt=Re==="top-right",qt=_e.classList.contains("tvw-absolute");if(kt!==qt&&ve){if(_e.remove(),kt)_e.className="tvw-absolute tvw-top-4 tvw-z-50",_e.style.right="48px",Be.style.position="relative",Be.appendChild(_e);else{_e.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",_e.style.right="";let at=Be.querySelector(".tvw-border-b-cw-divider"),Ut=ye.closeButtonWrapper;at&&Ut&&Ut.parentElement===at?at.insertBefore(_e,Ut):at&&at.appendChild(_e)}let $t=ye.closeButtonWrapper;$t&&!$t.classList.contains("tvw-absolute")&&(kt?$t.classList.add("tvw-ml-auto"):$t.classList.remove("tvw-ml-auto"))}}if(ve){let ft=(jo=W.size)!=null?jo:"32px";Z.style.height=ft,Z.style.width=ft;let kt=(qo=W.iconName)!=null?qo:"refresh-cw",qt=(Uo=W.iconColor)!=null?Uo:"";Z.innerHTML="";let $t=re(kt,"20px",qt||"",2);if($t&&Z.appendChild($t),qt?(Z.style.color=qt,Z.classList.remove("tvw-text-cw-muted")):(Z.style.color="",Z.classList.add("tvw-text-cw-muted")),W.backgroundColor?(Z.style.backgroundColor=W.backgroundColor,Z.classList.remove("hover:tvw-bg-gray-100")):(Z.style.backgroundColor="",Z.classList.add("hover:tvw-bg-gray-100")),W.borderWidth||W.borderColor){let Le=W.borderWidth||"0px",Ct=W.borderColor||"transparent";Z.style.border=`${Le} solid ${Ct}`,Z.classList.remove("tvw-border-none")}else Z.style.border="",Z.classList.add("tvw-border-none");W.borderRadius?(Z.style.borderRadius=W.borderRadius,Z.classList.remove("tvw-rounded-full")):(Z.style.borderRadius="",Z.classList.add("tvw-rounded-full")),W.paddingX?(Z.style.paddingLeft=W.paddingX,Z.style.paddingRight=W.paddingX):(Z.style.paddingLeft="",Z.style.paddingRight=""),W.paddingY?(Z.style.paddingTop=W.paddingY,Z.style.paddingBottom=W.paddingY):(Z.style.paddingTop="",Z.style.paddingBottom="");let at=(zo=W.tooltipText)!=null?zo:"Clear chat",Ut=(Jo=W.showTooltip)!=null?Jo:!0;if(Z.setAttribute("aria-label",at),_e&&(_e._cleanupTooltip&&(_e._cleanupTooltip(),delete _e._cleanupTooltip),Ut&&at)){let Le=null,Ct=()=>{if(Le||!Z)return;Le=p("div","tvw-clear-chat-tooltip"),Le.textContent=at;let xs=p("div");xs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(xs);let Tn=Z.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${Tn.left+Tn.width/2}px`,Le.style.top=`${Tn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Dt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};_e.addEventListener("mouseenter",Ct),_e.addEventListener("mouseleave",Dt),Z.addEventListener("focus",Ct),Z.addEventListener("blur",Dt),_e._cleanupTooltip=()=>{Dt(),_e&&(_e.removeEventListener("mouseenter",Ct),_e.removeEventListener("mouseleave",Dt)),Z&&(Z.removeEventListener("focus",Ct),Z.removeEventListener("blur",Dt))}}}}let Zt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Is],Yt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Pn.message,Pn.messageAndClick];C=ks({parsers:Zt,handlers:Yt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),K=ua(e,C,ie),O.updateConfig(e),xn(ze,O.getMessages(),K),gn.render(e.suggestionChips,O,de,void 0,e.suggestionChipsConfig),ss(),$n(O.isStreaming());let hn=((Ko=e.voiceRecognition)==null?void 0:Ko.enabled)===!0,js=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(hn&&js)if(!z||!et){let W=Ns(e.voiceRecognition,e.sendButton);W&&(z=W.micButton,et=W.micButtonWrapper,_t.insertBefore(et,ot),z.addEventListener("click",Nn),z.disabled=O.isStreaming())}else{let W=(Yo=e.voiceRecognition)!=null?Yo:{},Me=(Vo=e.sendButton)!=null?Vo:{},Ze=(Xo=W.iconName)!=null?Xo:"mic",ve=(Go=Me.size)!=null?Go:"40px",Re=(Qo=W.iconSize)!=null?Qo:ve,ft=parseFloat(Re)||24;z.style.width=Re,z.style.height=Re,z.style.minWidth=Re,z.style.minHeight=Re;let kt=(ei=(Zo=W.iconColor)!=null?Zo:Me.textColor)!=null?ei:"currentColor";z.innerHTML="";let qt=re(Ze,ft,kt,2);qt?z.appendChild(qt):z.textContent="\u{1F3A4}";let $t=(ti=W.backgroundColor)!=null?ti:Me.backgroundColor;$t?(z.style.backgroundColor=$t,z.classList.remove("tvw-bg-cw-primary")):(z.style.backgroundColor="",z.classList.add("tvw-bg-cw-primary")),kt?(z.style.color=kt,z.classList.remove("tvw-text-white")):!kt&&!Me.textColor&&(z.style.color="",z.classList.add("tvw-text-white")),W.borderWidth?(z.style.borderWidth=W.borderWidth,z.style.borderStyle="solid"):(z.style.borderWidth="",z.style.borderStyle=""),W.borderColor?z.style.borderColor=W.borderColor:z.style.borderColor="",W.paddingX?(z.style.paddingLeft=W.paddingX,z.style.paddingRight=W.paddingX):(z.style.paddingLeft="",z.style.paddingRight=""),W.paddingY?(z.style.paddingTop=W.paddingY,z.style.paddingBottom=W.paddingY):(z.style.paddingTop="",z.style.paddingBottom="");let at=et==null?void 0:et.querySelector(".tvw-send-button-tooltip"),Ut=(ni=W.tooltipText)!=null?ni:"Start voice recognition";if(((si=W.showTooltip)!=null?si:!1)&&Ut)if(at)at.textContent=Ut,at.style.display="";else{let Ct=document.createElement("div");Ct.className="tvw-send-button-tooltip",Ct.textContent=Ut,et==null||et.insertBefore(Ct,z)}else at&&(at.style.display="none");et.style.display="",z.disabled=O.isStreaming()}else z&&et&&(et.style.display="none",jt&&Kt());if(((ri=e.attachments)==null?void 0:ri.enabled)===!0)if(!Q||!F){let W=(oi=e.attachments)!=null?oi:{},Ze=(ai=((ii=e.sendButton)!=null?ii:{}).size)!=null?ai:"40px";$e||($e=p("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),$e.style.display="none",wt.insertBefore($e,de)),se||(se=document.createElement("input"),se.type="file",se.accept=((li=W.allowedTypes)!=null?li:wn).join(","),se.multiple=((di=W.maxFiles)!=null?di:4)>1,se.style.display="none",se.setAttribute("aria-label","Attach files"),wt.insertBefore(se,de)),Q=p("div","tvw-send-button-wrapper"),F=p("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),F.type="button",F.setAttribute("aria-label",(ci=W.buttonTooltipText)!=null?ci:"Attach file");let ve=(ui=W.buttonIconName)!=null?ui:"paperclip",Re=Ze,ft=parseFloat(Re)||40,kt=Math.round(ft*.6);F.style.width=Re,F.style.height=Re,F.style.minWidth=Re,F.style.minHeight=Re,F.style.fontSize="18px",F.style.lineHeight="1",F.style.backgroundColor="transparent",F.style.color="var(--cw-primary, #111827)",F.style.border="none",F.style.borderRadius="6px",F.style.transition="background-color 0.15s ease",F.addEventListener("mouseenter",()=>{F.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),F.addEventListener("mouseleave",()=>{F.style.backgroundColor="transparent"});let qt=re(ve,kt,"currentColor",1.5);qt?F.appendChild(qt):F.textContent="\u{1F4CE}",F.addEventListener("click",Ut=>{Ut.preventDefault(),se==null||se.click()}),Q.appendChild(F);let $t=(pi=W.buttonTooltipText)!=null?pi:"Attach file",at=p("div","tvw-send-button-tooltip");at.textContent=$t,Q.appendChild(at),Mt.append(Q),!U&&se&&$e&&(U=In.fromConfig(W),U.setPreviewsContainer($e),se.addEventListener("change",async()=>{U&&(se!=null&&se.files)&&(await U.handleFileSelect(se.files),se.value="")}))}else{Q.style.display="";let W=(gi=e.attachments)!=null?gi:{};se&&(se.accept=((mi=W.allowedTypes)!=null?mi:wn).join(","),se.multiple=((fi=W.maxFiles)!=null?fi:4)>1),U&&U.updateConfig({allowedTypes:W.allowedTypes,maxFileSize:W.maxFileSize,maxFiles:W.maxFiles})}else Q&&(Q.style.display="none"),U&&U.clearAttachments();let ct=(hi=e.sendButton)!=null?hi:{},qs=(wi=ct.useIcon)!=null?wi:!1,ws=(vi=ct.iconText)!=null?vi:"\u2191",An=ct.iconName,En=(yi=ct.tooltipText)!=null?yi:"Send message",ba=(bi=ct.showTooltip)!=null?bi:!1,vs=(xi=ct.size)!=null?xi:"40px",Us=ct.backgroundColor,en=ct.textColor;if(qs){if(G.style.width=vs,G.style.height=vs,G.style.minWidth=vs,G.style.minHeight=vs,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",An){let W=parseFloat(vs)||24,Me=en&&typeof en=="string"&&en.trim()?en.trim():"currentColor",Ze=re(An,W,Me,2);Ze?(G.appendChild(Ze),G.style.color=Me):(G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white"))}else G.textContent=ws,en?G.style.color=en:G.classList.add("tvw-text-white");G.className="tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-primary")):G.classList.add("tvw-bg-cw-primary")}else G.textContent=(Si=(Ci=e.copy)==null?void 0:Ci.sendButtonLabel)!=null?Si:"Send",G.style.width="",G.style.height="",G.style.minWidth="",G.style.minHeight="",G.style.fontSize="",G.style.lineHeight="",G.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",Us?(G.style.backgroundColor=Us,G.classList.remove("tvw-bg-cw-accent")):G.classList.add("tvw-bg-cw-accent"),en?G.style.color=en:G.classList.add("tvw-text-white");ct.borderWidth?(G.style.borderWidth=ct.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ct.borderColor?G.style.borderColor=ct.borderColor:G.style.borderColor="",ct.paddingX?(G.style.paddingLeft=ct.paddingX,G.style.paddingRight=ct.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ct.paddingY?(G.style.paddingTop=ct.paddingY,G.style.paddingBottom=ct.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let ys=ot==null?void 0:ot.querySelector(".tvw-send-button-tooltip");if(ba&&En)if(ys)ys.textContent=En,ys.style.display="";else{let W=document.createElement("div");W.className="tvw-send-button-tooltip",W.textContent=En,ot==null||ot.insertBefore(W,G)}else ys&&(ys.style.display="none");let bs=(Ai=e.statusIndicator)!=null?Ai:{},xa=(Ei=bs.visible)!=null?Ei:!0;if(Tt.style.display=xa?"":"none",O){let W=O.getStatus(),Me=Ze=>{var ve,Re,ft,kt;return Ze==="idle"?(ve=bs.idleText)!=null?ve:Pt.idle:Ze==="connecting"?(Re=bs.connectingText)!=null?Re:Pt.connecting:Ze==="connected"?(ft=bs.connectedText)!=null?ft:Pt.connected:Ze==="error"?(kt=bs.errorText)!=null?kt:Pt.error:Pt[Ze]};Tt.textContent=Me(W)}},open(){b&&nt(!0,"api")},close(){b&&nt(!1,"api")},toggle(){b&&nt(!I,"api")},clearChat(){O.clearMessages();try{localStorage.removeItem(Xn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Xn}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==Xn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let g=i.clear();g instanceof Promise&&g.catch(w=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",w)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}a={},C.syncFromMetadata(),$==null||$.clear(),ae==null||ae.update()},setMessage(l){return!de||O.isStreaming()?!1:(!I&&b&&nt(!0,"system"),de.value=l,de.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let g=(l==null?void 0:l.trim())||de.value.trim();return g?(!I&&b&&nt(!0,"system"),de.value="",de.style.height="auto",O.sendMessage(g),!0):!1},startVoiceRecognition(){return jt||O.isStreaming()||!as()?!1:(!I&&b&&nt(!0,"system"),Ke.manuallyDeactivated=!1,rn(),Sn("user"),!0)},stopVoiceRecognition(){return jt?(Ke.manuallyDeactivated=!0,rn(),Kt("user"),!0):!1},injectMessage(l){return!I&&b&&nt(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!I&&b&&nt(!0,"system");let g=O.injectAssistantMessage(l);return M&&(M=!1,R&&(clearTimeout(R),R=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),g},injectUserMessage(l){return!I&&b&&nt(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!I&&b&&nt(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!I&&b&&nt(!0,"system"),O.injectMessageBatch(l)},injectTestMessage(l){!I&&b&&nt(!0,"system"),O.injectTestEvent(l)},async connectStream(l,g){return O.connectStream(l,g)},__pushEventStreamEvent(l){$&&$.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||!$||je()},hideEventStream(){fe&&Ce()},isEventStreamVisible(){return fe},focusInput(){return b&&!I||!de?!1:(de.focus(),!0)},async resolveApproval(l,g){let A=O.getMessages().find(S=>{var H;return S.variant==="approval"&&((H=S.approval)==null?void 0:H.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return O.resolveApproval(A.approval,g)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,g){return s.on(l,g)},off(l,g){s.off(l,g)},isOpen(){return b&&I},isVoiceActive(){return Ke.active},getState(){return{open:b&&I,launcherEnabled:b,voiceActive:Ke.active,streaming:O.isStreaming()}},showCSATFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=ur({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitCSATFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!I&&b&&nt(!0,"system");let g=ze.querySelector(".tvw-feedback-container");g&&g.remove();let w=pr({onSubmit:async(A,S)=>{var H;O.isClientTokenMode()&&await O.submitNPSFeedback(A,S),(H=l==null?void 0:l.onSubmit)==null||H.call(l,A,S)},onDismiss:l==null?void 0:l.onDismiss,...l});ze.appendChild(w),w.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return O.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return O.submitNPSFeedback(l,g)},destroy(){ut.forEach(l=>l()),Oe.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),Gt&&ee.removeEventListener("click",Gt)}};if((((qe=r==null?void 0:r.debugTools)!=null?qe:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:Lt,getMessages:Lt.getMessages,getStatus:Lt.getStatus,getMetadata:Lt.getPersistentMetadata,updateMetadata:Lt.updatePersistentMetadata,clearHistory:()=>Lt.clearChat(),setVoiceActive:w=>w?Lt.startVoiceRecognition():Lt.stopVoiceRecognition()};window.AgentWidgetBrowser=g,ut.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),g=w=>{let A=w.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Lt.focusInput()};if(window.addEventListener("persona:focusInput",g),ut.push(()=>{window.removeEventListener("persona:focusInput",g)}),N){let w=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.showEventStream()},A=S=>{let H=S.detail;(!(H!=null&&H.instanceId)||H.instanceId===l)&&Lt.hideEventStream()};window.addEventListener("persona:showEventStream",w),window.addEventListener("persona:hideEventStream",A),ut.push(()=>{window.removeEventListener("persona:showEventStream",w),window.removeEventListener("persona:hideEventStream",A)})}}let Ft=yl(e.persistState);if(Ft&&b){let l=bl(Ft.storage),g=`${Ft.keyPrefix}widget-open`,w=`${Ft.keyPrefix}widget-voice`,A=`${Ft.keyPrefix}widget-voice-mode`;if(l){let S=((dt=Ft.persist)==null?void 0:dt.openState)&&l.getItem(g)==="true",H=((Ue=Ft.persist)==null?void 0:Ue.voiceState)&&l.getItem(w)==="true",he=((xt=Ft.persist)==null?void 0:xt.voiceState)&&l.getItem(A)==="true";if(S&&setTimeout(()=>{Lt.open(),setTimeout(()=>{var le;if(H||he)Lt.startVoiceRecognition();else if((le=Ft.persist)!=null&&le.focusInput){let ue=t.querySelector("textarea");ue&&ue.focus()}},100)},0),(Nt=Ft.persist)!=null&&Nt.openState&&(s.on("widget:opened",()=>{l.setItem(g,"true")}),s.on("widget:closed",()=>{l.setItem(g,"false")})),(Jt=Ft.persist)!=null&&Jt.voiceState&&(s.on("voice:state",le=>{l.setItem(w,le.active?"true":"false")}),s.on("user:message",le=>{l.setItem(A,le.viaVoice?"true":"false")})),Ft.clearOnChatClear){let le=()=>{l.removeItem(g),l.removeItem(w),l.removeItem(A)},ue=()=>le();window.addEventListener("persona:clear-chat",ue),ut.push(()=>{window.removeEventListener("persona:clear-chat",ue)})}}}return Lt};var Ur={},xl=t=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof t=="string"){let n=document.querySelector(t);if(!n)throw new Error(`Chat widget target "${t}" was not found`);return n}return t},Cl=()=>{try{if(typeof Ur!="undefined"&&Ur.url)return new URL("../widget.css",Ur.url).href}catch{}return null},pa=t=>{let n=Cl(),r=()=>{if(!(t instanceof ShadowRoot)||t.querySelector("link[data-persona]"))return;let e=document.head.querySelector("link[data-persona]");if(!e)return;let o=e.cloneNode(!0);t.insertBefore(o,t.firstChild)};if(t instanceof ShadowRoot)if(n){let e=document.createElement("link");e.rel="stylesheet",e.href=n,e.setAttribute("data-persona","true"),t.insertBefore(e,t.firstChild)}else r();else if(!document.head.querySelector("link[data-persona]")&&n){let o=document.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),document.head.appendChild(o)}},zr=t=>{var c,v,d,f;let n=xl(t.target),r=document.createElement("div");r.className="persona-host";let e=(d=(v=(c=t.config)==null?void 0:c.launcher)==null?void 0:v.enabled)!=null?d:!0;e||(r.style.height="100%"),n.appendChild(r);let o=t.useShadowDom===!0,s,i;if(o){let h=r.attachShadow({mode:"open"});i=h,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"),h.appendChild(s),pa(h)}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),pa(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=gr(s,t.config,{debugTools:t.debugTools});(f=t.onReady)==null||f.call(t);let u={...a,host:r,destroy(){a.destroy(),r.remove(),t.windowKey&&typeof window!="undefined"&&delete window[t.windowKey]}};return t.windowKey&&typeof window!="undefined"&&(window[t.windowKey]=u),u};var ga={name:"@runtypelabs/persona",version:"1.46.1",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 Hn=ga.version;function un(t){if(t!==void 0)return typeof t=="string"?t:Array.isArray(t)?`[${t.map(n=>n.toString()).join(", ")}]`:t.toString()}function Al(t){if(t)return{getHeaders:un(t.getHeaders),onFeedback:un(t.onFeedback),onCopy:un(t.onCopy),requestMiddleware:un(t.requestMiddleware),actionHandlers:un(t.actionHandlers),actionParsers:un(t.actionParsers),postprocessMessage:un(t.postprocessMessage),contextProviders:un(t.contextProviders),streamParser:un(t.streamParser)}}var ma=`({ 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
- }`,fa=`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
- }`,ha=`(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
- }`,wa=`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
- }`,El=`(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
- }`,Tl=`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 Ml(t){if(!t)return null;let n=t.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function mr(t){var n,r;return(r=(n=t.parserType)!=null?n:Ml(t.streamParser))!=null?r:"plain"}function fr(t,n){let r=[];return t.toolCall&&(r.push(`${n}toolCall: {`),Object.entries(t.toolCall).forEach(([e,o])=>{typeof o=="string"&&r.push(`${n} ${e}: "${o}",`)}),r.push(`${n}},`)),r}function hr(t,n,r){let e=[],o=t.messageActions&&Object.entries(t.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(`${n}messageActions: {`),t.messageActions&&Object.entries(t.messageActions).forEach(([i,a])=>{i==="onFeedback"||i==="onCopy"||(typeof a=="string"?e.push(`${n} ${i}: "${a}",`):typeof a=="boolean"&&e.push(`${n} ${i}: ${a},`))}),r!=null&&r.onFeedback&&e.push(`${n} onFeedback: ${r.onFeedback},`),r!=null&&r.onCopy&&e.push(`${n} onCopy: ${r.onCopy},`),e.push(`${n}},`)),e}function wr(t,n){let r=[];if(t.markdown){let e=t.markdown.options&&Object.keys(t.markdown.options).length>0,o=t.markdown.disableDefaultStyles!==void 0;(e||o)&&(r.push(`${n}markdown: {`),e&&(r.push(`${n} options: {`),Object.entries(t.markdown.options).forEach(([s,i])=>{typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`)}),r.push(`${n} },`)),o&&r.push(`${n} disableDefaultStyles: ${t.markdown.disableDefaultStyles},`),r.push(`${n}},`))}return r}function vr(t,n){let r=[];if(t.layout){let e=t.layout.header&&Object.keys(t.layout.header).some(s=>s!=="render"),o=t.layout.messages&&Object.keys(t.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(e||o)&&(r.push(`${n}layout: {`),e&&(r.push(`${n} header: {`),Object.entries(t.layout.header).forEach(([s,i])=>{s!=="render"&&(typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),o&&(r.push(`${n} messages: {`),Object.entries(t.layout.messages).forEach(([s,i])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof i=="object"&&i!==null?(r.push(`${n} avatar: {`),Object.entries(i).forEach(([a,u])=>{typeof u=="string"?r.push(`${n} ${a}: "${u}",`):typeof u=="boolean"&&r.push(`${n} ${a}: ${u},`)}),r.push(`${n} },`)):s==="timestamp"&&typeof i=="object"&&i!==null?Object.entries(i).some(([u])=>u!=="format")&&(r.push(`${n} timestamp: {`),Object.entries(i).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?r.push(`${n} ${u}: "${c}",`):typeof c=="boolean"&&r.push(`${n} ${u}: ${c},`))}),r.push(`${n} },`)):typeof i=="string"?r.push(`${n} ${s}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${s}: ${i},`))}),r.push(`${n} },`)),r.push(`${n}},`))}return r}function Jr(t,n){let r=[];return t&&(t.getHeaders&&r.push(`${n}getHeaders: ${t.getHeaders},`),t.requestMiddleware&&r.push(`${n}requestMiddleware: ${t.requestMiddleware},`),t.actionParsers&&r.push(`${n}actionParsers: ${t.actionParsers},`),t.actionHandlers&&r.push(`${n}actionHandlers: ${t.actionHandlers},`),t.contextProviders&&r.push(`${n}contextProviders: ${t.contextProviders},`),t.streamParser&&r.push(`${n}streamParser: ${t.streamParser},`)),r}function va(t,n="esm",r){let e={...t};delete e.postprocessMessage,delete e.initialMessages;let o=r?{...r,hooks:Al(r.hooks)}:void 0;return n==="esm"?Ll(e,o):n==="script-installer"?Wl(e):n==="script-advanced"?Hl(e,o):n==="react-component"?Il(e,o):n==="react-advanced"?kl(e,o):Pl(e,o)}function Ll(t,n){let r=n==null?void 0:n.hooks,e=mr(t),o=e!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.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(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...fr(t," ")),s.push(...hr(t," ",r)),s.push(...wr(t," ")),s.push(...vr(t," ")),s.push(...Jr(r," ")),t.debug&&s.push(` debug: ${t.debug},`),r!=null&&r.postprocessMessage?s.push(` postprocessMessage: ${r.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
133
- `)}function Il(t,n){let r=n==null?void 0:n.hooks,e=mr(t),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 t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.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(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...fr(t," ")),s.push(...hr(t," ",r)),s.push(...wr(t," ")),s.push(...vr(t," ")),s.push(...Jr(r," ")),t.debug&&s.push(` debug: ${t.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 kl(t,n){let r=n==null?void 0:n.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 t.apiUrl&&e.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&e.push(` clientToken: "${t.clientToken}",`),t.flowId&&e.push(` flowId: "${t.flowId}",`),t.theme&&(e.push(" theme: {"),Object.entries(t.theme).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),t.launcher&&(e.push(" launcher: {"),Object.entries(t.launcher).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.copy&&(e.push(" copy: {"),Object.entries(t.copy).forEach(([o,s])=>{e.push(` ${o}: "${s}",`)}),e.push(" },")),t.sendButton&&(e.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.voiceRecognition&&(e.push(" voiceRecognition: {"),Object.entries(t.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(" },")),t.statusIndicator&&(e.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([o,s])=>{typeof s=="string"?e.push(` ${o}: "${s}",`):typeof s=="boolean"&&e.push(` ${o}: ${s},`)}),e.push(" },")),t.features&&(e.push(" features: {"),Object.entries(t.features).forEach(([o,s])=>{e.push(` ${o}: ${s},`)}),e.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(e.push(" suggestionChips: ["),t.suggestionChips.forEach(o=>{e.push(` "${o}",`)}),e.push(" ],")),t.suggestionChipsConfig&&(e.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&e.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&e.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&e.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&e.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),e.push(" },")),e.push(...fr(t," ")),e.push(...hr(t," ",r)),e.push(...wr(t," ")),e.push(...vr(t," ")),r!=null&&r.getHeaders&&e.push(` getHeaders: ${r.getHeaders},`),r!=null&&r.contextProviders&&e.push(` contextProviders: ${r.contextProviders},`),t.debug&&e.push(` debug: ${t.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(${El}),`)),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(` ${ma}`),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(` ${ma}`),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(` ${ha}`),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(` ${ha}`),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 ya(t){var o;let n=mr(t),r=n!=="plain",e={};if(t.apiUrl&&(e.apiUrl=t.apiUrl),t.clientToken&&(e.clientToken=t.clientToken),t.flowId&&(e.flowId=t.flowId),r&&(e.parserType=n),t.theme&&(e.theme=t.theme),t.launcher&&(e.launcher=t.launcher),t.copy&&(e.copy=t.copy),t.sendButton&&(e.sendButton=t.sendButton),t.voiceRecognition&&(e.voiceRecognition=t.voiceRecognition),t.statusIndicator&&(e.statusIndicator=t.statusIndicator),t.features&&(e.features=t.features),((o=t.suggestionChips)==null?void 0:o.length)>0&&(e.suggestionChips=t.suggestionChips),t.suggestionChipsConfig&&(e.suggestionChipsConfig=t.suggestionChipsConfig),t.debug&&(e.debug=t.debug),t.toolCall){let s={};Object.entries(t.toolCall).forEach(([i,a])=>{typeof a=="string"&&(s[i]=a)}),Object.keys(s).length>0&&(e.toolCall=s)}if(t.messageActions){let s={};Object.entries(t.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(t.markdown){let s={};t.markdown.options&&(s.options=t.markdown.options),t.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=t.markdown.disableDefaultStyles),Object.keys(s).length>0&&(e.markdown=s)}if(t.layout){let s={};if(t.layout.header){let i={};Object.entries(t.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(t.layout.messages){let i={};Object.entries(t.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 Wl(t){let n=ya(t),r=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Hn}/dist/install.global.js" data-config='${r}'></script>`}function Pl(t,n){let r=n==null?void 0:n.hooks,e=mr(t),o=e!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Hn}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Hn}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return t.apiUrl&&s.push(` apiUrl: "${t.apiUrl}",`),t.clientToken&&s.push(` clientToken: "${t.clientToken}",`),t.flowId&&s.push(` flowId: "${t.flowId}",`),o&&s.push(` parserType: "${e}",`),t.theme&&(s.push(" theme: {"),Object.entries(t.theme).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.launcher&&(s.push(" launcher: {"),Object.entries(t.launcher).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.copy&&(s.push(" copy: {"),Object.entries(t.copy).forEach(([i,a])=>{s.push(` ${i}: "${a}",`)}),s.push(" },")),t.sendButton&&(s.push(" sendButton: {"),Object.entries(t.sendButton).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(t.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(" },")),t.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(t.statusIndicator).forEach(([i,a])=>{typeof a=="string"?s.push(` ${i}: "${a}",`):typeof a=="boolean"&&s.push(` ${i}: ${a},`)}),s.push(" },")),t.features&&(s.push(" features: {"),Object.entries(t.features).forEach(([i,a])=>{s.push(` ${i}: ${a},`)}),s.push(" },")),t.suggestionChips&&t.suggestionChips.length>0&&(s.push(" suggestionChips: ["),t.suggestionChips.forEach(i=>{s.push(` "${i}",`)}),s.push(" ],")),t.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),t.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${t.suggestionChipsConfig.fontFamily}",`),t.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${t.suggestionChipsConfig.fontWeight}",`),t.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${t.suggestionChipsConfig.paddingX}",`),t.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${t.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...fr(t," ")),s.push(...hr(t," ",r)),s.push(...wr(t," ")),s.push(...vr(t," ")),s.push(...Jr(r," ")),t.debug&&s.push(` debug: ${t.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 Hl(t,n){let r=n==null?void 0:n.hooks,e=ya(t),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@${Hn}/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(${Tl});`),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(` ${fa}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${fa}`),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(` ${wa}`),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(` ${wa}`),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 Bl=zr;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_DARK_THEME,DEFAULT_LIGHT_THEME,DEFAULT_WIDGET_CONFIG,VERSION,attachHeaderToContainer,buildComposer,buildDefaultHeader,buildExpandedHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,componentRegistry,createActionManager,createAgentExperience,createBubbleWithLayout,createCSATFeedback,createComponentMiddleware,createComponentStreamParser,createDirectivePostprocessor,createFlexibleJsonStreamParser,createImagePart,createJsonStreamParser,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createRegexJsonParser,createStandardBubble,createTextPart,createTypingIndicator,createXmlParser,defaultActionHandlers,defaultJsonActionParser,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateUserMessageId,getDisplayText,getHeaderLayout,getImageParts,hasComponentDirective,hasImages,headerLayouts,initAgentWidget,isComponentDirectiveType,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,renderComponentDirective,renderLoadingIndicatorWithFallback,validateImageFile});
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