@runtypelabs/persona 1.45.0 → 1.46.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +33 -0
- package/dist/index.cjs +30 -30
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +12 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.global.js +48 -48
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +30 -30
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
- package/src/components/event-stream-view.test.ts +26 -0
- package/src/components/event-stream-view.ts +6 -3
- package/src/types.ts +7 -0
- package/src/ui.ts +61 -15
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
1
|
+
"use strict";var 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,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),Ii=t=>t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),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,`
|
|
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()=>{}}},zs=t=>{try{let n=JSON.parse(t);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Js=()=>{let t={processChunk:n=>null,getExtractedText:()=>null};return t.__isPlainTextParser=!0,t},Ks=()=>{var n;let t=Wa();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)}},Ys=()=>{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,on.parse)(r,on.STR|on.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?t=typeof o.text=="string"?Us(o.text):"":o.type==="init"&&o.form?t="":typeof o.text=="string"&&(t=Us(o.text)))}catch{}return n=r.length,t!==null?{text:t,raw:r}:null},close:()=>{}}},Pi=t=>{let n=null,r=0,o=t||(s=>{if(!s||typeof s!="object")return null;let i=a=>typeof a=="string"?Us(a):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Us(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,on.parse)(s,on.STR|on.OBJ),u=o(a);u!==null&&(n=u)}catch{}return r=s.length,{text:n||"",raw:s}},close:()=>{}}},Vs=()=>{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 Pa="https://api.runtype.com/v1/dispatch",xr="https://api.runtype.com",Cr=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 Ha(t){switch(t){case"json":return Ys;case"regex-json":return Ks;case"xml":return Vs;case"plain":default:return Js}}var Cn=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var r,e,o;this.apiUrl=(r=n.apiUrl)!=null?r:Pa,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(e=n.streamParser)!=null?e:Ha(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$/,""))||xr;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$/,""))||xr}/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 w=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:w}),w}let c=await this.buildPayload(n.messages),v=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([w])=>w!=="sessionId"&&w!=="session_id")):void 0,d={sessionId:u.sessionId,messages:n.messages.filter(Cr).map(w=>{var S,x,E;return{id:w.id,role:w.role,content:(E=(x=(S=w.contentParts)!=null?S:w.llmContent)!=null?x:w.rawContent)!=null?E:w.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 w=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 x=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:x}),x}if(f.status===429){let x=new Error(w.hint||"Message limit reached for this session.");throw r({type:"error",error:x}),x}let S=new Error(w.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!f.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(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$/,""))||xr}/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(Cr).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(Cr).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,ze,dt,Mt,Nt,$e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt,te,Oe,Ct,Wt,Lt,j,et,Ie,K,O,we,de,re,Me,Ne,J,le,Be,Je,ot,In,it,Kt,Jn,dn,Yt,$,cn,Qt,mn,Kn,Zt,en,kn,Wn,Ls,Is,ks,Yn,Pn,Ke,Vn,Xn,tn,Ws,Ps,Gn,fn,nn,Hs,Bs,Rs,hr,hn,wn,nt,Hn,Qn,Zn,es,ts,Rt,_t,sn,Vt,ns,vn,Ut,$s,Bn,Fs,Os,rn,Ge,Qe,un,ss,rs,wr,Pt,vr,$t,os,is,as,ls,ds,cs,us,ps,gs;let o=n.getReader(),s=new TextDecoder,i="",a=Date.now(),u=0,c=()=>a+u++,v=D=>{let ke=D.reasoning?{...D.reasoning,chunks:[...D.reasoning.chunks]}:void 0,_e=D.toolCall?{...D.toolCall,chunks:D.toolCall.chunks?[...D.toolCall.chunks]:void 0}:void 0,at=D.tools?D.tools.map(mt=>({...mt,chunks:mt.chunks?[...mt.chunks]:void 0})):void 0;return{...D,reasoning:ke,toolCall:_e,tools:at}},d=D=>{r({type:"message",message:v(D)})},f=null,w={current:null},S=new Map,x=new Map,E={lastId:null,byStep:new Map},C={lastId:null,byCall:new Map},W=D=>{if(D==null)return null;try{return String(D)}catch{return null}},V=D=>{var ke,_e,at,mt,Tt;return W((Tt=(mt=(at=(_e=(ke=D.stepId)!=null?ke:D.step_id)!=null?_e:D.step)!=null?at:D.parentId)!=null?mt:D.flowStepId)!=null?Tt:D.flow_step_id)},b=D=>{var ke,_e,at,mt,Tt,st,m;return W((m=(st=(Tt=(mt=(at=(_e=(ke=D.callId)!=null?ke:D.call_id)!=null?_e:D.requestId)!=null?at:D.request_id)!=null?mt:D.toolCallId)!=null?Tt:D.tool_call_id)!=null?st:D.stepId)!=null?m:D.step_id)},N=()=>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=(D,ke)=>{E.lastId=ke,D&&E.byStep.set(D,ke)},R=(D,ke)=>{var Tt;let _e=(Tt=D.reasoningId)!=null?Tt:D.id,at=V(D);if(_e){let st=String(_e);return M(at,st),st}if(at){let st=E.byStep.get(at);if(st)return E.lastId=st,st}if(E.lastId&&!ke)return E.lastId;if(!ke)return null;let mt=`reason-${c()}`;return M(at,mt),mt},ne=D=>{let ke=S.get(D);if(ke)return ke;let _e={id:`reason-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:D,status:"streaming",chunks:[]}};return S.set(D,_e),d(_e),_e},Y=(D,ke)=>{C.lastId=ke,D&&C.byCall.set(D,ke)},_=(D,ke)=>{var Tt;let _e=(Tt=D.toolId)!=null?Tt:D.id,at=b(D);if(_e){let st=String(_e);return Y(at,st),st}if(at){let st=C.byCall.get(at);if(st)return C.lastId=st,st}if(C.lastId&&!ke)return C.lastId;if(!ke)return null;let mt=`tool-${c()}`;return Y(at,mt),mt},q=D=>{let ke=x.get(D);if(ke)return ke;let _e={id:`tool-${D}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:D,status:"pending"}};return x.set(D,_e),d(_e),_e},U=D=>{if(typeof D=="number"&&Number.isFinite(D))return D;if(typeof D=="string"){let ke=Number(D);if(!Number.isNaN(ke)&&Number.isFinite(ke))return ke;let _e=Date.parse(D);if(!Number.isNaN(_e))return _e}return Date.now()},ue=D=>{if(typeof D=="string")return D;if(D==null)return"";try{return JSON.stringify(D)}catch{return String(D)}},B=new Map,Z=new Map,P=null,z=new Map,Ce=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(;;){let{done:D,value:ke}=await o.read();if(D)break;i+=s.decode(ke,{stream:!0});let _e=i.split(`
|
|
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(`
|
|
5
5
|
|
|
6
|
-
`);i=(
|
|
7
|
-
`),Tt="message",st="";for(let H of mt)H.startsWith("event:")?Tt=H.replace("event:","").trim():H.startsWith("data:")&&(st+=H.replace("data:","").trim());if(!st)continue;let m;try{m=JSON.parse(st)}catch(H){r({type:"error",error:H instanceof Error?H:new Error("Failed to parse chat stream payload")});continue}let Pe=Tt!=="message"?Tt:(dt=m.type)!=null?dt:"message";if((Mt=this.onSSEEvent)==null||Mt.call(this,Pe,m),this.parseSSEEvent){w.current=f;let H=await this.handleCustomSSEEvent(m,r,w,d,c);if(w.current&&!f&&(f=w.current),H)continue}if(Pe==="reason_start"){let H=(Nt=R(m,!0))!=null?Nt:`reason-${c()}`,y=ne(H);y.reasoning=($e=y.reasoning)!=null?$e:{id:H,status:"streaming",chunks:[]},y.reasoning.startedAt=(se=y.reasoning.startedAt)!=null?se:U((Se=m.startedAt)!=null?Se:m.timestamp),y.reasoning.completedAt=void 0,y.reasoning.durationMs=void 0,y.streaming=!0,y.reasoning.status="streaming",d(y)}else if(Pe==="reason_delta"||Pe==="reason_chunk"){let H=(Fe=(he=R(m,!1))!=null?he:R(m,!0))!=null?Fe:`reason-${c()}`,y=ne(H);y.reasoning=(Xe=y.reasoning)!=null?Xe:{id:H,status:"streaming",chunks:[]},y.reasoning.startedAt=(pe=y.reasoning.startedAt)!=null?pe:U((Et=m.startedAt)!=null?Et:m.timestamp);let L=(gt=(pt=(G=m.reasoningText)!=null?G:m.text)!=null?pt:m.delta)!=null?gt:"";if(L&&m.hidden!==!0&&y.reasoning.chunks.push(String(L)),y.reasoning.status=m.done?"complete":"streaming",m.done){y.reasoning.completedAt=U((vt=m.completedAt)!=null?vt:m.timestamp);let ie=(Dt=y.reasoning.startedAt)!=null?Dt:Date.now();y.reasoning.durationMs=Math.max(0,((yt=y.reasoning.completedAt)!=null?yt:Date.now())-ie)}y.streaming=y.reasoning.status!=="complete",d(y)}else if(Pe==="reason_complete"){let H=(We=(Q=R(m,!1))!=null?Q:R(m,!0))!=null?We:`reason-${c()}`,y=S.get(H);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=U((bt=m.completedAt)!=null?bt:m.timestamp);let ie=(xt=y.reasoning.startedAt)!=null?xt:Date.now();y.reasoning.durationMs=Math.max(0,((te=y.reasoning.completedAt)!=null?te:Date.now())-ie),y.streaming=!1,d(y)}let L=V(m);L&&E.byStep.delete(L)}else if(Pe==="tool_start"){let H=(Oe=_(m,!0))!=null?Oe:`tool-${c()}`,y=q(H),L=(Ct=y.toolCall)!=null?Ct:{id:H,status:"pending"};L.name=(Wt=m.toolName)!=null?Wt:L.name,L.status="running",m.args!==void 0?L.args=m.args:m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=(j=L.startedAt)!=null?j:U((Lt=m.startedAt)!=null?Lt:m.timestamp),L.completedAt=void 0,L.durationMs=void 0,y.toolCall=L,y.streaming=!0;let ie=m.agentContext;(ie||m.executionId)&&(y.agentMetadata={executionId:(et=ie==null?void 0:ie.executionId)!=null?et:m.executionId,iteration:(Ie=ie==null?void 0:ie.iteration)!=null?Ie:m.iteration}),d(y)}else if(Pe==="tool_chunk"||Pe==="tool_delta"){let H=(O=(K=_(m,!1))!=null?K:_(m,!0))!=null?O:`tool-${c()}`,y=q(H),L=(we=y.toolCall)!=null?we:{id:H,status:"running"};L.startedAt=(re=L.startedAt)!=null?re:U((de=m.startedAt)!=null?de:m.timestamp);let ie=(J=(Ne=(Me=m.text)!=null?Me:m.delta)!=null?Ne:m.message)!=null?J:"";ie&&(L.chunks=(le=L.chunks)!=null?le:[],L.chunks.push(String(ie))),L.status="running",y.toolCall=L,y.streaming=!0;let Ae=m.agentContext;(Ae||m.executionId)&&(y.agentMetadata=(ot=y.agentMetadata)!=null?ot:{executionId:(Be=Ae==null?void 0:Ae.executionId)!=null?Be:m.executionId,iteration:(Je=Ae==null?void 0:Ae.iteration)!=null?Je:m.iteration}),d(y)}else if(Pe==="tool_complete"){let H=(it=(In=_(m,!1))!=null?In:_(m,!0))!=null?it:`tool-${c()}`,y=q(H),L=(Kt=y.toolCall)!=null?Kt:{id:H,status:"running"};L.status="complete",m.result!==void 0&&(L.result=m.result),typeof m.duration=="number"&&(L.duration=m.duration),L.completedAt=U((Jn=m.completedAt)!=null?Jn:m.timestamp);let ie=(dn=m.duration)!=null?dn:m.executionTime;if(typeof ie=="number")L.durationMs=ie;else{let It=(Yt=L.startedAt)!=null?Yt:Date.now();L.durationMs=Math.max(0,(($=L.completedAt)!=null?$:Date.now())-It)}y.toolCall=L,y.streaming=!1;let Ae=m.agentContext;(Ae||m.executionId)&&(y.agentMetadata=(mn=y.agentMetadata)!=null?mn:{executionId:(cn=Ae==null?void 0:Ae.executionId)!=null?cn:m.executionId,iteration:(Qt=Ae==null?void 0:Ae.iteration)!=null?Qt:m.iteration}),d(y);let Ye=b(m);Ye&&C.byCall.delete(Ye)}else if(Pe==="step_chunk"||Pe==="step_delta"){let H=m.stepType,y=m.executionType;if(H==="tool"||y==="context")continue;let L=N(),ie=(kn=(en=(Zt=(Kn=m.text)!=null?Kn:m.delta)!=null?Zt:m.content)!=null?en:m.chunk)!=null?kn:"";if(ie){let Ye=((Wn=Z.get(L.id))!=null?Wn:"")+ie;L.rawContent=Ye,B.has(L.id)||B.set(L.id,this.createStreamParser());let It=B.get(L.id),rt=Ye.trim().startsWith("{")||Ye.trim().startsWith("[");if(rt&&Z.set(L.id,Ye),It.__isPlainTextParser===!0){L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L);continue}let ft=It.processChunk(Ye);if(ft instanceof Promise)ft.then(De=>{var ct;let qe=typeof De=="string"?De:(ct=De==null?void 0:De.text)!=null?ct: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+=ie,Z.delete(Ue.id),B.delete(Ue.id),Ue.rawContent=void 0,d(Ue))}}).catch(()=>{L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L)});else{let De=typeof ft=="string"?ft:(Ls=ft==null?void 0:ft.text)!=null?Ls:null;De!==null&&De.trim()!==""?(L.content=De,d(L)):!rt&&!Ye.trim().startsWith("<")&&(L.content+=ie,Z.delete(L.id),B.delete(L.id),L.rawContent=void 0,d(L))}}if(m.isComplete){let Ae=(ks=(Is=m.result)==null?void 0:Is.response)!=null?ks:L.content;if(Ae){let Ye=Z.get(L.id),It=Ye!=null?Ye:ue(Ae);L.rawContent=It;let rt=B.get(L.id),St=null,ft=!1;if(rt&&(St=rt.getExtractedText(),St===null&&(St=zs(It)),St===null)){let De=rt.processChunk(It);De instanceof Promise?(ft=!0,De.then(qe=>{var Ue;let ct=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(ct!==null){let l=f;l&&l.id===L.id&&(l.content=ct,l.streaming=!1,B.delete(l.id),Z.delete(l.id),d(l))}})):St=typeof De=="string"?De:(Yn=De==null?void 0:De.text)!=null?Yn:null}if(!ft){St!==null&&St.trim()!==""?L.content=St:Z.has(L.id)||(L.content=ue(Ae));let De=B.get(L.id);if(De){let qe=(Pn=De.close)==null?void 0:Pn.call(De);qe instanceof Promise&&qe.catch(()=>{}),B.delete(L.id)}Z.delete(L.id),L.streaming=!1,d(L)}}}}else if(Pe==="step_complete"){let H=m.stepType,y=m.executionType;if(H==="tool"||y==="context")continue;let L=(Ke=m.result)==null?void 0:Ke.response,ie=N();if(L!=null){let Ae=B.get(ie.id),Ye=!1,It=!1;if(Ae){let rt=Ae.getExtractedText(),St=Z.get(ie.id),ft=St!=null?St:ue(L);if(ie.rawContent=ft,rt!==null&&rt.trim()!=="")ie.content=rt,Ye=!0;else{let De=zs(ft);if(De!==null)ie.content=De,Ye=!0;else{let qe=Ae.processChunk(ft);if(qe instanceof Promise)It=!0,qe.then(ct=>{var l;let Ue=typeof ct=="string"?ct:(l=ct==null?void 0:ct.text)!=null?l:null;if(Ue!==null&&Ue.trim()!==""){let p=f;p&&p.id===ie.id&&(p.content=Ue,p.streaming=!1,B.delete(p.id),Z.delete(p.id),d(p))}else{let p=Ae.getExtractedText(),h=f;h&&h.id===ie.id&&(p!==null&&p.trim()!==""?h.content=p:Z.has(h.id)||(h.content=ue(L)),h.streaming=!1,B.delete(h.id),Z.delete(h.id),d(h))}});else{let ct=typeof qe=="string"?qe:(Vn=qe==null?void 0:qe.text)!=null?Vn:null;if(ct!==null&&ct.trim()!=="")ie.content=ct,Ye=!0;else{let Ue=Ae.getExtractedText();Ue!==null&&Ue.trim()!==""&&(ie.content=Ue,Ye=!0)}}}}}if(!It){if(!ie.rawContent){let rt=Z.get(ie.id);ie.rawContent=rt!=null?rt:ue(L)}if(!Ye&&!Z.has(ie.id)&&(ie.content=ue(L)),Ae){let rt=(Xn=Ae.close)==null?void 0:Xn.call(Ae);rt instanceof Promise&&rt.catch(()=>{})}B.delete(ie.id),Z.delete(ie.id),ie.streaming=!1,d(ie)}}else B.delete(ie.id),Z.delete(ie.id),ie.streaming=!1,d(ie)}else if(Pe==="flow_complete"){let H=(tn=m.result)==null?void 0:tn.response;if(H!=null){let y=N(),L=Z.get(y.id),ie=L!=null?L:ue(H);y.rawContent=ie;let Ae=ue(H),Ye=B.get(y.id);if(Ye){let St=zs(ie);if(St!==null)Ae=St;else{let ft=Ye.processChunk(ie);ft instanceof Promise&&ft.then(qe=>{var Ue;let ct=typeof qe=="string"?qe:(Ue=qe==null?void 0:qe.text)!=null?Ue:null;if(ct!==null){let l=f;l&&l.id===y.id&&(l.content=ct,l.streaming=!1,d(l))}});let De=Ye.getExtractedText();De!==null&&(Ae=De)}}B.delete(y.id),Z.delete(y.id);let It=Ae!==y.content,rt=y.streaming!==!1;It&&(y.content=Ae),y.streaming=!1,(It||rt)&&d(y)}else if(f!==null){let y=f;B.delete(y.id),Z.delete(y.id),y.streaming!==!1&&(y.streaming=!1,d(y))}r({type:"status",status:"idle"})}else if(Pe==="agent_start")P={executionId:m.executionId,agentId:(Ws=m.agentId)!=null?Ws:"virtual",agentName:(Ps=m.agentName)!=null?Ps:"",status:"running",currentIteration:0,maxIterations:(Gn=m.maxIterations)!=null?Gn:1,startedAt:U(m.startedAt)};else if(Pe==="agent_iteration_start"){if(P&&(P.currentIteration=m.iteration),Ce==="separate"&&m.iteration>1){let H=f;H&&(H.streaming=!1,d(H),z.set(m.iteration-1,H),f=null)}}else if(Pe!=="agent_turn_start"){if(Pe==="agent_turn_delta"){if(m.contentType==="text"){let H=N();H.content+=(fn=m.delta)!=null?fn:"",H.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId,agentName:P==null?void 0:P.agentName},d(H)}else if(m.contentType==="thinking"){let H=(nn=m.turnId)!=null?nn:`agent-think-${m.iteration}`,y=ne(H);y.reasoning=(Hs=y.reasoning)!=null?Hs:{id:H,status:"streaming",chunks:[]},y.reasoning.chunks.push((Bs=m.delta)!=null?Bs:""),y.agentMetadata={executionId:m.executionId,iteration:m.iteration,turnId:m.turnId},d(y)}else if(m.contentType==="tool_input"){let H=(Rs=m.toolCallId)!=null?Rs:C.lastId;if(H){let y=x.get(H);y!=null&&y.toolCall&&(y.toolCall.chunks=(hr=y.toolCall.chunks)!=null?hr:[],y.toolCall.chunks.push((hn=m.delta)!=null?hn:""),d(y))}}}else if(Pe==="agent_turn_complete"){let H=m.turnId;if(H){let y=S.get(H);if(y!=null&&y.reasoning){y.reasoning.status="complete",y.reasoning.completedAt=U(m.completedAt);let L=(wn=y.reasoning.startedAt)!=null?wn:Date.now();y.reasoning.durationMs=Math.max(0,((nt=y.reasoning.completedAt)!=null?nt:Date.now())-L),y.streaming=!1,d(y)}}}else if(Pe==="agent_tool_start"){let H=(Hn=m.toolCallId)!=null?Hn:`agent-tool-${c()}`;Y(b(m),H);let y=q(H),L=(Qn=y.toolCall)!=null?Qn:{id:H,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=(Zn=m.toolName)!=null?Zn:L.name,L.status="running",m.parameters!==void 0&&(L.args=m.parameters),L.startedAt=U((es=m.startedAt)!=null?es:m.timestamp),y.toolCall=L,y.streaming=!0,y.agentMetadata={executionId:m.executionId,iteration:m.iteration},d(y)}else if(Pe==="agent_tool_delta"){let H=(ts=m.toolCallId)!=null?ts:C.lastId;if(H){let y=(Rt=x.get(H))!=null?Rt:q(H);y.toolCall&&(y.toolCall.chunks=(_t=y.toolCall.chunks)!=null?_t:[],y.toolCall.chunks.push((sn=m.delta)!=null?sn:""),y.toolCall.status="running",y.streaming=!0,d(y))}}else if(Pe==="agent_tool_complete"){let H=(Vt=m.toolCallId)!=null?Vt:C.lastId;if(H){let y=(ns=x.get(H))!=null?ns:q(H);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=U((vn=m.completedAt)!=null?vn:m.timestamp),y.streaming=!1,d(y);let L=b(m);L&&C.byCall.delete(L)}}}else if(Pe!=="agent_iteration_complete"){if(Pe==="agent_reflection"||Pe==="agent_reflect"){let H=`agent-reflection-${m.executionId}-${m.iteration}`,y={id:H,role:"assistant",content:(Ut=m.reflection)!=null?Ut:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:H,status:"complete",chunks:[($s=m.reflection)!=null?$s:""]},agentMetadata:{executionId:m.executionId,iteration:m.iteration}};d(y)}else if(Pe==="agent_complete"){P&&(P.status=m.success?"complete":"error",P.completedAt=U(m.completedAt),P.stopReason=m.stopReason);let H=f;H&&(H.streaming=!1,d(H)),r({type:"status",status:"idle"})}else if(Pe==="agent_error"){let H=typeof m.error=="string"?m.error:(Fs=(Bn=m.error)==null?void 0:Bn.message)!=null?Fs:"Agent execution error";m.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",H):r({type:"error",error:new Error(H)})}else if(Pe!=="agent_ping")if(Pe==="agent_approval_start"){let H=(Os=m.approvalId)!=null?Os:`approval-${c()}`,y={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(rn=P==null?void 0:P.agentId)!=null?rn:"virtual",executionId:(Qe=(Ge=m.executionId)!=null?Ge:P==null?void 0:P.executionId)!=null?Qe:"",toolName:(un=m.toolName)!=null?un:"",toolType:m.toolType,description:(rs=m.description)!=null?rs:`Execute ${(ss=m.toolName)!=null?ss:"tool"}`,parameters:m.parameters}};d(y)}else if(Pe==="step_await"&&m.awaitReason==="approval_required"){let H=(wr=m.approvalId)!=null?wr:`approval-${c()}`,y={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:"pending",agentId:(Pt=P==null?void 0:P.agentId)!=null?Pt:"virtual",executionId:($t=(vr=m.executionId)!=null?vr:P==null?void 0:P.executionId)!=null?$t:"",toolName:(os=m.toolName)!=null?os:"",toolType:m.toolType,description:(as=m.description)!=null?as:`Execute ${(is=m.toolName)!=null?is:"tool"}`,parameters:m.parameters}};d(y)}else if(Pe==="agent_approval_complete"){let H=m.approvalId;if(H){let L={id:`approval-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:H,status:(ls=m.decision)!=null?ls:"approved",agentId:(ds=P==null?void 0:P.agentId)!=null?ds:"virtual",executionId:(us=(cs=m.executionId)!=null?cs:P==null?void 0:P.executionId)!=null?us:"",toolName:(ps=m.toolName)!=null?ps:"",description:(gs=m.description)!=null?gs:"",resolvedAt:Date.now()}};d(L)}}else Pe==="error"&&m.error&&r({type:"error",error:m.error instanceof Error?m.error:new Error(String(m.error))})}}}}}};function Hi(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${t}_${n}`}function Rn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${t}_${n}`}function Sn(){let t=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${t}_${n}`}var Xs="[Image]";function Bi(t){return typeof t=="string"?[{type:"text",text:t}]:t}function Ri(t){return typeof t=="string"?t:t.filter(n=>n.type==="text").map(n=>n.text).join("")}function $i(t){return typeof t=="string"?!1:t.some(n=>n.type==="image")}function Fi(t){return typeof t=="string"?[]:t.filter(n=>n.type==="image")}function Gs(t){return{type:"text",text:t}}function Oi(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 Ni(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 Di(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 _i=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Ba=["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"],gn=[..._i,...Ba];function Ra(t){return _i.includes(t)||t.startsWith("image/")}function Qs(t){return Ra(t.type)}async function ji(t){return new Promise((n,r)=>{let e=new FileReader;e.onload=()=>{let o=e.result;Qs(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 qi(t,n=gn,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 $a(t){let n=t.split(".");return n.length>1?n.pop().toLowerCase():""}function Ui(t,n){let r=$a(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 Cn(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 Cn(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"?Rn():r==="assistant"?Sn():`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,w={id:u!=null?u:o==="user"?Rn():o==="assistant"?Sn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:v!=null?v:this.nextSequence(),streaming:d,...i!==void 0&&{llmContent:i},...a!==void 0&&{contentParts:a}};r.push(w)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}async sendMessage(n,r){var c,v,d,f,w;let e=n.trim();if(!e&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;(c=this.abortController)==null||c.abort();let o=Rn(),s=Sn(),i={id:o,role:"user",content:e||Xs,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(S){let x=S instanceof Error&&(S.name==="AbortError"||S.message.includes("aborted")||S.message.includes("abort"));if(!x){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,x||(S instanceof Error?(d=(v=this.callbacks).onError)==null||d.call(v,S):(w=(f=this.callbacks).onError)==null||w.call(f,new Error(String(S))))}}async continueConversation(){var o,s,i,a,u;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=Sn();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 e,o,s;if(!this.streaming){(e=this.abortController)==null||e.abort(),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(o=this.callbacks).onError)==null||s.call(o,i instanceof Error?i:new Error(String(i)))}}}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 w=await d.json().catch(()=>null);throw new Error((u=w==null?void 0:w.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 g=(t,n)=>{let r=document.createElement(t);return n&&(r.className=n),r};var Fa=Ea(require("lucide"),1),oe=(t,n=24,r="currentColor",e=2)=>{try{let o=t.split("-").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join(""),s=Fa[o];return s?Oa(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 Oa(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 Zs={allowedTypes:gn,maxFileSize:10*1024*1024,maxFiles:4};function Na(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Da(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 An=class t{constructor(n={}){this.attachments=[];this.previewsContainer=null;var r,e,o;this.config={allowedTypes:(r=n.allowedTypes)!=null?r:Zs.allowedTypes,maxFileSize:(e=n.maxFileSize)!=null?e:Zs.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Zs.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:Zs.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=qi(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 ji(c),f=Qs(c)?URL.createObjectURL(c):null,w={id:Na(),file:c,previewUrl:f,contentPart:d};this.attachments.push(w),this.renderPreview(w)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(a=this.config).onAttachmentsChange)==null||u.call(a,this.getAttachments())}}removeAttachment(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=Qs(n.file),e=g("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=g("img");i.src=n.previewUrl,i.alt=n.file.name,i.className="tvw-w-full tvw-h-full tvw-object-cover tvw-rounded-lg tvw-border tvw-border-gray-200",i.style.width="48px",i.style.height="48px",i.style.objectFit="cover",i.style.borderRadius="8px",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=Da(n.file.type),u=oe(a,20,"var(--cw-muted, #6b7280)",1.5);u&&i.appendChild(u);let c=g("span");c.textContent=Ui(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=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=oe("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 Sr=()=>{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"},_a=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"||Sr()==="dark"?e:r},zi=t=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{t(Sr())});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(Sr());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())}},er=(t,n)=>{let r=_a(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 Ji=require("idiomorph"),Ki=(t,n,r={})=>{let{preserveTypingAnimation:e=!0}=r;Ji.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 Bt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var Jt={"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 Cs=(t,n)=>{let r=g("button");r.type="button",r.innerHTML=`
|
|
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&>.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 e,o,s;if(!this.streaming){(e=this.abortController)==null||e.abort(),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(s=(o=this.callbacks).onError)==null||s.call(o,i instanceof Error?i:new Error(String(i)))}}}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=`
|
|
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 C,W,V,b,N,M,R,ne,Y,_,q,U;let i=(C=s.launcher)!=null?C:{},a=r.querySelector("[data-role='launcher-title']");a&&(a.textContent=(W=i.title)!=null?W:"Chat Assistant");let u=r.querySelector("[data-role='launcher-subtitle']");u&&(u.textContent=(V=i.subtitle)!=null?V:"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 ue=(b=i.agentIconSize)!=null?b:"40px";if(v.style.height=ue,v.style.width=ue,v.innerHTML="",i.agentIconName){let B=parseFloat(ue)||24,Z=oe(i.agentIconName,B*.6,"#ffffff",2);Z?(v.appendChild(Z),v.style.display=""):(v.textContent=(N=i.agentIconText)!=null?N:"\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 ue=(R=i.agentIconSize)!=null?R:"40px";d.style.height=ue,d.style.width=ue,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 ue=(ne=i.callToActionIconSize)!=null?ne:"32px";f.style.height=ue,f.style.width=ue,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 B=0;if(i.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=i.callToActionIconPadding,B=(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 Z=parseFloat(ue)||24,P=Math.max(Z-B,8),z=oe(i.callToActionIconName,P,"currentColor",2);z?f.appendChild(z):f.textContent=(Y=i.callToActionIconText)!=null?Y:"\u2197"}else f.textContent=(_=i.callToActionIconText)!=null?_:"\u2197"}let w=i.position&&Jt[i.position]?Jt[i.position]:Jt["bottom-right"],S="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=`${S} ${w}`;let x="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=(q=i.border)!=null?q:x,r.style.boxShadow=(U=i.shadow)!=null?U:E},o=()=>{r.removeEventListener("click",n),r.remove()};return t&&e(t),{element:r,update:e,destroy:o}};var an=t=>{var _,q,U,ue,B,Z,P,z,Ce,fe,ze,dt,Mt,Nt,$e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt;let{config:n,showClose:r=!0}=t,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=(_=n==null?void 0:n.launcher)!=null?_:{},s=(q=o.headerIconSize)!=null?q:"48px",i=(U=o.closeButtonSize)!=null?U:"32px",a=(ue=o.closeButtonPlacement)!=null?ue:"inline",u=(B=o.headerIconHidden)!=null?B:!1,c=o.headerIconName,v=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-xl");if(v.style.height=s,v.style.width=s,!u)if(c){let te=parseFloat(s)||24,Oe=oe(c,te*.6,"#ffffff",1);Oe?v.replaceChildren(Oe):v.textContent=(P=(Z=n==null?void 0:n.launcher)==null?void 0:Z.agentIconText)!=null?P:"\u{1F4AC}"}else if((z=n==null?void 0:n.launcher)!=null&&z.iconUrl){let te=g("img");te.src=n.launcher.iconUrl,te.alt="",te.className="tvw-rounded-xl tvw-object-cover",te.style.height=s,te.style.width=s,v.replaceChildren(te)}else v.textContent=(fe=(Ce=n==null?void 0:n.launcher)==null?void 0:Ce.agentIconText)!=null?fe:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col"),f=g("span","tvw-text-base tvw-font-semibold");f.textContent=(dt=(ze=n==null?void 0:n.launcher)==null?void 0:ze.title)!=null?dt:"Chat Assistant";let w=g("span","tvw-text-xs tvw-text-cw-muted");w.textContent=(Nt=(Mt=n==null?void 0:n.launcher)==null?void 0:Mt.subtitle)!=null?Nt:"Here to help you get answers fast",d.append(f,w),u?e.append(d):e.append(v,d);let S=($e=o.clearChat)!=null?$e:{},x=(Se=S.enabled)!=null?Se:!0,E=(se=S.placement)!=null?se:"inline",C=null,W=null;if(x){let te=(he=S.size)!=null?he:"32px",Oe=(Fe=S.iconName)!=null?Fe:"refresh-cw",Ct=(Xe=S.iconColor)!=null?Xe:"",Wt=(Et=S.backgroundColor)!=null?Et:"",Lt=(pe=S.borderWidth)!=null?pe:"",j=(G=S.borderColor)!=null?G:"",et=(pt=S.borderRadius)!=null?pt:"",Ie=(gt=S.paddingX)!=null?gt:"",K=(vt=S.paddingY)!=null?vt:"",O=(Dt=S.tooltipText)!=null?Dt:"Clear chat",we=(yt=S.showTooltip)!=null?yt:!0;W=g("div",E==="top-right"?"tvw-absolute tvw-top-4 tvw-z-50":"tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper"),E==="top-right"&&(W.style.right="48px"),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=te,C.style.width=te,C.type="button",C.setAttribute("aria-label",O);let de=oe(Oe,"20px",Ct||"",1);if(de&&C.appendChild(de),Ct&&(C.style.color=Ct,C.classList.remove("tvw-text-cw-muted")),Wt&&(C.style.backgroundColor=Wt,C.classList.remove("hover:tvw-bg-gray-100")),Lt||j){let re=Lt||"0px",Me=j||"transparent";C.style.border=`${re} solid ${Me}`,C.classList.remove("tvw-border-none")}if(et&&(C.style.borderRadius=et,C.classList.remove("tvw-rounded-full")),Ie?(C.style.paddingLeft=Ie,C.style.paddingRight=Ie):(C.style.paddingLeft="",C.style.paddingRight=""),K?(C.style.paddingTop=K,C.style.paddingBottom=K):(C.style.paddingTop="",C.style.paddingBottom=""),W.appendChild(C),we&&O&&C&&W){let re=null,Me=()=>{if(re||!C)return;re=g("div","tvw-clear-chat-tooltip"),re.textContent=O;let J=g("div");J.className="tvw-clear-chat-tooltip-arrow",re.appendChild(J);let le=C.getBoundingClientRect();re.style.position="fixed",re.style.left=`${le.left+le.width/2}px`,re.style.top=`${le.top-8}px`,re.style.transform="translate(-50%, -100%)",document.body.appendChild(re)},Ne=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};W.addEventListener("mouseenter",Me),W.addEventListener("mouseleave",Ne),C.addEventListener("focus",Me),C.addEventListener("blur",Ne),W._cleanupTooltip=()=>{Ne(),W&&(W.removeEventListener("mouseenter",Me),W.removeEventListener("mouseleave",Ne)),C&&(C.removeEventListener("focus",Me),C.removeEventListener("blur",Ne))}}E==="inline"&&e.appendChild(W)}let V=g("div",a==="top-right"?"tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50":x&&E==="inline"?"":"tvw-ml-auto"),b=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");b.style.height=i,b.style.width=i,b.type="button";let N=(Q=o.closeButtonTooltipText)!=null?Q:"Close chat",M=(We=o.closeButtonShowTooltip)!=null?We:!0;b.setAttribute("aria-label",N),b.style.display=r?"":"none";let R=(bt=o.closeButtonIconName)!=null?bt:"x",ne=(xt=o.closeButtonIconText)!=null?xt:"\xD7",Y=oe(R,"20px",o.closeButtonColor||"",1);if(Y?b.appendChild(Y):b.textContent=ne,o.closeButtonColor?(b.style.color=o.closeButtonColor,b.classList.remove("tvw-text-cw-muted")):(b.style.color="",b.classList.add("tvw-text-cw-muted")),o.closeButtonBackgroundColor?(b.style.backgroundColor=o.closeButtonBackgroundColor,b.classList.remove("hover:tvw-bg-gray-100")):(b.style.backgroundColor="",b.classList.add("hover:tvw-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let te=o.closeButtonBorderWidth||"0px",Oe=o.closeButtonBorderColor||"transparent";b.style.border=`${te} solid ${Oe}`,b.classList.remove("tvw-border-none")}else b.style.border="",b.classList.add("tvw-border-none");if(o.closeButtonBorderRadius?(b.style.borderRadius=o.closeButtonBorderRadius,b.classList.remove("tvw-rounded-full")):(b.style.borderRadius="",b.classList.add("tvw-rounded-full")),o.closeButtonPaddingX?(b.style.paddingLeft=o.closeButtonPaddingX,b.style.paddingRight=o.closeButtonPaddingX):(b.style.paddingLeft="",b.style.paddingRight=""),o.closeButtonPaddingY?(b.style.paddingTop=o.closeButtonPaddingY,b.style.paddingBottom=o.closeButtonPaddingY):(b.style.paddingTop="",b.style.paddingBottom=""),V.appendChild(b),M&&N){let te=null,Oe=()=>{if(te)return;te=g("div","tvw-clear-chat-tooltip"),te.textContent=N;let Wt=g("div");Wt.className="tvw-clear-chat-tooltip-arrow",te.appendChild(Wt);let Lt=b.getBoundingClientRect();te.style.position="fixed",te.style.left=`${Lt.left+Lt.width/2}px`,te.style.top=`${Lt.top-8}px`,te.style.transform="translate(-50%, -100%)",document.body.appendChild(te)},Ct=()=>{te&&te.parentNode&&(te.parentNode.removeChild(te),te=null)};V.addEventListener("mouseenter",Oe),V.addEventListener("mouseleave",Ct),b.addEventListener("focus",Oe),b.addEventListener("blur",Ct),V._cleanupTooltip=()=>{Ct(),V.removeEventListener("mouseenter",Oe),V.removeEventListener("mouseleave",Ct),b.removeEventListener("focus",Oe),b.removeEventListener("blur",Ct)}}return a!=="top-right"&&e.appendChild(V),{header:e,iconHolder:v,headerTitle:f,headerSubtitle:w,closeButton:b,closeButtonWrapper:V,clearChatButton:C,clearChatButtonWrapper:W}},En=(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 Ar=t=>an({config:t.config,showClose:t.showClose,onClose:t.onClose,onClearChat:t.onClearChat}),Er=t=>{var S,x,E,C;let{config:n,showClose:r=!0,onClose:e}=t,o=(S=n==null?void 0:n.launcher)!=null?S:{},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=(x=o.title)!=null?x:"Chat Assistant",s.appendChild(i);let a=(E=o.closeButtonSize)!=null?E:"32px",u=g("div",""),c=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");c.style.height=a,c.style.width=a,c.type="button",c.setAttribute("aria-label","Close chat"),c.style.display=r?"":"none";let v=(C=o.closeButtonIconName)!=null?C:"x",d=oe(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=g("div");f.style.display="none";let w=g("span");return w.style.display="none",{header:s,iconHolder:f,headerTitle:i,headerSubtitle:w,closeButton:c,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},Tr=t=>{var b,N,M,R,ne,Y,_,q;let{config:n,showClose:r=!0,onClose:e,onClearChat:o}=t,s=(b=n==null?void 0:n.launcher)!=null?b:{},i=g("div","tvw-flex tvw-flex-col tvw-bg-cw-surface tvw-px-6 tvw-py-5 tvw-border-b-cw-divider"),a=g("div","tvw-flex tvw-items-center tvw-gap-3"),u=(N=s.headerIconSize)!=null?N:"56px",c=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-rounded-xl tvw-bg-cw-primary tvw-text-white tvw-text-2xl");c.style.height=u,c.style.width=u;let v=s.headerIconName;if(v){let U=parseFloat(u)||24,ue=oe(v,U*.5,"#ffffff",2);ue?c.replaceChildren(ue):c.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}"}else if(s.iconUrl){let U=g("img");U.src=s.iconUrl,U.alt="",U.className="tvw-rounded-xl tvw-object-cover",U.style.height=u,U.style.width=u,c.replaceChildren(U)}else c.textContent=(R=s.agentIconText)!=null?R:"\u{1F4AC}";let d=g("div","tvw-flex tvw-flex-col tvw-flex-1"),f=g("span","tvw-text-lg tvw-font-semibold");f.textContent=(ne=s.title)!=null?ne:"Chat Assistant";let w=g("span","tvw-text-sm tvw-text-cw-muted");w.textContent=(Y=s.subtitle)!=null?Y:"Here to help you get answers fast",d.append(f,w),a.append(c,d);let S=(_=s.closeButtonSize)!=null?_:"32px",x=g("div",""),E=g("button","tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none");E.style.height=S,E.style.width=S,E.type="button",E.setAttribute("aria-label","Close chat"),E.style.display=r?"":"none";let C=(q=s.closeButtonIconName)!=null?q:"x",W=oe(C,"20px",s.closeButtonColor||"",2);W?E.appendChild(W):E.textContent="\xD7",e&&E.addEventListener("click",e),x.appendChild(E),a.appendChild(x),i.appendChild(a);let V=g("div","tvw-mt-3 tvw-pt-3 tvw-border-t tvw-border-gray-100 tvw-text-xs tvw-text-cw-muted");return V.textContent="Online and ready to help",i.appendChild(V),{header:i,iconHolder:c,headerTitle:f,headerSubtitle:w,closeButton:E,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}},tr={default:Ar,minimal:Er,expanded:Tr},Mr=t=>{var n;return(n=tr[t])!=null?n:tr.default},Fn=(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=g("div");v.style.display="none";let d=g("span"),f=g("span"),w=g("button");w.style.display="none";let S=g("div");return S.style.display="none",{header:c,iconHolder:v,headerTitle:d,headerSubtitle:f,closeButton:w,closeButtonWrapper:S,clearChatButton:null,clearChatButtonWrapper:null}}let e=(i=n==null?void 0:n.layout)!=null?i:"default",s=Mr(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 ja=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'}},On=t=>{var $e,Se,se,he,Fe,Xe,Et,pe,G,pt,gt,vt,Dt,yt,Q,We,bt,xt,te,Oe,Ct,Wt,Lt,j,et,Ie,K,O,we,de;let{config:n}=t,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=(Se=($e=n==null?void 0:n.copy)==null?void 0:$e.inputPlaceholder)!=null?Se:"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=(he=(se=n==null?void 0:n.theme)==null?void 0:se.inputFontFamily)!=null?he:"sans-serif",a=(Xe=(Fe=n==null?void 0:n.theme)==null?void 0:Fe.inputFontWeight)!=null?Xe:"400";s.style.fontFamily=ja(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 re=Math.min(s.scrollHeight,v);s.style.height=`${re}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=(Et=n==null?void 0:n.sendButton)!=null?Et:{},w=(pe=f.useIcon)!=null?pe:!1,S=(G=f.iconText)!=null?G:"\u2191",x=f.iconName,E=(pt=f.tooltipText)!=null?pt:"Send message",C=(gt=f.showTooltip)!=null?gt:!1,W=(vt=f.size)!=null?vt:"40px",V=f.backgroundColor,b=f.textColor,N=g("div","tvw-send-button-wrapper"),M=g("button",w?"tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer":"tvw-rounded-button tvw-bg-cw-accent tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold disabled:tvw-opacity-50 tvw-cursor-pointer");if(M.type="submit",w){if(M.style.width=W,M.style.height=W,M.style.minWidth=W,M.style.minHeight=W,M.style.fontSize="18px",M.style.lineHeight="1",M.innerHTML="",x){let re=parseFloat(W)||24,Me=b&&typeof b=="string"&&b.trim()?b.trim():"currentColor",Ne=oe(x,re,Me,2);Ne?(M.appendChild(Ne),M.style.color=Me):(M.textContent=S,b?M.style.color=b:M.classList.add("tvw-text-white"))}else M.textContent=S,b?M.style.color=b:M.classList.add("tvw-text-white");V?M.style.backgroundColor=V:M.classList.add("tvw-bg-cw-primary")}else M.textContent=(yt=(Dt=n==null?void 0:n.copy)==null?void 0:Dt.sendButtonLabel)!=null?yt:"Send",b?M.style.color=b: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=""),C&&E){let re=g("div","tvw-send-button-tooltip");re.textContent=E,N.appendChild(re)}N.appendChild(M);let R=(Q=n==null?void 0:n.voiceRecognition)!=null?Q:{},ne=R.enabled===!0,Y=null,_=null,q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(ne&&q){_=g("div","tvw-send-button-wrapper"),Y=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer"),Y.type="button",Y.setAttribute("aria-label","Start voice recognition");let re=(We=R.iconName)!=null?We:"mic",Me=(bt=R.iconSize)!=null?bt:W,Ne=parseFloat(Me)||24,J=(xt=R.backgroundColor)!=null?xt:V,le=(te=R.iconColor)!=null?te:b;Y.style.width=Me,Y.style.height=Me,Y.style.minWidth=Me,Y.style.minHeight=Me,Y.style.fontSize="18px",Y.style.lineHeight="1";let Be=le||"currentColor",Je=oe(re,Ne,Be,1.5);Je?(Y.appendChild(Je),Y.style.color=Be):(Y.textContent="\u{1F3A4}",Y.style.color=Be),J?Y.style.backgroundColor=J:Y.classList.add("tvw-bg-cw-primary"),le?Y.style.color=le:!le&&!b&&Y.classList.add("tvw-text-white"),R.borderWidth&&(Y.style.borderWidth=R.borderWidth,Y.style.borderStyle="solid"),R.borderColor&&(Y.style.borderColor=R.borderColor),R.paddingX&&(Y.style.paddingLeft=R.paddingX,Y.style.paddingRight=R.paddingX),R.paddingY&&(Y.style.paddingTop=R.paddingY,Y.style.paddingBottom=R.paddingY),_.appendChild(Y);let ot=(Oe=R.tooltipText)!=null?Oe:"Start voice recognition";if(((Ct=R.showTooltip)!=null?Ct:!1)&&ot){let it=g("div","tvw-send-button-tooltip");it.textContent=ot,_.appendChild(it)}}let U=(Wt=n==null?void 0:n.attachments)!=null?Wt:{},ue=U.enabled===!0,B=null,Z=null,P=null,z=null;if(ue){z=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),z.style.display="none",P=g("input"),P.type="file",P.accept=((Lt=U.allowedTypes)!=null?Lt:gn).join(","),P.multiple=((j=U.maxFiles)!=null?j:4)>1,P.style.display="none",P.setAttribute("aria-label","Attach files"),Z=g("div","tvw-send-button-wrapper"),B=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),B.type="button",B.setAttribute("aria-label",(et=U.buttonTooltipText)!=null?et:"Attach file");let re=(Ie=U.buttonIconName)!=null?Ie:"paperclip",Me=W,Ne=parseFloat(Me)||40,J=Math.round(Ne*.6);B.style.width=Me,B.style.height=Me,B.style.minWidth=Me,B.style.minHeight=Me,B.style.fontSize="18px",B.style.lineHeight="1",B.style.backgroundColor="transparent",B.style.color="var(--cw-primary, #111827)",B.style.border="none",B.style.borderRadius="6px",B.style.transition="background-color 0.15s ease",B.addEventListener("mouseenter",()=>{B.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),B.addEventListener("mouseleave",()=>{B.style.backgroundColor="transparent"});let le=oe(re,J,"currentColor",1.5);le?B.appendChild(le):B.textContent="\u{1F4CE}",B.addEventListener("click",ot=>{ot.preventDefault(),P==null||P.click()}),Z.appendChild(B);let Be=(K=U.buttonTooltipText)!=null?K:"Attach file",Je=g("div","tvw-send-button-tooltip");Je.textContent=Be,Z.appendChild(Je)}o.addEventListener("click",re=>{re.target!==M&&re.target!==N&&re.target!==Y&&re.target!==_&&re.target!==B&&re.target!==Z&&s.focus()}),z&&(z.style.gap="8px",o.append(z)),P&&o.append(P),o.append(s);let Ce=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-w-full"),fe=g("div","tvw-flex tvw-items-center tvw-gap-2");Z&&fe.append(Z);let ze=g("div","tvw-flex tvw-items-center tvw-gap-1");_&&ze.append(_),ze.append(N),Ce.append(fe,ze),o.append(Ce);let dt=g("div","tvw-mt-2 tvw-text-right tvw-text-xs tvw-text-cw-muted"),Mt=(O=n==null?void 0:n.statusIndicator)!=null?O:{},Nt=(we=Mt.visible)!=null?we:!0;return dt.style.display=Nt?"":"none",dt.textContent=(de=Mt.idleText)!=null?de:"Online",r.append(e,o,dt),{footer:r,suggestions:e,composerForm:o,textarea:s,sendButton:M,sendButtonWrapper:N,micButton:Y,micButtonWrapper:_,statusText:dt,attachmentButton:B,attachmentButtonWrapper:Z,attachmentInput:P,attachmentPreviewsContainer:z,actionsRow:Ce,leftActions:fe,rightActions:ze}};var Yi=t=>{var u,c,v,d,f,w,S;if(!((c=(u=t==null?void 0:t.launcher)==null?void 0:u.enabled)!=null?c:!0)){let x=g("div","tvw-relative tvw-h-full tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0"),E=g("div","tvw-relative tvw-flex-1 tvw-flex tvw-flex-col tvw-min-h-0"),C=(d=(v=t==null?void 0:t.launcher)==null?void 0:v.width)!=null?d:"100%";return x.style.width=C,E.style.width="100%",x.appendChild(E),{wrapper:x,panel:E}}let r=(f=t==null?void 0:t.launcher)!=null?f:{},e=r.position&&Jt[r.position]?Jt[r.position]:Jt["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=(S=(w=t==null?void 0:t.launcher)==null?void 0:w.width)!=null?S: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}},Vi=(t,n=!0)=>{var w,S,x,E,C,W,V;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=t==null?void 0:t.layout)==null?void 0:w.header,o=((S=t==null?void 0:t.layout)==null?void 0:S.showHeader)!==!1,s=e?Fn(t,e,{showClose:n}):an({config:t,showClose:n}),i=g("div","tvw-widget-body tvw-flex tvw-flex-1 tvw-min-h-0 tvw-flex-col tvw-gap-6 tvw-overflow-y-auto tvw-bg-cw-container tvw-px-6 tvw-py-6");i.id="persona-scroll-container";let a=g("div","tvw-rounded-2xl tvw-bg-cw-surface tvw-p-6 tvw-shadow-sm"),u=g("h2","tvw-text-lg tvw-font-semibold tvw-text-cw-primary");u.textContent=(E=(x=t==null?void 0:t.copy)==null?void 0:x.welcomeTitle)!=null?E:"Hello \u{1F44B}";let c=g("p","tvw-mt-2 tvw-text-sm tvw-text-cw-muted");c.textContent=(W=(C=t==null?void 0:t.copy)==null?void 0:C.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",a.append(u,c);let v=g("div","tvw-flex tvw-flex-col tvw-gap-3");i.append(a,v);let d=On({config:t}),f=((V=t==null?void 0:t.layout)==null?void 0:V.showFooter)!==!1;return o?En(r,s,t):(s.header.style.display="none",En(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 qa=320,Ua=320,za=t=>!t.contentParts||t.contentParts.length===0?[]:t.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Ja=(t,n,r)=>{if(t.length===0)return null;try{let e=g("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=g("img");c.alt=((d=a.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${qa}px`,c.style.maxHeight=`${Ua}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}},Tn=()=>{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},Lr=(t,n,r)=>{let e={config:r!=null?r:{},streaming:!0,location:t,defaultRenderer:Tn};if(n){let o=n(e);if(o!==null)return o}return Tn()},Ka=(t,n)=>{let r=g("div","tvw-flex-shrink-0 tvw-w-8 tvw-h-8 tvw-rounded-full tvw-flex tvw-items-center tvw-justify-center tvw-text-sm"),e=n==="user"?t.userAvatar:t.assistantAvatar;if(e)if(e.startsWith("http")||e.startsWith("/")||e.startsWith("data:")){let o=g("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},Xi=(t,n)=>{let r=g("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},Ya=(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},Ir=(t,n,r)=>{var w,S,x,E,C,W;let e=(w=n.showCopy)!=null?w:!0,o=(S=n.showUpvote)!=null?S:!0,s=(x=n.showDownvote)!=null?x:!0,i=(E=n.visibility)!=null?E:"hover",a=(C=n.align)!=null?C:"right",u=(W=n.layout)!=null?W:"pill-inside",c={left:"tvw-message-actions-left",center:"tvw-message-actions-center",right:"tvw-message-actions-right"}[a],v={"pill-inside":"tvw-message-actions-pill","row-inside":"tvw-message-actions-row"}[u],d=g("div",`tvw-message-actions tvw-flex tvw-items-center tvw-gap-1 tvw-mt-2 ${c} ${v} ${i==="hover"?"tvw-message-actions-hover":""}`);d.id=`actions-${t.id}`,d.setAttribute("data-actions-for",t.id);let f=(V,b,N)=>{let M=document.createElement("button");M.className="tvw-message-action-btn",M.setAttribute("aria-label",b),M.setAttribute("title",b),M.setAttribute("data-action",N);let R=oe(V,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},Nn=(t,n,r,e,o,s)=>{var _,q,U,ue,B,Z,P;let i=r!=null?r:{},a=(_=i.layout)!=null?_:"bubble",u=i.avatar,c=i.timestamp,v=(q=u==null?void 0:u.show)!=null?q:!1,d=(U=c==null?void 0:c.show)!=null?U:!1,f=(ue=u==null?void 0:u.position)!=null?ue:"left",w=(B=c==null?void 0:c.position)!=null?B:"below",S=Ya(t.role,a),x=g("div",S.join(" "));x.id=`bubble-${t.id}`,x.setAttribute("data-message-id",t.id);let E=za(t),C=(P=(Z=t.content)==null?void 0:Z.trim())!=null?P:"",V=E.length>0&&C===Xs,b=document.createElement("div"),N=n({text:t.content,message:t,streaming:!!t.streaming,raw:t.rawContent}),M=null;if(V?(M=document.createElement("div"),M.innerHTML=N,M.style.display="none",b.appendChild(M)):b.innerHTML=N,d&&w==="inline"&&t.createdAt){let z=Xi(t,c);z.classList.add("tvw-ml-2","tvw-inline"),b.appendChild(z)}if(E.length>0){let z=Ja(E,!V&&!!C,()=>{V&&M&&(M.style.display="")});z?x.appendChild(z):V&&M&&(M.style.display="")}if(x.appendChild(b),d&&w==="below"&&t.createdAt){let z=Xi(t,c);z.classList.add("tvw-mt-1"),x.appendChild(z)}if(t.streaming&&t.role==="assistant"&&(!t.content||!t.content.trim())){let z=Lr("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);z&&x.appendChild(z)}if(t.role==="assistant"&&!t.streaming&&t.content&&t.content.trim()&&(e==null?void 0:e.enabled)!==!1&&e){let z=Ir(t,e,o);x.appendChild(z)}if(!v||t.role==="system")return x;let ne=g("div",`tvw-flex tvw-gap-2 ${t.role==="user"?"tvw-flex-row-reverse":""}`),Y=Ka(u,t.role);return f==="right"||f==="left"&&t.role==="user"?ne.append(x,Y):ne.append(Y,x),x.classList.remove("tvw-max-w-[85%]"),x.classList.add("tvw-max-w-[calc(85%-2.5rem)]"),ne},Gi=(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}):Nn(t,n,r,e,o,s)};var Dn=new Set,Qi=(t,n)=>{let r=Dn.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=oe(r?"chevron-up":"chevron-down",16,"currentColor",2);u?i.appendChild(u):i.textContent=r?"Hide":"Show"}o.style.display=r?"":"none"},kr=t=>{let n=t.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-${t.id}`,r.setAttribute("data-message-id",t.id),!n)return r;let e=Dn.has(t.id),o=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");o.type="button",o.setAttribute("aria-expanded",e?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=g("div","tvw-flex tvw-flex-col tvw-text-left"),i=g("span","tvw-text-xs tvw-text-cw-primary");i.textContent="Thinking...",s.appendChild(i);let a=g("span","tvw-text-xs tvw-text-cw-primary");a.textContent=ki(n),s.appendChild(a),n.status==="complete"?i.style.display="none":i.style.display="";let u=g("div","tvw-flex tvw-items-center"),v=oe(e?"chevron-up":"chevron-down",16,"currentColor",2);v?u.appendChild(v):u.textContent=e?"Hide":"Show";let d=g("div","tvw-flex tvw-items-center tvw-ml-auto");d.append(u),o.append(s,d);let f=g("div","tvw-border-t tvw-px-4 tvw-py-3");f.style.display=e?"":"none";let w=n.chunks.join(""),S=g("div","tvw-whitespace-pre-wrap tvw-text-xs tvw-leading-snug tvw-text-cw-muted");return S.textContent=w||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(S),(()=>{o.setAttribute("aria-expanded",e?"true":"false"),u.innerHTML="";let C=oe(e?"chevron-up":"chevron-down",16,"currentColor",2);C?u.appendChild(C):u.textContent=e?"Hide":"Show",f.style.display=e?"":"none"})(),r.append(o,f),r};var _n=new Set,Zi=(t,n,r)=>{var c;let e=_n.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=oe(e?"chevron-up":"chevron-down",16,v,2);d?u.appendChild(d):u.textContent=e?"Hide":"Show"}i.style.display=e?"":"none"},Wr=(t,n)=>{var x;let r=t.toolCall,e=(x=n==null?void 0:n.toolCall)!=null?x:{},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-${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=_n.has(t.id),i=g("button","tvw-flex tvw-w-full tvw-items-center tvw-justify-between tvw-gap-3 tvw-bg-transparent tvw-px-4 tvw-py-3 tvw-text-left tvw-cursor-pointer tvw-border-none");i.type="button",i.setAttribute("aria-expanded",s?"true":"false"),i.setAttribute("data-expand-header","true"),i.setAttribute("data-bubble-type","tool"),e.headerBackgroundColor&&(i.style.backgroundColor=e.headerBackgroundColor),e.headerPaddingX&&(i.style.paddingLeft=e.headerPaddingX,i.style.paddingRight=e.headerPaddingX),e.headerPaddingY&&(i.style.paddingTop=e.headerPaddingY,i.style.paddingBottom=e.headerPaddingY);let a=g("div","tvw-flex tvw-flex-col tvw-text-left"),u=g("span","tvw-text-xs tvw-text-cw-primary");e.headerTextColor&&(u.style.color=e.headerTextColor),u.textContent=Wi(r),a.appendChild(u);let c=g("div","tvw-flex tvw-items-center"),v=e.toggleTextColor||e.headerTextColor||"currentColor",d=oe(s?"chevron-up":"chevron-down",16,v,2);d?c.appendChild(d):c.textContent=s?"Hide":"Show";let f=g("div","tvw-flex tvw-items-center tvw-gap-2 tvw-ml-auto");f.append(c),i.append(a,f);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 E=g("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,w.appendChild(E)}if(r.args!==void 0){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Arguments";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=xs(r.args),E.append(C,W),w.appendChild(E)}if(r.chunks&&r.chunks.length){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Activity";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=r.chunks.join(`
|
|
16
|
-
`),E.append(C,W),w.appendChild(E)}if(r.status==="complete"&&r.result!==void 0){let E=g("div","tvw-space-y-1"),C=g("div","tvw-text-xs tvw-text-cw-muted");e.labelTextColor&&(C.style.color=e.labelTextColor),C.textContent="Result";let W=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");W.style.fontSize="0.75rem",W.style.lineHeight="1rem",e.codeBlockBackgroundColor&&(W.style.backgroundColor=e.codeBlockBackgroundColor),e.codeBlockBorderColor&&(W.style.borderColor=e.codeBlockBorderColor),e.codeBlockTextColor&&(W.style.color=e.codeBlockTextColor),W.textContent=xs(r.result),E.append(C,W),w.appendChild(E)}if(r.status==="complete"&&typeof r.duration=="number"){let E=g("div","tvw-text-xs tvw-text-cw-muted");e.contentTextColor&&(E.style.color=e.contentTextColor),E.textContent=`Duration: ${r.duration}ms`,w.appendChild(E)}return(()=>{i.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=e.toggleTextColor||e.headerTextColor||"currentColor",C=oe(s?"chevron-up":"chevron-down",16,E,2);C?c.appendChild(C):c.textContent=s?"Hide":"Show",w.style.display=s?"":"none"})(),o.append(i,w),o};var Pr=(t,n)=>{var x,E,C,W,V,b,N,M,R,ne,Y;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=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-${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=g("div","tvw-flex tvw-items-start tvw-gap-3 tvw-px-4 tvw-py-3"),a=g("div","tvw-flex-shrink-0 tvw-mt-0.5");a.setAttribute("data-approval-icon","true");let u=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",c=r.status==="approved"?"#16a34a":r.status==="denied"?"#dc2626":r.status==="timeout"?"#ca8a04":(x=e==null?void 0:e.titleColor)!=null?x:"currentColor",v=oe(u,20,c,2);v&&a.appendChild(v);let d=g("div","tvw-flex-1 tvw-min-w-0"),f=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=(E=e==null?void 0:e.title)!=null?E:"Approval Required",f.appendChild(w),!o){let _=g("span","tvw-inline-flex tvw-items-center tvw-px-2 tvw-py-0.5 tvw-rounded-full tvw-text-xs tvw-font-medium");_.setAttribute("data-approval-status",r.status),r.status==="approved"?(_.className+=" tvw-approval-badge-approved",_.textContent="Approved"):r.status==="denied"?(_.className+=" tvw-approval-badge-denied",_.textContent="Denied"):r.status==="timeout"&&(_.className+=" tvw-approval-badge-timeout",_.textContent="Timeout"),f.appendChild(_)}d.appendChild(f);let S=g("p","tvw-text-sm tvw-mt-0.5 tvw-text-cw-muted");if(e!=null&&e.descriptionColor&&(S.style.color=e.descriptionColor),S.textContent=r.description,d.appendChild(S),r.parameters){let _=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&&(_.style.backgroundColor=e.parameterBackgroundColor),e!=null&&e.parameterTextColor&&(_.style.color=e.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=xs(r.parameters),d.appendChild(_)}if(o){let _=g("div","tvw-flex tvw-gap-2 tvw-mt-2");_.setAttribute("data-approval-buttons","true");let q=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");q.type="button",q.style.backgroundColor=(C=e==null?void 0:e.approveButtonColor)!=null?C:"#16a34a",q.style.color=(W=e==null?void 0:e.approveButtonTextColor)!=null?W:"#ffffff",q.setAttribute("data-approval-action","approve");let U=oe("shield-check",14,(V=e==null?void 0:e.approveButtonTextColor)!=null?V:"#ffffff",2);U&&(U.style.marginRight="4px",q.appendChild(U));let ue=document.createTextNode((b=e==null?void 0:e.approveLabel)!=null?b:"Approve");q.appendChild(ue);let B=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");B.type="button",B.style.backgroundColor=(N=e==null?void 0:e.denyButtonColor)!=null?N:"transparent",B.style.color=(M=e==null?void 0:e.denyButtonTextColor)!=null?M:"#dc2626",B.style.border=`1px solid ${(R=e==null?void 0:e.denyButtonTextColor)!=null?R:"#fca5a5"}`,B.setAttribute("data-approval-action","deny");let Z=oe("shield-x",14,(ne=e==null?void 0:e.denyButtonTextColor)!=null?ne:"#dc2626",2);Z&&(Z.style.marginRight="4px",B.appendChild(Z));let P=document.createTextNode((Y=e==null?void 0:e.denyLabel)!=null?Y:"Deny");B.appendChild(P),_.append(q,B),d.appendChild(_)}return i.append(a,d),s.appendChild(i),s};var ea=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(w=>w.role==="user"))return;let v=document.createDocumentFragment(),d=o?o.isStreaming():!1,f=w=>{switch(w){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';case"sans-serif":default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};e.forEach(w=>{let S=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");S.type="button",S.textContent=w,S.disabled=d,a!=null&&a.fontFamily&&(S.style.fontFamily=f(a.fontFamily)),a!=null&&a.fontWeight&&(S.style.fontWeight=a.fontWeight),a!=null&&a.paddingX&&(S.style.paddingLeft=a.paddingX,S.style.paddingRight=a.paddingX),a!=null&&a.paddingY&&(S.style.paddingTop=a.paddingY,S.style.paddingBottom=a.paddingY),S.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(w))}),v.appendChild(S),n.push(S)}),t.appendChild(v)}}};var Ss=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 As=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 jn(t,n){n&&n.split(/\s+/).forEach(r=>r&&t.classList.add(r))}var Va={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"}},Xa={bg:"#f3f4f6",text:"#4b5563"},Ga=["flowName","stepName","reasoningText","text","name","tool","toolName"],Qa=100;function Za(t,n){let r={...Va,...n};if(r[t])return r[t];for(let e of Object.keys(r))if(e.endsWith("_")&&t.startsWith(e))return r[e];return Xa}function el(t,n){return`+${((t-n)/1e3).toFixed(3)}s`}function tl(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 nl(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 sl(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 rl(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 ol(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=g("div","tvw-bg-cw-container tvw-border-t tvw-border-cw-divider tvw-px-3 tvw-py-2 tvw-ml-4 tvw-mr-3 tvw-mb-1 tvw-rounded-b tvw-overflow-auto tvw-max-h-[300px]"),u=g("pre","tvw-m-0 tvw-whitespace-pre-wrap tvw-break-all tvw-text-[11px] tvw-text-cw-secondary tvw-font-mono");return u.textContent=e,a.appendChild(u),a}}function Hr(t,n,r,e,o,s,i,a){var f;let u=o.has(t.id),c=g("div","tvw-border-b tvw-border-cw-divider tvw-text-xs");jn(c,(f=e.classNames)==null?void 0:f.eventRow);let v=i.find(w=>w.renderEventStreamRow);if(v!=null&&v.renderEventStreamRow&&a){let w=v.renderEventStreamRow({event:t,index:n,config:a,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>s(t.id)});if(w)return c.appendChild(w),c}return c.appendChild(d()),c;function d(){var U,ue;let w=g("div",""),S=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");S.setAttribute("data-event-id",t.id);let x=g("span","tvw-flex-shrink-0 tvw-text-cw-muted tvw-w-4 tvw-text-center tvw-flex tvw-items-center tvw-justify-center"),E=oe(u?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let C=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-whitespace-nowrap tvw-flex-shrink-0 tvw-font-mono tvw-w-[70px]"),W=(U=e.timestampFormat)!=null?U:"relative";C.textContent=W==="relative"?el(t.timestamp,r):tl(t.timestamp);let V=null;e.showSequenceNumbers!==!1&&(V=g("span","tvw-text-[11px] tvw-text-cw-muted tvw-font-mono tvw-flex-shrink-0 tvw-w-[28px] tvw-text-right"),V.textContent=String(n+1));let b=Za(t.type,e.badgeColors),N=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");N.style.backgroundColor=b.bg,N.style.color=b.text,N.style.borderColor=b.text+"50",N.textContent=t.type;let M=(ue=e.descriptionFields)!=null?ue:Ga,R=nl(t.payload,M),ne=null;R&&(ne=g("span","tvw-text-[11px] tvw-text-cw-secondary tvw-truncate tvw-min-w-0"),ne.textContent=R);let Y=g("div","tvw-flex-1 tvw-min-w-0"),_=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"),q=oe("clipboard","12px","currentColor",1.5);return q&&_.appendChild(q),_.addEventListener("click",async B=>{B.stopPropagation(),await sl(rl(t)),_.innerHTML="";let Z=oe("check","12px","currentColor",1.5);Z&&_.appendChild(Z),setTimeout(()=>{_.innerHTML="";let P=oe("clipboard","12px","currentColor",1.5);P&&_.appendChild(P)},1500)}),S.appendChild(x),S.appendChild(C),V&&S.appendChild(V),S.appendChild(N),ne&&S.appendChild(ne),S.appendChild(Y),S.appendChild(_),w.appendChild(S),u&&w.appendChild(ol(t,i,a)),w}}function ta(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=g("div","tvw-event-stream-view tvw-flex tvw-flex-col tvw-flex-1 tvw-min-h-0");jn(f,d==null?void 0:d.panel);let w=[],S="",x="",E=null,C=[],W={},V=0,b=!1,N=0,M=0,R=!1,ne=null,Y=!1,_=0,q=new Set,U=new Map,ue="",B="",Z=null,P,z,Ce,fe,ze;function dt(){let K=g("div","tvw-flex tvw-flex-col tvw-flex-shrink-0"),O=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");jn(O,d==null?void 0:d.headerBar);let we=g("span","tvw-text-sm tvw-font-medium tvw-text-cw-primary tvw-whitespace-nowrap");we.textContent="Events",P=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"),P.textContent="0";let de=g("div","tvw-flex-1");z=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 re=g("option","");re.value="",re.textContent="All events",z.appendChild(re),Ce=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"),Ce.type="button",Ce.title="Copy All";let Ne=oe("clipboard-copy","12px","currentColor",1.5);Ne&&Ce.appendChild(Ne);let J=g("span","tvw-text-xs");J.textContent="Copy All",Ce.appendChild(J),O.appendChild(we),O.appendChild(P),O.appendChild(de),O.appendChild(z),O.appendChild(Ce);let le=g("div","tvw-relative tvw-px-4 tvw-py-2.5 tvw-border-b tvw-border-cw-divider tvw-bg-cw-surface");jn(le,d==null?void 0:d.searchBar);let Be=oe("search","14px","var(--cw-muted, #9ca3af)",1.5),Je=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");Be&&Je.appendChild(Be),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"),jn(fe,d==null?void 0:d.searchInput),fe.type="text",fe.placeholder="Search event payloads...",ze=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"),ze.type="button",ze.style.display="none";let ot=oe("x","12px","currentColor",2);return ot&&ze.appendChild(ot),le.appendChild(Je),le.appendChild(fe),le.appendChild(ze),K.appendChild(O),K.appendChild(le),K}let Mt,Nt=s.find(K=>K.renderEventStreamToolbar);if(Nt!=null&&Nt.renderEventStreamToolbar&&o){let K=Nt.renderEventStreamToolbar({config:o,defaultRenderer:()=>dt(),eventCount:n.getSize(),filteredCount:0,onFilterChange:O=>{S=O,gt(),yt()},onSearchChange:O=>{x=O,gt(),yt()}});Mt=K!=null?K:dt()}else Mt=dt();let $e=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");$e.style.display="none";let Se=g("div","tvw-flex-1 tvw-min-h-0 tvw-relative"),se=g("div","tvw-event-stream-list tvw-overflow-y-auto tvw-min-h-0");se.style.height="100%";let he=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");jn(he,d==null?void 0:d.scrollIndicator),he.style.display="none";let Fe=oe("arrow-down","12px","currentColor",2);Fe&&he.appendChild(Fe);let Xe=g("span","");he.appendChild(Xe);let Et=g("div","tvw-flex tvw-items-center tvw-justify-center tvw-h-full tvw-text-sm tvw-text-cw-muted");Et.style.display="none",Se.appendChild(se),Se.appendChild(Et),Se.appendChild(he),f.setAttribute("tabindex","0"),f.appendChild(Mt),f.appendChild($e),f.appendChild(Se);function pe(){let K=n.getAll(),O={};for(let J of K)O[J.type]=(O[J.type]||0)+1;let we=Object.keys(O).sort(),de=we.length!==C.length||!we.every((J,le)=>J===C[le]),re=!de&&we.some(J=>O[J]!==W[J]),Me=K.length!==Object.values(W).reduce((J,le)=>J+le,0);if(!de&&!re&&!Me||(C=we,W=O,!z))return;let Ne=z.value;if(z.options[0].textContent="All events",de){for(;z.options.length>1;)z.remove(1);for(let J of we){let le=g("option","");le.value=J,le.textContent=`${J} (${O[J]||0})`,z.appendChild(le)}Ne&&we.includes(Ne)?z.value=Ne:Ne&&(z.value="",S="")}else for(let J=1;J<z.options.length;J++){let le=z.options[J];le.textContent=`${le.value} (${O[le.value]||0})`}}function G(){let K=n.getAll();if(S&&(K=K.filter(O=>O.type===S)),x){let O=x.toLowerCase();K=K.filter(we=>we.type.toLowerCase().includes(O)||we.payload.toLowerCase().includes(O))}return K}function pt(){return S!==""||x!==""}function gt(){V=0,N=0,b=!1,he.style.display="none"}function vt(K){q.has(K)?q.delete(K):q.add(K),Z=K;let O=se.scrollTop,we=b;Y=!0,b=!0,yt(),se.scrollTop=O,b=we,Y=!1}function Dt(){return se.scrollHeight-se.scrollTop-se.clientHeight<=50}function yt(){M=Date.now(),R=!1,pe();let K=n.getEvictedCount();K>0?($e.textContent=`${K.toLocaleString()} older events truncated`,$e.style.display=""):$e.style.display="none",w=G();let O=w.length,we=n.getSize()>0;P&&(P.textContent=String(n.getSize())),O===0&&we&&pt()?(Et.textContent=x?`No events matching '${x}'`:"No events matching filter",Et.style.display="",se.style.display="none"):(Et.style.display="none",se.style.display=""),Ce&&(Ce.title=pt()?`Copy Filtered (${O})`:"Copy All"),b&&O>V&&(N+=O-V,Xe.textContent=`${N} new event${N===1?"":"s"}`,he.style.display=""),V=O;let de=n.getAll(),re=de.length>0?de[0].timestamp:0,Me=new Set(w.map(le=>le.id));for(let le of q)Me.has(le)||q.delete(le);let Ne=S!==ue||x!==B,J=U.size===0&&w.length>0;if(Ne||J||w.length===0){se.innerHTML="",U.clear();let le=document.createDocumentFragment();for(let Be=0;Be<w.length;Be++){let Je=Hr(w[Be],Be,re,i,q,vt,s,o);U.set(w[Be].id,Je),le.appendChild(Je)}se.appendChild(le),ue=S,B=x,Z=null}else{if(Z!==null){let Be=U.get(Z);if(Be&&Be.parentNode===se){let Je=w.findIndex(ot=>ot.id===Z);if(Je>=0){let ot=Hr(w[Je],Je,re,i,q,vt,s,o);se.insertBefore(ot,Be),Be.remove(),U.set(Z,ot)}}Z=null}let le=new Set(w.map(Be=>Be.id));for(let[Be,Je]of U)le.has(Be)||(Je.remove(),U.delete(Be));for(let Be=0;Be<w.length;Be++){let Je=w[Be];if(!U.has(Je.id)){let ot=Hr(Je,Be,re,i,q,vt,s,o);U.set(Je.id,ot),se.appendChild(ot)}}}b||(se.scrollTop=se.scrollHeight)}function Q(){if(Date.now()-M>=Qa){ne!==null&&(cancelAnimationFrame(ne),ne=null),yt();return}R||(R=!0,ne=requestAnimationFrame(()=>{ne=null,yt()}))}let We=(K,O)=>{if(!Ce)return;Ce.innerHTML="";let we=oe(K,"12px","currentColor",1.5);we&&Ce.appendChild(we);let de=g("span","tvw-text-xs");de.textContent="Copy All",Ce.appendChild(de),setTimeout(()=>{Ce.innerHTML="";let re=oe("clipboard-copy","12px","currentColor",1.5);re&&Ce.appendChild(re);let Me=g("span","tvw-text-xs");Me.textContent="Copy All",Ce.appendChild(Me),Ce.disabled=!1},O)},bt=async()=>{if(Ce){Ce.disabled=!0;try{let K;pt()?K=w:K=r?await r():n.getAll();let O=K.map(we=>{try{return JSON.parse(we.payload)}catch{return we.payload}});await navigator.clipboard.writeText(JSON.stringify(O,null,2)),We("check",1500)}catch{We("x",1500)}}},xt=()=>{z&&(S=z.value,gt(),yt())},te=()=>{!fe||!ze||(ze.style.display=fe.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{x=fe.value,gt(),yt()},150))},Oe=()=>{!fe||!ze||(fe.value="",x="",ze.style.display="none",E&&clearTimeout(E),gt(),yt())},Ct=()=>{if(Y)return;let K=se.scrollTop,O=K>_;_=K,Dt()&&O?(b=!1,N=0,he.style.display="none"):Dt()||(b=!0)},Wt=K=>{K.deltaY<0&&(b=!0)},Lt=()=>{se.scrollTop=se.scrollHeight,b=!1,N=0,he.style.display="none"},j=K=>{let O=K.target;if(!O||O.closest("button"))return;let we=O.closest("[data-event-id]");if(!we)return;let de=we.getAttribute("data-event-id");de&&vt(de)},et=K=>{if((K.metaKey||K.ctrlKey)&&K.key==="f"){K.preventDefault(),fe==null||fe.focus(),fe==null||fe.select();return}K.key==="Escape"&&(fe&&document.activeElement===fe?(Oe(),fe.blur(),f.focus()):e&&e())};Ce&&Ce.addEventListener("click",bt),z&&z.addEventListener("change",xt),fe&&fe.addEventListener("input",te),ze&&ze.addEventListener("click",Oe),se.addEventListener("scroll",Ct),se.addEventListener("wheel",Wt,{passive:!0}),se.addEventListener("click",j),he.addEventListener("click",Lt),f.addEventListener("keydown",et);function Ie(){E&&clearTimeout(E),ne!==null&&(cancelAnimationFrame(ne),ne=null),R=!1,U.clear(),Ce&&Ce.removeEventListener("click",bt),z&&z.removeEventListener("change",xt),fe&&fe.removeEventListener("input",te),ze&&ze.removeEventListener("click",Oe),se.removeEventListener("scroll",Ct),se.removeEventListener("wheel",Wt),se.removeEventListener("click",j),he.removeEventListener("click",Lt),f.removeEventListener("keydown",et)}return{element:f,update:Q,destroy:Ie}}}var na={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"}},Br=(t,n,r,e)=>{let o=t.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var S,x,E;if(s.dataset.enhanced==="true")return;let i=(S=s.dataset.tvForm)!=null?S:"init";s.dataset.enhanced="true";let a=(x=na[i])!=null?x:na.init;s.classList.add("tvw-form-card","tvw-space-y-4");let u=g("div","tvw-space-y-1"),c=g("h3","tvw-text-base tvw-font-semibold tvw-text-cw-primary");if(c.textContent=a.title,u.appendChild(c),a.description){let C=g("p","tvw-text-sm tvw-text-cw-muted");C.textContent=a.description,u.appendChild(C)}let v=document.createElement("form");v.className="tvw-form-grid tvw-space-y-3",a.fields.forEach(C=>{var M,R;let W=g("label","tvw-form-field tvw-flex tvw-flex-col tvw-gap-1");W.htmlFor=`${n.id}-${i}-${C.name}`;let V=g("span","tvw-text-xs tvw-font-medium tvw-text-cw-muted");V.textContent=C.label,W.appendChild(V);let b=(M=C.type)!=null?M:"text",N;b==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=b),N.className="tvw-rounded-xl tvw-border tvw-border-gray-200 tvw-bg-white tvw-px-3 tvw-py-2 tvw-text-sm tvw-text-cw-primary focus:tvw-outline-none focus:tvw-border-cw-primary",N.id=`${n.id}-${i}-${C.name}`,N.name=C.name,N.placeholder=(R=C.placeholder)!=null?R:"",C.required&&(N.required=!0),W.appendChild(N),v.appendChild(W)});let d=g("div","tvw-flex tvw-items-center tvw-justify-between tvw-gap-2"),f=g("div","tvw-text-xs tvw-text-cw-muted tvw-min-h-[1.5rem]"),w=g("button","tvw-inline-flex tvw-items-center tvw-rounded-full tvw-bg-cw-primary tvw-px-4 tvw-py-2 tvw-text-sm tvw-font-semibold tvw-text-white disabled:tvw-opacity-60 tvw-cursor-pointer");w.type="submit",w.textContent=(E=a.submitLabel)!=null?E:"Submit",d.appendChild(f),d.appendChild(w),v.appendChild(d),s.replaceChildren(u,v),v.addEventListener("submit",async C=>{var N,M;C.preventDefault();let W=(N=r.formEndpoint)!=null?N:"/form",V=new FormData(v),b={};V.forEach((R,ne)=>{b[ne]=R}),b.type=i,w.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(W,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(b)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let ne=await R.json();f.textContent=(M=ne.message)!=null?M:"Thanks! We'll be in touch soon.",ne.success&&ne.nextPrompt&&await e.sendMessage(String(ne.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{w.disabled=!1}})})};var Rr=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()}},Es=new Rr;var $r={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"},Fr={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:$r,darkTheme:Fr,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 nr(t){var n,r,e,o,s,i,a,u,c,v,d,f,w,S,x,E,C,W,V;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:{...(w=(f=tt.layout)==null?void 0:f.messages)==null?void 0:w.timestamp,...(x=(S=t.layout)==null?void 0:S.messages)==null?void 0:x.timestamp}},slots:{...(E=tt.layout)==null?void 0:E.slots,...(C=t.layout)==null?void 0:C.slots}},markdown:{...tt.markdown,...t.markdown,options:{...(W=tt.markdown)==null?void 0:W.options,...(V=t.markdown)==null?void 0:V.options}},messageActions:{...tt.messageActions,...t.messageActions}}:tt}var sa=()=>{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 il=t=>{let n=t.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:t},al=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},Ts=({text:t})=>{if(!t||!t.includes("{"))return null;try{let n=il(t),r=al(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}},Or=t=>typeof t=="string"?t:t==null?"":String(t),Mn={message:t=>t.type!=="message"?void 0:{handled:!0,displayText:Or(t.payload.text)},messageAndClick:(t,n)=>{var o;if(t.type!=="message_and_click")return;let r=t.payload,e=Or(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:Or(r.text)}}},ra=t=>Array.isArray(t)?t.map(n=>String(n)):[],Ms=t=>{let n=new Set(ra(t.getSessionMetadata().processedActionMessageIds)),r=()=>{n=new Set(ra(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 ll=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}},dl=t=>t.map(n=>({...n,streaming:!1})),sr=(t="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=n();return r?ll(r.getItem(t)):null},save:r=>{let e=n();if(e)try{let o={...r,messages:r.messages?dl(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 Nr=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)})}},qn=new Nr;var Un=require("partial-json");function cl(t){if(!t||typeof t!="object"||!("component"in t))return!1;let n=t.component;return typeof n=="string"&&n.length>0}function ul(t,n){if(!cl(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 rr(){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,Un.parse)(r,Un.STR|Un.OBJ),s=ul(o,r);s&&(t=s)}catch{}return n=r.length,t},reset:()=>{t=null,n=0}}}function oa(t){return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"&&"props"in t&&typeof t.props=="object"}function or(t,n){let{config:r,message:e,onPropsUpdate:o}=n,s=qn.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 ia(){let t=rr();return{processChunk:n=>t.processChunk(n),getDirective:()=>t.getExtractedDirective(),reset:()=>{t.reset()}}}function ir(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 ar(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 pl=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function lr(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=pl}=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 w=document.createElement("div");w.className="tvw-feedback-header";let S=document.createElement("h3");S.className="tvw-feedback-title",S.textContent=e,w.appendChild(S);let x=document.createElement("p");x.className="tvw-feedback-subtitle",x.textContent=o,w.appendChild(x),f.appendChild(w);let E=document.createElement("div");E.className="tvw-feedback-rating tvw-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];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",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)&<){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=`
|
|
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,C.forEach((ne,Y)=>{let _=Y<M;ne.classList.toggle("selected",_),ne.setAttribute("aria-checked",Y===M-1?"true":"false")})}),C.push(R),E.appendChild(R)}f.appendChild(E);let W=null;if(u){let M=document.createElement("div");M.className="tvw-feedback-comment-container",W=document.createElement("textarea"),W.className="tvw-feedback-comment",W.placeholder=s,W.rows=3,W.setAttribute("aria-label","Additional comments"),M.appendChild(W),f.appendChild(M)}let V=document.createElement("div");V.className="tvw-feedback-actions";let b=document.createElement("button");b.type="button",b.className="tvw-feedback-btn tvw-feedback-btn-skip",b.textContent=a,b.addEventListener("click",()=>{r==null||r(),v.remove()});let N=document.createElement("button");return N.type="button",N.className="tvw-feedback-btn tvw-feedback-btn-submit",N.textContent=i,N.addEventListener("click",async()=>{if(d===null){E.classList.add("tvw-feedback-shake"),setTimeout(()=>E.classList.remove("tvw-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let M=(W==null?void 0:W.value.trim())||void 0;await n(d,M),v.remove()}catch(M){N.disabled=!1,N.textContent=i,console.error("[CSAT Feedback] Failed to submit:",M)}}),V.appendChild(b),V.appendChild(N),f.appendChild(V),v.appendChild(f),v}function dr(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,w=document.createElement("div");w.className="tvw-feedback-content";let S=document.createElement("div");S.className="tvw-feedback-header";let x=document.createElement("h3");x.className="tvw-feedback-title",x.textContent=e,S.appendChild(x);let E=document.createElement("p");E.className="tvw-feedback-subtitle",E.textContent=o,S.appendChild(E),w.appendChild(S);let C=document.createElement("div");C.className="tvw-feedback-rating tvw-feedback-rating-nps",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Likelihood rating from 0 to 10");let W=document.createElement("div");W.className="tvw-feedback-labels";let V=document.createElement("span");V.className="tvw-feedback-label-low",V.textContent=c;let b=document.createElement("span");b.className="tvw-feedback-label-high",b.textContent=v,W.appendChild(V),W.appendChild(b);let N=document.createElement("div");N.className="tvw-feedback-numbers";let M=[];for(let q=0;q<=10;q++){let U=document.createElement("button");U.type="button",U.className="tvw-feedback-rating-btn tvw-feedback-number-btn",U.setAttribute("role","radio"),U.setAttribute("aria-checked","false"),U.setAttribute("aria-label",`Rating ${q} out of 10`),U.textContent=String(q),U.dataset.rating=String(q),q<=6?U.classList.add("tvw-feedback-detractor"):q<=8?U.classList.add("tvw-feedback-passive"):U.classList.add("tvw-feedback-promoter"),U.addEventListener("click",()=>{f=q,M.forEach((ue,B)=>{ue.classList.toggle("selected",B===q),ue.setAttribute("aria-checked",B===q?"true":"false")})}),M.push(U),N.appendChild(U)}C.appendChild(W),C.appendChild(N),w.appendChild(C);let R=null;if(u){let q=document.createElement("div");q.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"),q.appendChild(R),w.appendChild(q)}let ne=document.createElement("div");ne.className="tvw-feedback-actions";let Y=document.createElement("button");Y.type="button",Y.className="tvw-feedback-btn tvw-feedback-btn-skip",Y.textContent=a,Y.addEventListener("click",()=>{r==null||r(),d.remove()});let _=document.createElement("button");return _.type="button",_.className="tvw-feedback-btn tvw-feedback-btn-submit",_.textContent=i,_.addEventListener("click",async()=>{if(f===null){N.classList.add("tvw-feedback-shake"),setTimeout(()=>N.classList.remove("tvw-feedback-shake"),500);return}_.disabled=!0,_.textContent="Submitting...";try{let q=(R==null?void 0:R.value.trim())||void 0;await n(f,q),d.remove()}catch(q){_.disabled=!1,_.textContent=i,console.error("[NPS Feedback] Failed to submit:",q)}}),ne.appendChild(Y),ne.appendChild(_),w.appendChild(ne),d.appendChild(w),d}var zn="persona-chat-history",gl=30*1e3,ml={"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 fl(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=ml[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 hl(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 wl(t){try{let n=t==="local"?localStorage:sessionStorage,r="__persist_test__";return n.setItem(r,"1"),n.removeItem(r),n}catch{return null}}var Dr=t=>!t||typeof t!="object"?{}:{...t},aa=t=>t.map(n=>({...n,streaming:!1})),la=(t,n,r)=>{let e=t!=null&&t.markdown?bs(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):qs(s)}},cr=(t,n,r)=>{var os,is,as,ls,ds,cs,us,ps,gs,D,ke,_e,at,mt,Tt,st,m,Pe,H,y,L,ie,Ae,Ye,It,rt,St,ft,De,qe,ct,Ue;t.id&&t.id!=="persona-root"&&!t.getAttribute("data-persona-instance")&&t.setAttribute("data-persona-instance",t.id),t.id="persona-root";let e=nr(n),o=Es.getForInstance(e.plugins);e.components&&qn.registerAll(e.components);let s=sa(),i=(os=e.storageAdapter)!=null?os:sr(),a={},u=null,c=l=>{if(e.onStateLoaded)try{return e.onStateLoaded(l)}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",p)}return l};if(i!=null&&i.load)try{let l=i.load();if(l&&typeof l.then=="function")u=l.then(p=>{let h=p!=null?p:{messages:[],metadata:{}};return c(h)});else{let p=l!=null?l:{messages:[],metadata:{}},h=c(p);h.metadata&&(a=Dr(h.metadata)),(is=h.messages)!=null&&is.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:{}});(as=l.messages)!=null&&as.length&&(e={...e,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let v=()=>a,d=l=>{var h;a=(h=l({...a}))!=null?h:{},Gn()},f=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ts],w=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Mn.message,Mn.messageAndClick],S=Ms({parsers:f,handlers:w,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null});S.syncFromMetadata();let x=(ds=(ls=e.launcher)==null?void 0:ls.enabled)!=null?ds:!0,E=(us=(cs=e.launcher)==null?void 0:cs.autoExpand)!=null?us:!1,C=E,W=x,V=(gs=(ps=e.layout)==null?void 0:ps.header)==null?void 0:gs.layout,b=x?E:!0,N=!1,M=null,R=()=>{N=!0,M&&clearTimeout(M),M=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},ne=la(e,S,R),Y=(ke=(D=e.features)==null?void 0:D.showReasoning)!=null?ke:!0,_=(at=(_e=e.features)==null?void 0:_e.showToolCalls)!=null?at:!0,q=(Tt=(mt=e.features)==null?void 0:mt.showEventStreamToggle)!=null?Tt:!1,ue=`${(m=typeof e.persistState=="object"?(st=e.persistState)==null?void 0:st.keyPrefix:void 0)!=null?m:"persona-"}event-stream`,B=q?new As(ue):null,Z=(y=(H=(Pe=e.features)==null?void 0:Pe.eventStream)==null?void 0:H.maxEvents)!=null?y:2e3,P=q?new Ss(Z,B):null,z=null,Ce=!1,fe=null,ze=0;B==null||B.open().then(()=>P==null?void 0:P.restore()).catch(l=>{e.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let dt={onCopy:l=>{var p,h;s.emit("message:copy",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.id,"copy").catch(T=>{e.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",T)}),(h=(p=e.messageActions)==null?void 0:p.onCopy)==null||h.call(p,l)},onFeedback:l=>{var p,h;s.emit("message:feedback",l),$!=null&&$.isClientTokenMode()&&$.submitMessageFeedback(l.messageId,l.type).catch(T=>{e.debug&&console.error("[AgentWidget] Failed to submit feedback:",T)}),(h=(p=e.messageActions)==null?void 0:p.onFeedback)==null||h.call(p,l)}},Mt=(L=e.statusIndicator)!=null?L:{},Nt=l=>{var p,h,T,A;return l==="idle"?(p=Mt.idleText)!=null?p:Bt.idle:l==="connecting"?(h=Mt.connectingText)!=null?h:Bt.connecting:l==="connected"?(T=Mt.connectedText)!=null?T:Bt.connected:l==="error"?(A=Mt.errorText)!=null?A:Bt.error:Bt[l]},{wrapper:$e,panel:Se}=Yi(e),se=Vi(e,x),{container:he,body:Fe,messagesWrapper:Xe,suggestions:Et,textarea:pe,sendButton:G,sendButtonWrapper:pt,composerForm:gt,statusText:vt,introTitle:Dt,introSubtitle:yt,closeButton:Q,iconHolder:We,headerTitle:bt,headerSubtitle:xt,header:te,footer:Oe,actionsRow:Ct,leftActions:Wt,rightActions:Lt}=se,j=se.micButton,et=se.micButtonWrapper,Ie=se.attachmentButton,K=se.attachmentButtonWrapper,O=se.attachmentInput,we=se.attachmentPreviewsContainer,de=null;(ie=e.attachments)!=null&&ie.enabled&&O&&we&&(de=An.fromConfig(e.attachments),de.setPreviewsContainer(we),O.addEventListener("change",l=>{let p=l.target;de==null||de.handleFileSelect(p.files),p.value=""}));let re=o.find(l=>l.renderHeader);if(re!=null&&re.renderHeader){let l=re.renderHeader({config:e,defaultRenderer:()=>{let p=an({config:e,showClose:x});return En(he,p,e),p.header},onClose:()=>nt(!1,"user")});if(l){let p=he.querySelector(".tvw-border-b-cw-divider");p&&(p.replaceWith(l),te=l)}}let Me=()=>{var p,h,T,A;if(!P)return;if(Ce=!0,!z&&P&&(z=ta({buffer:P,getFullHistory:()=>P.getAllFromStore(),onClose:()=>Ne(),config:e,plugins:o})),z&&(Fe.style.display="none",(p=Oe.parentNode)==null||p.insertBefore(z.element,Oe),z.update()),J){J.classList.remove("tvw-text-cw-muted"),J.classList.add("tvw-text-cw-accent"),J.style.boxShadow="inset 0 0 0 1.5px var(--cw-accent, #3b82f6)";let F=(A=(T=(h=e.features)==null?void 0:h.eventStream)==null?void 0:T.classNames)==null?void 0:A.toggleButtonActive;F&&F.split(/\s+/).forEach(ve=>ve&&J.classList.add(ve))}let l=()=>{if(!Ce)return;let F=Date.now();F-ze>=200&&(z==null||z.update(),ze=F),fe=requestAnimationFrame(l)};ze=0,fe=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},Ne=()=>{var l,p,h;if(Ce){if(Ce=!1,z&&z.element.remove(),Fe.style.display="",J){J.classList.remove("tvw-text-cw-accent"),J.classList.add("tvw-text-cw-muted"),J.style.boxShadow="";let T=(h=(p=(l=e.features)==null?void 0:l.eventStream)==null?void 0:p.classNames)==null?void 0:h.toggleButtonActive;T&&T.split(/\s+/).forEach(A=>A&&J.classList.remove(A))}fe!==null&&(cancelAnimationFrame(fe),fe=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},J=null;if(q){let l=(Ye=(Ae=e.features)==null?void 0:Ae.eventStream)==null?void 0:Ye.classNames,p="tvw-inline-flex tvw-items-center tvw-justify-center tvw-rounded-full tvw-text-cw-muted hover:tvw-bg-gray-100 tvw-cursor-pointer tvw-border-none tvw-bg-transparent tvw-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");J=g("button",p),J.style.width="28px",J.style.height="28px",J.type="button",J.setAttribute("aria-label","Event Stream"),J.title="Event Stream";let h=oe("activity","18px","currentColor",1.5);h&&J.appendChild(h);let T=se.clearChatButtonWrapper,A=se.closeButtonWrapper,F=T||A;F&&F.parentNode===te?te.insertBefore(J,F):te.appendChild(J),J.addEventListener("click",()=>{Ce?Ne():Me()})}let le=o.find(l=>l.renderComposer);if(le!=null&&le.renderComposer){let l=le.renderComposer({config:e,defaultRenderer:()=>On({config:e}).footer,onSubmit:p=>{$&&!$.isStreaming()&&$.sendMessage(p)},disabled:!1});l&&(Oe.replaceWith(l),Oe=l)}(()=>{var T,A;let l=(A=(T=e.layout)==null?void 0:T.slots)!=null?A:{},p=F=>{switch(F){case"body-top":return he.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6")||null;case"messages":return Xe;case"footer-top":return Et;case"composer":return gt;case"footer-bottom":return vt;default:return null}},h=(F,ve)=>{var ae;switch(F){case"header-left":case"header-center":case"header-right":if(F==="header-left")te.insertBefore(ve,te.firstChild);else if(F==="header-right")te.appendChild(ve);else{let ce=te.querySelector(".tvw-flex-col");ce?(ae=ce.parentNode)==null||ae.insertBefore(ve,ce.nextSibling):te.appendChild(ve)}break;case"body-top":{let ce=Fe.querySelector(".tvw-rounded-2xl.tvw-bg-cw-surface.tvw-p-6");ce?ce.replaceWith(ve):Fe.insertBefore(ve,Fe.firstChild);break}case"body-bottom":Fe.appendChild(ve);break;case"footer-top":Et.replaceWith(ve);break;case"footer-bottom":vt.replaceWith(ve);break;default:break}};for(let[F,ve]of Object.entries(l))if(ve)try{let ae=ve({config:e,defaultContent:()=>p(F)});ae&&h(F,ae)}catch(ae){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${F}":`,ae)}})();let Je=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let T=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!T)return;let A=T.getAttribute("data-message-id");if(!A)return;let F=h.getAttribute("data-bubble-type");F==="reasoning"?(Dn.has(A)?Dn.delete(A):Dn.add(A),Qi(A,T)):F==="tool"&&(_n.has(A)?_n.delete(A):_n.add(A),Zi(A,T,e))};Xe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))}),Xe.addEventListener("keydown",l=>{let p=l.target;(l.key==="Enter"||l.key===" ")&&p.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Je(l))});let ot=new Map;Xe.addEventListener("click",l=>{var ve;let h=l.target.closest(".tvw-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let T=h.closest("[data-actions-for]");if(!T)return;let A=T.getAttribute("data-actions-for");if(!A)return;let F=h.getAttribute("data-action");if(F==="copy"){let ce=$.getMessages().find(xe=>xe.id===A);if(ce&&dt.onCopy){let xe=ce.content||"";navigator.clipboard.writeText(xe).then(()=>{h.classList.add("tvw-message-action-success");let ge=oe("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("tvw-message-action-success");let Ee=oe("copy",14,"currentColor",2);Ee&&(h.innerHTML="",h.appendChild(Ee))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),dt.onCopy(ce)}}else if(F==="upvote"||F==="downvote")if(((ve=ot.get(A))!=null?ve:null)===F)ot.delete(A),h.classList.remove("tvw-message-action-active");else{let xe=F==="upvote"?"downvote":"upvote",ge=T.querySelector(`[data-action="${xe}"]`);ge&&ge.classList.remove("tvw-message-action-active"),ot.set(A,F),h.classList.add("tvw-message-action-active");let ee=$.getMessages().find(I=>I.id===A);ee&&dt.onFeedback&&dt.onFeedback({type:F,messageId:ee.id,message:ee})}}),Xe.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let T=h.closest(".vanilla-approval-bubble");if(!T)return;let A=T.getAttribute("data-message-id");if(!A)return;let F=h.getAttribute("data-approval-action");if(!F)return;let ve=F==="approve"?"approved":"denied",ce=$.getMessages().find(ge=>ge.id===A);if(!(ce!=null&&ce.approval))return;let xe=T.querySelector("[data-approval-buttons]");xe&&xe.querySelectorAll("button").forEach(Ee=>{Ee.disabled=!0,Ee.style.opacity="0.5",Ee.style.cursor="not-allowed"}),$.resolveApproval(ce.approval,ve)}),Se.appendChild(he),t.appendChild($e);let In=()=>{var me,ye,Ve,He,ht,Ht,X,je,Xt,zt,pn,Ns,yr,ut,Ds,ms;let l=(ye=(me=e.launcher)==null?void 0:me.sidebarMode)!=null?ye:!1,p=l||((He=(Ve=e.launcher)==null?void 0:Ve.fullHeight)!=null?He:!1),h=(ht=e.theme)!=null?ht:{},T=(X=(Ht=e.launcher)==null?void 0:Ht.position)!=null?X:"bottom-left",A=T==="bottom-left"||T==="top-left",F=l?"none":"1px solid var(--tvw-cw-border)",ve=l?A?"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)",ae=l?"0":"16px",ce=(je=h.panelBorder)!=null?je:F,xe=(Xt=h.panelShadow)!=null?Xt:ve,ge=(zt=h.panelBorderRadius)!=null?zt:ae;t.style.cssText="",$e.style.cssText="",Se.style.cssText="",he.style.cssText="",Fe.style.cssText="",Oe.style.cssText="";let Ee=(Ns=(pn=e==null?void 0:e.launcher)==null?void 0:pn.width)!=null?Ns:e==null?void 0:e.launcherWidth,ee=Ee!=null?Ee:"min(400px, calc(100vw - 24px))";l||(Se.style.width=ee,Se.style.maxWidth=ee),Se.style.boxShadow=xe,Se.style.borderRadius=ge,he.style.border=ce,he.style.borderRadius=ge;let I=((yr=e.launcher)==null?void 0:yr.enabled)===!1;if(p&&(t.style.display="flex",t.style.flexDirection="column",t.style.height="100%",t.style.minHeight="0",$e.style.display="flex",$e.style.flexDirection="column",$e.style.flex="1 1 0%",$e.style.minHeight="0",$e.style.maxHeight="100%",$e.style.height="100%",I&&($e.style.overflow="hidden"),Se.style.display="flex",Se.style.flexDirection="column",Se.style.flex="1 1 0%",Se.style.minHeight="0",Se.style.maxHeight="100%",Se.style.height="100%",Se.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",Fe.style.flex="1 1 0%",Fe.style.minHeight="0",Fe.style.overflowY="auto",Oe.style.flexShrink="0"),$e.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&&!I&&((ut=Jt[T])!=null?ut:Jt["bottom-right"]).split(" ").forEach(bn=>$e.classList.add(bn)),l){let yn=(ms=(Ds=e.launcher)==null?void 0:Ds.sidebarWidth)!=null?ms:"420px";$e.style.cssText=`
|
|
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=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
top: 0 !important;
|
|
23
23
|
bottom: 0 !important;
|
|
24
|
-
width: ${
|
|
24
|
+
width: ${An} !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
|
-
${
|
|
32
|
-
`,
|
|
31
|
+
${S?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
32
|
+
`,te.style.cssText=`
|
|
33
33
|
position: relative !important;
|
|
34
34
|
display: flex !important;
|
|
35
35
|
flex-direction: column !important;
|
|
@@ -40,9 +40,9 @@
|
|
|
40
40
|
min-height: 0 !important;
|
|
41
41
|
margin: 0 !important;
|
|
42
42
|
padding: 0 !important;
|
|
43
|
-
box-shadow: ${
|
|
44
|
-
border-radius: ${
|
|
45
|
-
`,
|
|
43
|
+
box-shadow: ${be} !important;
|
|
44
|
+
border-radius: ${pe} !important;
|
|
45
|
+
`,te.style.setProperty("width","100%","important"),te.style.setProperty("max-width","100%","important"),Be.style.cssText=`
|
|
46
46
|
display: flex !important;
|
|
47
47
|
flex-direction: column !important;
|
|
48
48
|
flex: 1 1 0% !important;
|
|
@@ -51,13 +51,13 @@
|
|
|
51
51
|
min-height: 0 !important;
|
|
52
52
|
max-height: 100% !important;
|
|
53
53
|
overflow: hidden !important;
|
|
54
|
-
border-radius: ${
|
|
55
|
-
border: ${
|
|
56
|
-
`,
|
|
54
|
+
border-radius: ${pe} !important;
|
|
55
|
+
border: ${ue} !important;
|
|
56
|
+
`,Je.style.cssText=`
|
|
57
57
|
flex-shrink: 0 !important;
|
|
58
58
|
border-top: none !important;
|
|
59
59
|
padding: 8px 16px 12px 16px !important;
|
|
60
|
-
`}if(!I){let yn="max-height: -moz-available !important; max-height: stretch !important;",bn=l?"":"padding-top: 1.25em !important;";$e.style.cssText+=yn+bn}};In(),er(t,e);let it=[];q&&it.push(()=>{fe!==null&&(cancelAnimationFrame(fe),fe=null),z==null||z.destroy(),z=null,P==null||P.destroy(),P=null,B=null});let Kt=null,Jn=()=>{Kt&&(Kt(),Kt=null),e.colorScheme==="auto"&&(Kt=zi(()=>{er(t,e)}))};Jn(),it.push(()=>{Kt&&(Kt(),Kt=null)});let dn=ea(Et),Yt=null,$,cn=!1,Qt=!0,mn=0,Kn=0,Zt=null,en=!1,kn=0,Wn=!1,Ls=125,Is=2e3,ks=5,Yn=50,Pn=new Map,Ke={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Vn=(rt=(It=e.voiceRecognition)==null?void 0:It.autoResume)!=null?rt:!1,Xn=l=>{s.emit("voice:state",{active:Ke.active,source:l,timestamp:Date.now()})},tn=()=>{d(l=>({...l,voiceState:{active:Ke.active,timestamp:Date.now(),manuallyDeactivated:Ke.manuallyDeactivated}}))},Ws=()=>{var T,A;if(((T=e.voiceRecognition)==null?void 0:T.enabled)===!1)return;let l=Dr(a.voiceState),p=!!l.active,h=Number((A=l.timestamp)!=null?A:0);Ke.manuallyDeactivated=!!l.manuallyDeactivated,p&&Date.now()-h<gl&&setTimeout(()=>{Ke.active||(Ke.manuallyDeactivated=!1,vn("restore"))},1e3)},Ps=()=>$?aa($.getMessages()).filter(l=>!l.__skipPersist):[];function Gn(l){if(!(i!=null&&i.save))return;let h={messages:l?aa(l):$?Ps():[],metadata:a};try{let T=i.save(h);T instanceof Promise&&T.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)})}catch(T){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)}}let fn=(l=!1)=>{if(!Qt)return;let p=Date.now();en&&p<kn&&!l||(en&&p>=kn&&(en=!1),!(!l&&!cn)&&(p-Kn<Ls||(Kn=p,Zt&&cancelAnimationFrame(Zt),Zt=requestAnimationFrame(()=>{en||!Qt||(Wn=!0,Fe.scrollTop=Fe.scrollHeight,mn=Fe.scrollTop,requestAnimationFrame(()=>{Wn=!1}),Zt=null)}))))},nn=null,Hs=()=>$e.querySelector("#persona-scroll-container")||Fe,Bs=(l,p=500)=>{let h=l.scrollTop,T=l.clientHeight,A=l.scrollHeight,F=A-h;if(h+T>=A-2||Math.abs(F)<5)return;nn!==null&&(cancelAnimationFrame(nn),nn=null);let ae=performance.now(),ce=ge=>1-Math.pow(1-ge,3),xe=ge=>{let Ee=l.scrollHeight;Ee!==A&&(A=Ee,F=A-h);let ee=ge-ae,I=Math.min(ee/p,1),me=ce(I),ye=h+F*me;l.scrollTop=ye,I<1?nn=requestAnimationFrame(xe):(l.scrollTop=l.scrollHeight,nn=null)};nn=requestAnimationFrame(xe)},Rs=l=>{let p=new Map;l.forEach(h=>{let T=Pn.get(h.id);p.set(h.id,{streaming:h.streaming,role:h.role}),!T&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(T!=null&&T.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(T?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),Pn.clear(),p.forEach((h,T)=>{Pn.set(T,h)})},hn=(l,p,h)=>{var xe,ge,Ee,ee;let T=document.createElement("div"),F=(()=>{var me;let I=o.find(ye=>ye.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((me=e.loadingIndicator)!=null&&me.render)return e.loadingIndicator.render})();p.forEach(I=>{var ht,Ht;let me=null,ye=o.find(X=>!!(I.variant==="reasoning"&&X.renderReasoning||I.variant==="tool"&&X.renderToolCall||I.variant==="approval"&&X.renderApproval||!I.variant&&X.renderMessage)),Ve=(ht=e.layout)==null?void 0:ht.messages;if(ye)if(I.variant==="reasoning"&&I.reasoning&&ye.renderReasoning){if(!Y)return;me=ye.renderReasoning({message:I,defaultRenderer:()=>kr(I),config:e})}else if(I.variant==="tool"&&I.toolCall&&ye.renderToolCall){if(!_)return;me=ye.renderToolCall({message:I,defaultRenderer:()=>Wr(I,e),config:e})}else if(I.variant==="approval"&&I.approval&&ye.renderApproval){if(e.approval===!1)return;me=ye.renderApproval({message:I,defaultRenderer:()=>Pr(I,e),config:e})}else ye.renderMessage&&(me=ye.renderMessage({message:I,defaultRenderer:()=>{let X=Nn(I,h,Ve,e.messageActions,dt,{loadingIndicatorRenderer:F,widgetConfig:e});return I.role!=="user"&&Br(X,I,e,$),X},config:e}));if(!me&&I.role==="assistant"&&!I.variant&&e.enableComponentStreaming!==!1&&ir(I)){let je=ar(I);if(je){let Xt=or(je,{config:e,message:I,transform:h});if(Xt){let zt=document.createElement("div");if(zt.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(" "),zt.id=`bubble-${I.id}`,zt.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let pn=document.createElement("div");pn.className="tvw-mb-3 tvw-text-sm tvw-leading-relaxed",pn.innerHTML=h({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),zt.appendChild(pn)}zt.appendChild(Xt),me=zt}}}if(!me)if(I.variant==="reasoning"&&I.reasoning){if(!Y)return;me=kr(I)}else if(I.variant==="tool"&&I.toolCall){if(!_)return;me=Wr(I,e)}else if(I.variant==="approval"&&I.approval){if(e.approval===!1)return;me=Pr(I,e)}else{let X=(Ht=e.layout)==null?void 0:Ht.messages;X!=null&&X.renderUserMessage&&I.role==="user"?me=X.renderUserMessage({message:I,config:e,streaming:!!I.streaming}):X!=null&&X.renderAssistantMessage&&I.role==="assistant"?me=X.renderAssistantMessage({message:I,config:e,streaming:!!I.streaming}):me=Nn(I,h,X,e.messageActions,dt,{loadingIndicatorRenderer:F,widgetConfig:e}),I.role!=="user"&&me&&Br(me,I,e,$)}let He=document.createElement("div");He.className="tvw-flex",He.id=`wrapper-${I.id}`,He.setAttribute("data-wrapper-id",I.id),I.role==="user"&&He.classList.add("tvw-justify-end"),He.appendChild(me),T.appendChild(He)});let ve=p.some(I=>I.role==="assistant"&&I.streaming),ae=p[p.length-1],ce=(ae==null?void 0:ae.role)==="assistant"&&!ae.streaming;if(cn&&p.some(I=>I.role==="user")&&!ve&&!ce){let I={config:e,streaming:!0,location:"standalone",defaultRenderer:Tn},me=o.find(Ve=>Ve.renderLoadingIndicator),ye=null;if(me!=null&&me.renderLoadingIndicator&&(ye=me.renderLoadingIndicator(I)),ye===null&&((xe=e.loadingIndicator)!=null&&xe.render)&&(ye=e.loadingIndicator.render(I)),ye===null&&(ye=Tn()),ye){let Ve=document.createElement("div"),He=((ge=e.loadingIndicator)==null?void 0:ge.showBubble)!==!1;Ve.className=He?["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(ye);let ht=document.createElement("div");ht.className="tvw-flex",ht.id="wrapper-typing-indicator",ht.setAttribute("data-wrapper-id","typing-indicator"),ht.appendChild(Ve),T.appendChild(ht)}}if(!cn&&p.length>0){let I=p[p.length-1],me={config:e,lastMessage:I,messageCount:p.length},ye=o.find(He=>He.renderIdleIndicator),Ve=null;if(ye!=null&&ye.renderIdleIndicator&&(Ve=ye.renderIdleIndicator(me)),Ve===null&&((Ee=e.loadingIndicator)!=null&&Ee.renderIdle)&&(Ve=e.loadingIndicator.renderIdle(me)),Ve){let He=document.createElement("div"),ht=((ee=e.loadingIndicator)==null?void 0:ee.showBubble)!==!1;He.className=ht?["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(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(Ve);let Ht=document.createElement("div");Ht.className="tvw-flex",Ht.id="wrapper-idle-indicator",Ht.setAttribute("data-wrapper-id","idle-indicator"),Ht.appendChild(He),T.appendChild(Ht)}}Ki(l,T),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=Hs();Bs(I)})})},wn=()=>{x&&(b?($e.classList.remove("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-95","tvw-opacity-0"),Se.classList.add("tvw-scale-100","tvw-opacity-100"),Ge?Ge.element.style.display="none":Qe&&(Qe.style.display="none")):($e.classList.add("tvw-pointer-events-none","tvw-opacity-0"),Se.classList.remove("tvw-scale-100","tvw-opacity-100"),Se.classList.add("tvw-scale-95","tvw-opacity-0"),Ge?Ge.element.style.display="":Qe&&(Qe.style.display="")))},nt=(l,p="user")=>{if(!x||b===l)return;let h=b;b=l,wn(),b&&(un(),fn(!0));let T={open:b,source:p,timestamp:Date.now()};b&&!h?s.emit("widget:opened",T):!b&&h&&s.emit("widget:closed",T),s.emit("widget:state",{open:b,launcherEnabled:x,voiceActive:Ke.active,streaming:$.isStreaming()})},Hn=l=>{G.disabled=l,j&&(j.disabled=l),dn.buttons.forEach(p=>{p.disabled=l})},Qn=()=>{var A,F,ve,ae,ce,xe,ge,Ee,ee,I,me,ye,Ve,He;Dt.textContent=(F=(A=e.copy)==null?void 0:A.welcomeTitle)!=null?F:"Hello \u{1F44B}",yt.textContent=(ae=(ve=e.copy)==null?void 0:ve.welcomeSubtitle)!=null?ae:"Ask anything about your account or products.",pe.placeholder=(xe=(ce=e.copy)==null?void 0:ce.inputPlaceholder)!=null?xe:"How can I help...",((Ee=(ge=e.sendButton)==null?void 0:ge.useIcon)!=null?Ee:!1)||(G.textContent=(I=(ee=e.copy)==null?void 0:ee.sendButtonLabel)!=null?I:"Send");let p=(ye=(me=e.theme)==null?void 0:me.inputFontFamily)!=null?ye:"sans-serif",h=(He=(Ve=e.theme)==null?void 0:Ve.inputFontWeight)!=null?He:"400",T=ht=>{switch(ht){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'}};pe.style.fontFamily=T(p),pe.style.fontWeight=h};e.clientToken&&(e={...e,getStoredSessionId:()=>{let l=a.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{d(p=>({...p,sessionId:l}))}}),$=new $n(e,{onMessagesChanged(l){hn(Xe,l,ne),$&&(l.some(A=>A.role==="user")?dn.render([],$,pe,l):dn.render(e.suggestionChips,$,pe,l,e.suggestionChipsConfig)),fn(!cn),Rs(l);let p=[...l].reverse().find(T=>T.role==="user"),h=Ke.lastUserMessageId;p&&p.id!==h&&(Ke.lastUserMessageId=p.id,s.emit("user:message",p)),Ke.lastUserMessageWasVoice=!!(p!=null&&p.viaVoice),Gn(l)},onStatusChanged(l){var T;let p=(T=e.statusIndicator)!=null?T:{},h=A=>{var F,ve,ae,ce;return A==="idle"?(F=p.idleText)!=null?F:Bt.idle:A==="connecting"?(ve=p.connectingText)!=null?ve:Bt.connecting:A==="connected"?(ae=p.connectedText)!=null?ae:Bt.connected:A==="error"?(ce=p.errorText)!=null?ce:Bt.error:Bt[A]};vt.textContent=h(l)},onStreamingChanged(l){cn=l,Hn(l),$&&hn(Xe,$.getMessages(),ne),l||fn(!0)}}),e.clientToken&&$.initClientSession().catch(l=>{e.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),P&&$.setSSEEventCallback((l,p)=>{P==null||P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(p)})}),u&&u.then(l=>{var p;l&&(l.metadata&&(a=Dr(l.metadata),S.syncFromMetadata()),(p=l.messages)!=null&&p.length&&$.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Zn=l=>{var A;l.preventDefault();let p=pe.value.trim(),h=(A=de==null?void 0:de.hasAttachments())!=null?A:!1;if(!p&&!h)return;let T;h&&(T=[],T.push(...de.getContentParts()),p&&T.push(Gs(p))),pe.value="",pe.style.height="auto",$.sendMessage(p,{contentParts:T}),h&&de.clearAttachments()},es=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},ts=async l=>{var h;if(((h=e.attachments)==null?void 0:h.enabled)!==!0||!de)return;let p=fl(l.clipboardData);p.length!==0&&(l.preventDefault(),await de.handleFiles(p))},Rt=null,_t=!1,sn=null,Vt=null,ns=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,vn=(l="user")=>{var F,ve,ae,ce;if(_t||$.isStreaming())return;let p=ns();if(!p)return;Rt=new p;let T=(ve=((F=e.voiceRecognition)!=null?F:{}).pauseDuration)!=null?ve:2e3;Rt.continuous=!0,Rt.interimResults=!0,Rt.lang="en-US";let A=pe.value;Rt.onresult=xe=>{let ge="",Ee="";for(let I=0;I<xe.results.length;I++){let me=xe.results[I],ye=me[0].transcript;me.isFinal?ge+=ye+" ":Ee=ye}let ee=A+ge+Ee;pe.value=ee,sn&&clearTimeout(sn),(ge||Ee)&&(sn=window.setTimeout(()=>{let I=pe.value.trim();I&&Rt&&_t&&(Ut(),pe.value="",pe.style.height="auto",$.sendMessage(I,{viaVoice:!0}))},T))},Rt.onerror=xe=>{xe.error!=="no-speech"&&Ut()},Rt.onend=()=>{if(_t){let xe=pe.value.trim();xe&&xe!==A.trim()&&(pe.value="",pe.style.height="auto",$.sendMessage(xe,{viaVoice:!0})),Ut()}};try{if(Rt.start(),_t=!0,Ke.active=!0,l!=="system"&&(Ke.manuallyDeactivated=!1),Xn(l),tn(),j){Vt={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor};let xe=(ae=e.voiceRecognition)!=null?ae:{},ge=(ce=xe.recordingBackgroundColor)!=null?ce:"#ef4444",Ee=xe.recordingIconColor,ee=xe.recordingBorderColor;if(j.classList.add("tvw-voice-recording"),j.style.backgroundColor=ge,Ee){j.style.color=Ee;let I=j.querySelector("svg");I&&I.setAttribute("stroke",Ee)}ee&&(j.style.borderColor=ee),j.setAttribute("aria-label","Stop voice recognition")}}catch{Ut("system")}},Ut=(l="user")=>{if(_t){if(_t=!1,sn&&(clearTimeout(sn),sn=null),Rt){try{Rt.stop()}catch{}Rt=null}if(Ke.active=!1,Xn(l),tn(),j){if(j.classList.remove("tvw-voice-recording"),Vt){j.style.backgroundColor=Vt.backgroundColor,j.style.color=Vt.color,j.style.borderColor=Vt.borderColor;let p=j.querySelector("svg");p&&p.setAttribute("stroke",Vt.color||"currentColor"),Vt=null}j.setAttribute("aria-label","Start voice recognition")}}},$s=(l,p)=>{var ye,Ve,He,ht,Ht,X,je;if(!(typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined")))return null;let T=g("div","tvw-send-button-wrapper"),A=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer");A.type="button",A.setAttribute("aria-label","Start voice recognition");let F=(ye=l==null?void 0:l.iconName)!=null?ye:"mic",ve=(Ve=p==null?void 0:p.size)!=null?Ve:"40px",ae=(He=l==null?void 0:l.iconSize)!=null?He:ve,ce=parseFloat(ae)||24,xe=(ht=l==null?void 0:l.backgroundColor)!=null?ht:p==null?void 0:p.backgroundColor,ge=(Ht=l==null?void 0:l.iconColor)!=null?Ht:p==null?void 0:p.textColor;A.style.width=ae,A.style.height=ae,A.style.minWidth=ae,A.style.minHeight=ae,A.style.fontSize="18px",A.style.lineHeight="1";let Ee=ge||"currentColor",ee=oe(F,ce,Ee,1.5);ee?(A.appendChild(ee),A.style.color=Ee):(A.textContent="\u{1F3A4}",A.style.color=Ee),xe?A.style.backgroundColor=xe:A.classList.add("tvw-bg-cw-primary"),ge?A.style.color=ge:!ge&&!(p!=null&&p.textColor)&&A.classList.add("tvw-text-white"),l!=null&&l.borderWidth&&(A.style.borderWidth=l.borderWidth,A.style.borderStyle="solid"),l!=null&&l.borderColor&&(A.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(A.style.paddingLeft=l.paddingX,A.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(A.style.paddingTop=l.paddingY,A.style.paddingBottom=l.paddingY),T.appendChild(A);let I=(X=l==null?void 0:l.tooltipText)!=null?X:"Start voice recognition";if(((je=l==null?void 0:l.showTooltip)!=null?je:!1)&&I){let Xt=g("div","tvw-send-button-tooltip");Xt.textContent=I,T.appendChild(Xt)}return{micButton:A,micButtonWrapper:T}},Bn=()=>{if(_t){let l=pe.value.trim();Ke.manuallyDeactivated=!0,tn(),Ut("user"),l&&(pe.value="",pe.style.height="auto",$.sendMessage(l))}else Ke.manuallyDeactivated=!1,tn(),vn("user")};j&&(j.addEventListener("click",Bn),it.push(()=>{Ut("system"),j&&j.removeEventListener("click",Bn)}));let Fs=s.on("assistant:complete",()=>{Vn&&(Ke.active||Ke.manuallyDeactivated||Vn==="assistant"&&!Ke.lastUserMessageWasVoice||setTimeout(()=>{!Ke.active&&!Ke.manuallyDeactivated&&vn("auto")},600))});it.push(Fs);let Os=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});it.push(Os);let rn=()=>{nt(!b,"user")},Ge=null,Qe=null;if(x){let l=o.find(p=>p.renderLauncher);if(l!=null&&l.renderLauncher){let p=l.renderLauncher({config:e,defaultRenderer:()=>Cs(e,rn).element,onToggle:rn});p&&(Qe=p)}Qe||(Ge=Cs(e,rn))}Ge?t.appendChild(Ge.element):Qe&&t.appendChild(Qe),wn(),dn.render(e.suggestionChips,$,pe,void 0,e.suggestionChipsConfig),Qn(),Hn($.isStreaming()),fn(!0),Ws();let un=()=>{var h,T,A,F,ve,ae,ce,xe;let l=(T=(h=e.launcher)==null?void 0:h.sidebarMode)!=null?T:!1,p=l||((F=(A=e.launcher)==null?void 0:A.fullHeight)!=null?F:!1);if(!x){Se.style.height="",Se.style.width="";return}if(!l){let ge=(ae=(ve=e==null?void 0:e.launcher)==null?void 0:ve.width)!=null?ae:e==null?void 0:e.launcherWidth,Ee=ge!=null?ge:"min(400px, calc(100vw - 24px))";Se.style.width=Ee,Se.style.maxWidth=Ee}if(!p){let ge=window.innerHeight,Ee=64,ee=(xe=(ce=e.launcher)==null?void 0:ce.heightOffset)!=null?xe:0,I=Math.max(200,ge-Ee),me=Math.min(640,I),ye=Math.max(200,me-ee);Se.style.height=`${ye}px`}};un(),window.addEventListener("resize",un),it.push(()=>window.removeEventListener("resize",un)),mn=Fe.scrollTop;let ss=()=>{let l=Fe.scrollTop,p=Fe.scrollHeight,h=Fe.clientHeight,T=p-l-h,A=Math.abs(l-mn);if(mn=l,!Wn&&!(A<=ks)){if(!Qt&&T<Yn){en=!1,Qt=!0;return}Qt&&T>Yn&&(en=!0,kn=Date.now()+Is,Qt=!1)}};Fe.addEventListener("scroll",ss,{passive:!0}),it.push(()=>Fe.removeEventListener("scroll",ss)),it.push(()=>{Zt&&cancelAnimationFrame(Zt)});let rs=()=>{Q&&(Yt&&(Q.removeEventListener("click",Yt),Yt=null),x?(Q.style.display="",Yt=()=>{b=!1,wn()},Q.addEventListener("click",Yt)):Q.style.display="none")};rs(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{$.clearMessages();try{localStorage.removeItem(zn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zn}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==zn)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 p=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(p),i!=null&&i.clear)try{let h=i.clear();h instanceof Promise&&h.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",T)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}a={},S.syncFromMetadata(),P==null||P.clear(),z==null||z.update()})})(),gt.addEventListener("submit",Zn),pe.addEventListener("keydown",es),pe.addEventListener("paste",ts),it.push(()=>{gt.removeEventListener("submit",Zn),pe.removeEventListener("keydown",es),pe.removeEventListener("paste",ts)}),it.push(()=>{$.cancel()}),Ge?it.push(()=>{Ge==null||Ge.destroy()}):Qe&&it.push(()=>{Qe==null||Qe.remove()});let Pt={update(l){var Ur,zr,Jr,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,$o,Fo,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;let p=e.toolCall,h=e.colorScheme;e={...e,...l},In(),er(t,e),e.colorScheme!==h&&Jn();let T=Es.getForInstance(e.plugins);o.length=0,o.push(...T),x=(zr=(Ur=e.launcher)==null?void 0:Ur.enabled)!=null?zr:!0,E=(Kr=(Jr=e.launcher)==null?void 0:Jr.autoExpand)!=null?Kr:!1,Y=(Vr=(Yr=e.features)==null?void 0:Yr.showReasoning)!=null?Vr:!0,_=(Gr=(Xr=e.features)==null?void 0:Xr.showToolCalls)!=null?Gr:!0;let A=q;if(q=(Zr=(Qr=e.features)==null?void 0:Qr.showEventStreamToggle)!=null?Zr:!1,q&&!A){if(P||(B=new As(ue),P=new Ss(Z,B),B.open().then(()=>P==null?void 0:P.restore()).catch(()=>{}),$.setSSEEventCallback((k,Te)=>{P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:k,timestamp:Date.now(),payload:JSON.stringify(Te)})})),!J&&te){let k=(to=(eo=e.features)==null?void 0:eo.eventStream)==null?void 0:to.classNames,Te="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"+(k!=null&&k.toggleButton?" "+k.toggleButton:"");J=g("button",Te),J.style.width="28px",J.style.height="28px",J.type="button",J.setAttribute("aria-label","Event Stream"),J.title="Event Stream";let Ze=oe("activity","18px","currentColor",1.5);Ze&&J.appendChild(Ze);let be=se.clearChatButtonWrapper,Re=se.closeButtonWrapper,wt=be||Re;wt&&wt.parentNode===te?te.insertBefore(J,wt):te.appendChild(J),J.addEventListener("click",()=>{Ce?Ne():Me()})}}else!q&&A&&(Ne(),J&&(J.remove(),J=null),P==null||P.clear(),B==null||B.destroy(),P=null,B=null);if(((no=e.launcher)==null?void 0:no.enabled)===!1&&Ge&&(Ge.destroy(),Ge=null),((so=e.launcher)==null?void 0:so.enabled)===!1&&Qe&&(Qe.remove(),Qe=null),((ro=e.launcher)==null?void 0:ro.enabled)!==!1&&!Ge&&!Qe){let k=o.find(Te=>Te.renderLauncher);if(k!=null&&k.renderLauncher){let Te=k.renderLauncher({config:e,defaultRenderer:()=>Cs(e,rn).element,onToggle:rn});Te&&(Qe=Te,t.appendChild(Qe))}Qe||(Ge=Cs(e,rn),t.appendChild(Ge.element))}Ge&&Ge.update(e),bt&&((oo=e.launcher)==null?void 0:oo.title)!==void 0&&(bt.textContent=e.launcher.title),xt&&((io=e.launcher)==null?void 0:io.subtitle)!==void 0&&(xt.textContent=e.launcher.subtitle);let F=(ao=e.layout)==null?void 0:ao.header;if((F==null?void 0:F.layout)!==V&&te){let k=F?Fn(e,F,{showClose:x,onClose:()=>nt(!1,"user")}):an({config:e,showClose:x,onClose:()=>nt(!1,"user")});te.replaceWith(k.header),te=k.header,We=k.iconHolder,bt=k.headerTitle,xt=k.headerSubtitle,Q=k.closeButton,V=F==null?void 0:F.layout}else if(F&&(We&&(We.style.display=F.showIcon===!1?"none":""),bt&&(bt.style.display=F.showTitle===!1?"none":""),xt&&(xt.style.display=F.showSubtitle===!1?"none":""),Q&&(Q.style.display=F.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let k=F.showClearChat;if(k!==void 0){se.clearChatButtonWrapper.style.display=k?"":"none";let{closeButtonWrapper:Te}=se;Te&&!Te.classList.contains("tvw-absolute")&&(k?Te.classList.remove("tvw-ml-auto"):Te.classList.add("tvw-ml-auto"))}}let ae=((lo=e.layout)==null?void 0:lo.showHeader)!==!1;te&&(te.style.display=ae?"":"none");let ce=((co=e.layout)==null?void 0:co.showFooter)!==!1;Oe&&(Oe.style.display=ce?"":"none"),x!==W?x?nt(E,"auto"):(b=!0,wn()):E!==C&&nt(E,"auto"),C=E,W=x,un(),rs(),JSON.stringify(l.toolCall)!==JSON.stringify(p)&&$&&hn(Xe,$.getMessages(),ne);let ee=(uo=e.launcher)!=null?uo:{},I=(po=ee.headerIconHidden)!=null?po:!1,me=(mo=(go=e.layout)==null?void 0:go.header)==null?void 0:mo.showIcon,ye=I||me===!1,Ve=ee.headerIconName,He=(fo=ee.headerIconSize)!=null?fo:"48px";if(We){let k=he.querySelector(".tvw-border-b-cw-divider"),Te=k==null?void 0:k.querySelector(".tvw-flex-col");if(ye)We.style.display="none",k&&Te&&!k.contains(Te)&&k.insertBefore(Te,k.firstChild);else{if(We.style.display="",We.style.height=He,We.style.width=He,k&&Te&&(k.contains(We)?We.nextSibling!==Te&&(We.remove(),k.insertBefore(We,Te)):k.insertBefore(We,Te)),Ve){let be=parseFloat(He)||24,Re=oe(Ve,be*.6,"#ffffff",2);Re?We.replaceChildren(Re):We.textContent=(ho=ee.agentIconText)!=null?ho:"\u{1F4AC}"}else if(ee.iconUrl){let be=We.querySelector("img");if(be)be.src=ee.iconUrl,be.style.height=He,be.style.width=He;else{let Re=document.createElement("img");Re.src=ee.iconUrl,Re.alt="",Re.className="tvw-rounded-xl tvw-object-cover",Re.style.height=He,Re.style.width=He,We.replaceChildren(Re)}}else{let be=We.querySelector("svg"),Re=We.querySelector("img");(be||Re)&&We.replaceChildren(),We.textContent=(wo=ee.agentIconText)!=null?wo:"\u{1F4AC}"}let Ze=We.querySelector("img");Ze&&(Ze.style.height=He,Ze.style.width=He)}}let ht=(yo=(vo=e.layout)==null?void 0:vo.header)==null?void 0:yo.showTitle,Ht=(xo=(bo=e.layout)==null?void 0:bo.header)==null?void 0:xo.showSubtitle;if(bt&&(bt.style.display=ht===!1?"none":""),xt&&(xt.style.display=Ht===!1?"none":""),Q){((So=(Co=e.layout)==null?void 0:Co.header)==null?void 0:So.showCloseButton)===!1?Q.style.display="none":Q.style.display="";let Te=(Ao=ee.closeButtonSize)!=null?Ao:"32px",Ze=(Eo=ee.closeButtonPlacement)!=null?Eo:"inline";Q.style.height=Te,Q.style.width=Te;let{closeButtonWrapper:be}=se,Re=Ze==="top-right",wt=be==null?void 0:be.classList.contains("tvw-absolute");if(be&&Re!==wt)if(be.remove(),Re)be.className="tvw-absolute tvw-top-4 tvw-right-4 tvw-z-50",he.style.position="relative",he.appendChild(be);else{let Le=(Mo=(To=ee.clearChat)==null?void 0:To.placement)!=null?Mo:"inline",At=(Io=(Lo=ee.clearChat)==null?void 0:Lo.enabled)!=null?Io:!0;be.className=At&&Le==="inline"?"":"tvw-ml-auto";let Ot=he.querySelector(".tvw-border-b-cw-divider");Ot&&Ot.appendChild(be)}if(ee.closeButtonColor?(Q.style.color=ee.closeButtonColor,Q.classList.remove("tvw-text-cw-muted")):(Q.style.color="",Q.classList.add("tvw-text-cw-muted")),ee.closeButtonBackgroundColor?(Q.style.backgroundColor=ee.closeButtonBackgroundColor,Q.classList.remove("hover:tvw-bg-gray-100")):(Q.style.backgroundColor="",Q.classList.add("hover:tvw-bg-gray-100")),ee.closeButtonBorderWidth||ee.closeButtonBorderColor){let Le=ee.closeButtonBorderWidth||"0px",At=ee.closeButtonBorderColor||"transparent";Q.style.border=`${Le} solid ${At}`,Q.classList.remove("tvw-border-none")}else Q.style.border="",Q.classList.add("tvw-border-none");ee.closeButtonBorderRadius?(Q.style.borderRadius=ee.closeButtonBorderRadius,Q.classList.remove("tvw-rounded-full")):(Q.style.borderRadius="",Q.classList.add("tvw-rounded-full")),ee.closeButtonPaddingX?(Q.style.paddingLeft=ee.closeButtonPaddingX,Q.style.paddingRight=ee.closeButtonPaddingX):(Q.style.paddingLeft="",Q.style.paddingRight=""),ee.closeButtonPaddingY?(Q.style.paddingTop=ee.closeButtonPaddingY,Q.style.paddingBottom=ee.closeButtonPaddingY):(Q.style.paddingTop="",Q.style.paddingBottom="");let kt=(ko=ee.closeButtonIconName)!=null?ko:"x",jt=(Wo=ee.closeButtonIconText)!=null?Wo:"\xD7";Q.innerHTML="";let Ft=oe(kt,"20px",ee.closeButtonColor||"",2);Ft?Q.appendChild(Ft):Q.textContent=jt;let lt=(Po=ee.closeButtonTooltipText)!=null?Po:"Close chat",qt=(Ho=ee.closeButtonShowTooltip)!=null?Ho:!0;if(Q.setAttribute("aria-label",lt),be&&(be._cleanupTooltip&&(be._cleanupTooltip(),delete be._cleanupTooltip),qt&<)){let Le=null,At=()=>{if(Le||!Q)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=lt;let vs=g("div");vs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(vs);let xn=Q.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${xn.left+xn.width/2}px`,Le.style.top=`${xn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ot=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};be.addEventListener("mouseenter",At),be.addEventListener("mouseleave",Ot),Q.addEventListener("focus",At),Q.addEventListener("blur",Ot),be._cleanupTooltip=()=>{Ot(),be&&(be.removeEventListener("mouseenter",At),be.removeEventListener("mouseleave",Ot)),Q&&(Q.removeEventListener("focus",At),Q.removeEventListener("blur",Ot))}}}let{clearChatButton:X,clearChatButtonWrapper:je}=se;if(X){let k=(Bo=ee.clearChat)!=null?Bo:{},Te=(Ro=k.enabled)!=null?Ro:!0,Ze=(Fo=($o=e.layout)==null?void 0:$o.header)==null?void 0:Fo.showClearChat,be=Ze!==void 0?Ze:Te,Re=(Oo=k.placement)!=null?Oo:"inline";if(je){je.style.display=be?"":"none";let{closeButtonWrapper:wt}=se;wt&&!wt.classList.contains("tvw-absolute")&&(be?wt.classList.remove("tvw-ml-auto"):wt.classList.add("tvw-ml-auto"));let kt=Re==="top-right",jt=je.classList.contains("tvw-absolute");if(kt!==jt&&be){if(je.remove(),kt)je.className="tvw-absolute tvw-top-4 tvw-z-50",je.style.right="48px",he.style.position="relative",he.appendChild(je);else{je.className="tvw-relative tvw-ml-auto tvw-clear-chat-button-wrapper",je.style.right="";let lt=he.querySelector(".tvw-border-b-cw-divider"),qt=se.closeButtonWrapper;lt&&qt&&qt.parentElement===lt?lt.insertBefore(je,qt):lt&<.appendChild(je)}let Ft=se.closeButtonWrapper;Ft&&!Ft.classList.contains("tvw-absolute")&&(kt?Ft.classList.add("tvw-ml-auto"):Ft.classList.remove("tvw-ml-auto"))}}if(be){let wt=(No=k.size)!=null?No:"32px";X.style.height=wt,X.style.width=wt;let kt=(Do=k.iconName)!=null?Do:"refresh-cw",jt=(_o=k.iconColor)!=null?_o:"";X.innerHTML="";let Ft=oe(kt,"20px",jt||"",2);if(Ft&&X.appendChild(Ft),jt?(X.style.color=jt,X.classList.remove("tvw-text-cw-muted")):(X.style.color="",X.classList.add("tvw-text-cw-muted")),k.backgroundColor?(X.style.backgroundColor=k.backgroundColor,X.classList.remove("hover:tvw-bg-gray-100")):(X.style.backgroundColor="",X.classList.add("hover:tvw-bg-gray-100")),k.borderWidth||k.borderColor){let Le=k.borderWidth||"0px",At=k.borderColor||"transparent";X.style.border=`${Le} solid ${At}`,X.classList.remove("tvw-border-none")}else X.style.border="",X.classList.add("tvw-border-none");k.borderRadius?(X.style.borderRadius=k.borderRadius,X.classList.remove("tvw-rounded-full")):(X.style.borderRadius="",X.classList.add("tvw-rounded-full")),k.paddingX?(X.style.paddingLeft=k.paddingX,X.style.paddingRight=k.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),k.paddingY?(X.style.paddingTop=k.paddingY,X.style.paddingBottom=k.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let lt=(jo=k.tooltipText)!=null?jo:"Clear chat",qt=(qo=k.showTooltip)!=null?qo:!0;if(X.setAttribute("aria-label",lt),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),qt&<)){let Le=null,At=()=>{if(Le||!X)return;Le=g("div","tvw-clear-chat-tooltip"),Le.textContent=lt;let vs=g("div");vs.className="tvw-clear-chat-tooltip-arrow",Le.appendChild(vs);let xn=X.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${xn.left+xn.width/2}px`,Le.style.top=`${xn.top-8}px`,Le.style.transform="translate(-50%, -100%)",document.body.appendChild(Le)},Ot=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};je.addEventListener("mouseenter",At),je.addEventListener("mouseleave",Ot),X.addEventListener("focus",At),X.addEventListener("blur",Ot),je._cleanupTooltip=()=>{Ot(),je&&(je.removeEventListener("mouseenter",At),je.removeEventListener("mouseleave",Ot)),X&&(X.removeEventListener("focus",At),X.removeEventListener("blur",Ot))}}}}let Xt=e.actionParsers&&e.actionParsers.length?e.actionParsers:[Ts],zt=e.actionHandlers&&e.actionHandlers.length?e.actionHandlers:[Mn.message,Mn.messageAndClick];S=Ms({parsers:Xt,handlers:zt,getSessionMetadata:v,updateSessionMetadata:d,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ne=la(e,S,R),$.updateConfig(e),hn(Xe,$.getMessages(),ne),dn.render(e.suggestionChips,$,pe,void 0,e.suggestionChipsConfig),Qn(),Hn($.isStreaming());let pn=((Uo=e.voiceRecognition)==null?void 0:Uo.enabled)===!0,Ns=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined");if(pn&&Ns)if(!j||!et){let k=$s(e.voiceRecognition,e.sendButton);k&&(j=k.micButton,et=k.micButtonWrapper,Lt.insertBefore(et,pt),j.addEventListener("click",Bn),j.disabled=$.isStreaming())}else{let k=(zo=e.voiceRecognition)!=null?zo:{},Te=(Jo=e.sendButton)!=null?Jo:{},Ze=(Ko=k.iconName)!=null?Ko:"mic",be=(Yo=Te.size)!=null?Yo:"40px",Re=(Vo=k.iconSize)!=null?Vo:be,wt=parseFloat(Re)||24;j.style.width=Re,j.style.height=Re,j.style.minWidth=Re,j.style.minHeight=Re;let kt=(Go=(Xo=k.iconColor)!=null?Xo:Te.textColor)!=null?Go:"currentColor";j.innerHTML="";let jt=oe(Ze,wt,kt,2);jt?j.appendChild(jt):j.textContent="\u{1F3A4}";let Ft=(Qo=k.backgroundColor)!=null?Qo:Te.backgroundColor;Ft?(j.style.backgroundColor=Ft,j.classList.remove("tvw-bg-cw-primary")):(j.style.backgroundColor="",j.classList.add("tvw-bg-cw-primary")),kt?(j.style.color=kt,j.classList.remove("tvw-text-white")):!kt&&!Te.textColor&&(j.style.color="",j.classList.add("tvw-text-white")),k.borderWidth?(j.style.borderWidth=k.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),k.borderColor?j.style.borderColor=k.borderColor:j.style.borderColor="",k.paddingX?(j.style.paddingLeft=k.paddingX,j.style.paddingRight=k.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),k.paddingY?(j.style.paddingTop=k.paddingY,j.style.paddingBottom=k.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let lt=et==null?void 0:et.querySelector(".tvw-send-button-tooltip"),qt=(Zo=k.tooltipText)!=null?Zo:"Start voice recognition";if(((ei=k.showTooltip)!=null?ei:!1)&&qt)if(lt)lt.textContent=qt,lt.style.display="";else{let At=document.createElement("div");At.className="tvw-send-button-tooltip",At.textContent=qt,et==null||et.insertBefore(At,j)}else lt&&(lt.style.display="none");et.style.display="",j.disabled=$.isStreaming()}else j&&et&&(et.style.display="none",_t&&Ut());if(((ti=e.attachments)==null?void 0:ti.enabled)===!0)if(!K||!Ie){let k=(ni=e.attachments)!=null?ni:{},Ze=(ri=((si=e.sendButton)!=null?si:{}).size)!=null?ri:"40px";we||(we=g("div","tvw-attachment-previews tvw-flex tvw-flex-wrap tvw-gap-2 tvw-mb-2"),we.style.display="none",gt.insertBefore(we,pe)),O||(O=document.createElement("input"),O.type="file",O.accept=((oi=k.allowedTypes)!=null?oi:gn).join(","),O.multiple=((ii=k.maxFiles)!=null?ii:4)>1,O.style.display="none",O.setAttribute("aria-label","Attach files"),gt.insertBefore(O,pe)),K=g("div","tvw-send-button-wrapper"),Ie=g("button","tvw-rounded-button tvw-flex tvw-items-center tvw-justify-center disabled:tvw-opacity-50 tvw-cursor-pointer tvw-attachment-button"),Ie.type="button",Ie.setAttribute("aria-label",(ai=k.buttonTooltipText)!=null?ai:"Attach file");let be=(li=k.buttonIconName)!=null?li:"paperclip",Re=Ze,wt=parseFloat(Re)||40,kt=Math.round(wt*.6);Ie.style.width=Re,Ie.style.height=Re,Ie.style.minWidth=Re,Ie.style.minHeight=Re,Ie.style.fontSize="18px",Ie.style.lineHeight="1",Ie.style.backgroundColor="transparent",Ie.style.color="var(--cw-primary, #111827)",Ie.style.border="none",Ie.style.borderRadius="6px",Ie.style.transition="background-color 0.15s ease",Ie.addEventListener("mouseenter",()=>{Ie.style.backgroundColor="rgba(0, 0, 0, 0.05)"}),Ie.addEventListener("mouseleave",()=>{Ie.style.backgroundColor="transparent"});let jt=oe(be,kt,"currentColor",1.5);jt?Ie.appendChild(jt):Ie.textContent="\u{1F4CE}",Ie.addEventListener("click",qt=>{qt.preventDefault(),O==null||O.click()}),K.appendChild(Ie);let Ft=(di=k.buttonTooltipText)!=null?di:"Attach file",lt=g("div","tvw-send-button-tooltip");lt.textContent=Ft,K.appendChild(lt),Wt.append(K),!de&&O&&we&&(de=An.fromConfig(k),de.setPreviewsContainer(we),O.addEventListener("change",async()=>{de&&(O!=null&&O.files)&&(await de.handleFileSelect(O.files),O.value="")}))}else{K.style.display="";let k=(ci=e.attachments)!=null?ci:{};O&&(O.accept=((ui=k.allowedTypes)!=null?ui:gn).join(","),O.multiple=((pi=k.maxFiles)!=null?pi:4)>1),de&&de.updateConfig({allowedTypes:k.allowedTypes,maxFileSize:k.maxFileSize,maxFiles:k.maxFiles})}else K&&(K.style.display="none"),de&&de.clearAttachments();let ut=(gi=e.sendButton)!=null?gi:{},Ds=(mi=ut.useIcon)!=null?mi:!1,ms=(fi=ut.iconText)!=null?fi:"\u2191",yn=ut.iconName,bn=(hi=ut.tooltipText)!=null?hi:"Send message",wa=(wi=ut.showTooltip)!=null?wi:!1,fs=(vi=ut.size)!=null?vi:"40px",_s=ut.backgroundColor,Gt=ut.textColor;if(Ds){if(G.style.width=fs,G.style.height=fs,G.style.minWidth=fs,G.style.minHeight=fs,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",yn){let k=parseFloat(fs)||24,Te=Gt&&typeof Gt=="string"&&Gt.trim()?Gt.trim():"currentColor",Ze=oe(yn,k,Te,2);Ze?(G.appendChild(Ze),G.style.color=Te):(G.textContent=ms,Gt?G.style.color=Gt:G.classList.add("tvw-text-white"))}else G.textContent=ms,Gt?G.style.color=Gt: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",_s?(G.style.backgroundColor=_s,G.classList.remove("tvw-bg-cw-primary")):G.classList.add("tvw-bg-cw-primary")}else G.textContent=(bi=(yi=e.copy)==null?void 0:yi.sendButtonLabel)!=null?bi:"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",_s?(G.style.backgroundColor=_s,G.classList.remove("tvw-bg-cw-accent")):G.classList.add("tvw-bg-cw-accent"),Gt?G.style.color=Gt:G.classList.add("tvw-text-white");ut.borderWidth?(G.style.borderWidth=ut.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),ut.borderColor?G.style.borderColor=ut.borderColor:G.style.borderColor="",ut.paddingX?(G.style.paddingLeft=ut.paddingX,G.style.paddingRight=ut.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),ut.paddingY?(G.style.paddingTop=ut.paddingY,G.style.paddingBottom=ut.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let hs=pt==null?void 0:pt.querySelector(".tvw-send-button-tooltip");if(wa&&bn)if(hs)hs.textContent=bn,hs.style.display="";else{let k=document.createElement("div");k.className="tvw-send-button-tooltip",k.textContent=bn,pt==null||pt.insertBefore(k,G)}else hs&&(hs.style.display="none");let ws=(xi=e.statusIndicator)!=null?xi:{},va=(Ci=ws.visible)!=null?Ci:!0;if(vt.style.display=va?"":"none",$){let k=$.getStatus(),Te=Ze=>{var be,Re,wt,kt;return Ze==="idle"?(be=ws.idleText)!=null?be:Bt.idle:Ze==="connecting"?(Re=ws.connectingText)!=null?Re:Bt.connecting:Ze==="connected"?(wt=ws.connectedText)!=null?wt:Bt.connected:Ze==="error"?(kt=ws.errorText)!=null?kt:Bt.error:Bt[Ze]};vt.textContent=Te(k)}},open(){x&&nt(!0,"api")},close(){x&&nt(!1,"api")},toggle(){x&&nt(!b,"api")},clearChat(){$.clearMessages();try{localStorage.removeItem(zn),e.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${zn}`)}catch(p){console.error("[AgentWidget] Failed to clear default localStorage:",p)}if(e.clearChatHistoryStorageKey&&e.clearChatHistoryStorageKey!==zn)try{localStorage.removeItem(e.clearChatHistoryStorageKey),e.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${e.clearChatHistoryStorageKey}`)}catch(p){console.error("[AgentWidget] Failed to clear custom localStorage:",p)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),i!=null&&i.clear)try{let p=i.clear();p instanceof Promise&&p.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",p)}a={},S.syncFromMetadata(),P==null||P.clear(),z==null||z.update()},setMessage(l){return!pe||$.isStreaming()?!1:(!b&&x&&nt(!0,"system"),pe.value=l,pe.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if($.isStreaming())return!1;let p=(l==null?void 0:l.trim())||pe.value.trim();return p?(!b&&x&&nt(!0,"system"),pe.value="",pe.style.height="auto",$.sendMessage(p),!0):!1},startVoiceRecognition(){return _t||$.isStreaming()||!ns()?!1:(!b&&x&&nt(!0,"system"),Ke.manuallyDeactivated=!1,tn(),vn("user"),!0)},stopVoiceRecognition(){return _t?(Ke.manuallyDeactivated=!0,tn(),Ut("user"),!0):!1},injectMessage(l){return!b&&x&&nt(!0,"system"),$.injectMessage(l)},injectAssistantMessage(l){!b&&x&&nt(!0,"system");let p=$.injectAssistantMessage(l);return N&&(N=!1,M&&(clearTimeout(M),M=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),p},injectUserMessage(l){return!b&&x&&nt(!0,"system"),$.injectUserMessage(l)},injectSystemMessage(l){return!b&&x&&nt(!0,"system"),$.injectSystemMessage(l)},injectMessageBatch(l){return!b&&x&&nt(!0,"system"),$.injectMessageBatch(l)},injectTestMessage(l){!b&&x&&nt(!0,"system"),$.injectTestEvent(l)},async connectStream(l,p){return $.connectStream(l,p)},__pushEventStreamEvent(l){P&&P.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!q||!P||Me()},hideEventStream(){Ce&&Ne()},isEventStreamVisible(){return Ce},async resolveApproval(l,p){let T=$.getMessages().find(A=>{var F;return A.variant==="approval"&&((F=A.approval)==null?void 0:F.id)===l});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${l}`);return $.resolveApproval(T.approval,p)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...a}},updatePersistentMetadata(l){d(l)},on(l,p){return s.on(l,p)},off(l,p){s.off(l,p)},isOpen(){return x&&b},isVoiceActive(){return Ke.active},getState(){return{open:x&&b,launcherEnabled:x,voiceActive:Ke.active,streaming:$.isStreaming()}},showCSATFeedback(l){!b&&x&&nt(!0,"system");let p=Xe.querySelector(".tvw-feedback-container");p&&p.remove();let h=lr({onSubmit:async(T,A)=>{var F;$.isClientTokenMode()&&await $.submitCSATFeedback(T,A),(F=l==null?void 0:l.onSubmit)==null||F.call(l,T,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!b&&x&&nt(!0,"system");let p=Xe.querySelector(".tvw-feedback-container");p&&p.remove();let h=dr({onSubmit:async(T,A)=>{var F;$.isClientTokenMode()&&await $.submitNPSFeedback(T,A),(F=l==null?void 0:l.onSubmit)==null||F.call(l,T,A)},onDismiss:l==null?void 0:l.onDismiss,...l});Xe.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,p){return $.submitCSATFeedback(l,p)},async submitNPSFeedback(l,p){return $.submitNPSFeedback(l,p)},destroy(){it.forEach(l=>l()),$e.remove(),Ge==null||Ge.destroy(),Qe==null||Qe.remove(),Yt&&Q.removeEventListener("click",Yt)}};if((((St=r==null?void 0:r.debugTools)!=null?St:!1)||!!e.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,p={controller:Pt,getMessages:Pt.getMessages,getStatus:Pt.getStatus,getMetadata:Pt.getPersistentMetadata,updateMetadata:Pt.updatePersistentMetadata,clearHistory:()=>Pt.clearChat(),setVoiceActive:h=>h?Pt.startVoiceRecognition():Pt.stopVoiceRecognition()};window.AgentWidgetBrowser=p,it.push(()=>{window.AgentWidgetBrowser===p&&(window.AgentWidgetBrowser=l)})}if(q&&typeof window!="undefined"){let l=t.getAttribute("data-persona-instance")||t.id||"persona-"+Math.random().toString(36).slice(2,8),p=T=>{let A=T.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Pt.showEventStream()},h=T=>{let A=T.detail;(!(A!=null&&A.instanceId)||A.instanceId===l)&&Pt.hideEventStream()};window.addEventListener("persona:showEventStream",p),window.addEventListener("persona:hideEventStream",h),it.push(()=>{window.removeEventListener("persona:showEventStream",p),window.removeEventListener("persona:hideEventStream",h)})}let $t=hl(e.persistState);if($t&&x){let l=wl($t.storage),p=`${$t.keyPrefix}widget-open`,h=`${$t.keyPrefix}widget-voice`,T=`${$t.keyPrefix}widget-voice-mode`;if(l){let A=((ft=$t.persist)==null?void 0:ft.openState)&&l.getItem(p)==="true",F=((De=$t.persist)==null?void 0:De.voiceState)&&l.getItem(h)==="true",ve=((qe=$t.persist)==null?void 0:qe.voiceState)&&l.getItem(T)==="true";if(A&&setTimeout(()=>{Pt.open(),setTimeout(()=>{var ae;if(F||ve)Pt.startVoiceRecognition();else if((ae=$t.persist)!=null&&ae.focusInput){let ce=t.querySelector("textarea");ce&&ce.focus()}},100)},0),(ct=$t.persist)!=null&&ct.openState&&(s.on("widget:opened",()=>{l.setItem(p,"true")}),s.on("widget:closed",()=>{l.setItem(p,"false")})),(Ue=$t.persist)!=null&&Ue.voiceState&&(s.on("voice:state",ae=>{l.setItem(h,ae.active?"true":"false")}),s.on("user:message",ae=>{l.setItem(T,ae.viaVoice?"true":"false")})),$t.clearOnChatClear){let ae=()=>{l.removeItem(p),l.removeItem(h),l.removeItem(T)},ce=()=>ae();window.addEventListener("persona:clear-chat",ce),it.push(()=>{window.removeEventListener("persona:clear-chat",ce)})}}}return Pt};var _r={},vl=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},yl=()=>{try{if(typeof _r!="undefined"&&_r.url)return new URL("../widget.css",_r.url).href}catch{}return null},da=t=>{let n=yl(),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)}},jr=t=>{var c,v,d,f;let n=vl(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 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),da(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),da(r);n.id&&s.setAttribute("data-persona-instance",n.id);let a=cr(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 ca={name:"@runtypelabs/persona",version:"1.45.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 Ln=ca.version;function ln(t){if(t!==void 0)return typeof t=="string"?t:Array.isArray(t)?`[${t.map(n=>n.toString()).join(", ")}]`:t.toString()}function xl(t){if(t)return{getHeaders:ln(t.getHeaders),onFeedback:ln(t.onFeedback),onCopy:ln(t.onCopy),requestMiddleware:ln(t.requestMiddleware),actionHandlers:ln(t.actionHandlers),actionParsers:ln(t.actionParsers),postprocessMessage:ln(t.postprocessMessage),contextProviders:ln(t.contextProviders),streamParser:ln(t.streamParser)}}var ua=`({ text, message }: any) => {
|
|
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.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 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) => {
|
|
61
61
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
62
62
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
63
63
|
let cleanJson = jsonSource
|
|
@@ -70,7 +70,7 @@
|
|
|
70
70
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
71
71
|
} catch (e) { return null; }
|
|
72
72
|
return null;
|
|
73
|
-
}`,
|
|
73
|
+
}`,fa=`function(ctx) {
|
|
74
74
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
75
75
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
76
76
|
var cleanJson = jsonSource
|
|
@@ -83,7 +83,7 @@
|
|
|
83
83
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
84
84
|
} catch (e) { return null; }
|
|
85
85
|
return null;
|
|
86
|
-
}`,
|
|
86
|
+
}`,ha=`(action: any, context: any) => {
|
|
87
87
|
if (action.type !== 'nav_then_click') return;
|
|
88
88
|
const payload = action.payload || action.raw || {};
|
|
89
89
|
const url = payload?.page;
|
|
@@ -100,7 +100,7 @@
|
|
|
100
100
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
101
101
|
window.location.href = targetUrl;
|
|
102
102
|
return { handled: true, displayText: text };
|
|
103
|
-
}`,
|
|
103
|
+
}`,wa=`function(action, context) {
|
|
104
104
|
if (action.type !== 'nav_then_click') return;
|
|
105
105
|
var payload = action.payload || action.raw || {};
|
|
106
106
|
var url = payload.page;
|
|
@@ -117,24 +117,24 @@
|
|
|
117
117
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
118
118
|
window.location.href = targetUrl;
|
|
119
119
|
return { handled: true, displayText: text };
|
|
120
|
-
}`,
|
|
120
|
+
}`,El=`(parsed: any) => {
|
|
121
121
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
122
122
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
123
123
|
if (parsed.action === 'message') return parsed.text || '';
|
|
124
124
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
125
125
|
return parsed.text || null;
|
|
126
|
-
}`,
|
|
126
|
+
}`,Tl=`function(parsed) {
|
|
127
127
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
128
128
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
129
129
|
if (parsed.action === 'message') return parsed.text || '';
|
|
130
130
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
131
131
|
return parsed.text || null;
|
|
132
|
-
}`;function
|
|
133
|
-
`)}function
|
|
134
|
-
`)}function Ml(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(...pr(t," ")),e.push(...gr(t," ",r)),e.push(...mr(t," ")),e.push(...fr(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(${Cl}),`)),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(` ${ua}`),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(` ${ua}`),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(` ${ga}`),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(` ${ga}`),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
|
|
136
|
-
`)}function
|
|
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,"'");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(`
|
|
137
137
|
`).map((i,a)=>a===0?i:" "+i).join(`
|
|
138
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
139
|
-
`)}var
|
|
138
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${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});
|
|
140
140
|
//# sourceMappingURL=index.cjs.map
|