@runtypelabs/persona 2.0.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +21 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +43 -0
- package/dist/index.d.ts +43 -0
- package/dist/index.global.js +69 -69
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +21 -21
- package/dist/index.js.map +1 -1
- package/dist/widget.css +13 -0
- package/package.json +1 -1
- package/src/styles/widget.css +13 -0
- package/src/types/theme.ts +22 -0
- package/src/types.ts +24 -0
- package/src/utils/migration.ts +42 -1
- package/src/utils/theme.test.ts +33 -1
- package/src/utils/theme.ts +8 -0
- package/src/utils/tokens.ts +19 -0
package/dist/index.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),_r=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},hc=e=>{var a,i;let
|
|
1
|
+
import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let n=e==null?void 0:e.markedOptions,t=new pc({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}),r=uc(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},ir=e=>e?xs({markedOptions:e.options,renderer:e.renderer}):xs(),gc=xs(),_i=e=>gc(e),Dr=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ji=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),Di=e=>`%%FORM_PLACEHOLDER_${e}%%`,Vi=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,o)=>{try{let s=JSON.parse(o.trim());if(s&&typeof s=="object"&&s.component==="form"&&s.type){let a=Di(n.length);return n.push({token:a,type:String(s.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,o)=>{let s=Di(n.length);return n.push({token:s,type:o}),s}),t},mc=e=>{let n=ir(e);return t=>{let r=[],o=Vi(t,r),s=n(o);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g=`<div class="persona-form-directive" data-tv-form="${ji(i)}"></div>`;s=s.replace(d,g)}),s}},fc=e=>{let n=[],t=Vi(e,n),r=_i(t);return n.forEach(({token:o,type:s})=>{let a=new RegExp(o.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${ji(s)}"></div>`;r=r.replace(a,d)}),r};import{parse as qi,STR as Ui,OBJ as zi}from"partial-json";var vs=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),_r=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},hc=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},Ji=e=>e.status==="complete"?hc(e):e.status==="pending"?"Waiting":"",yc=e=>{var o,s,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Ki=e=>e.status==="complete"?yc(e):"Using tool...",bc=()=>{let e=null,n=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.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 a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Cs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Us=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},zs=()=>{var t;let e=bc();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Js=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=qi(n,Ui|zi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?vs(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=vs(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},xc=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?vs(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?vs(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=qi(s,Ui|zi),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Ks=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var vc="https://api.runtype.com/v1/dispatch",Ys="https://api.runtype.com",Xs=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Cc(e){switch(e){case"json":return Js;case"regex-json":return zs;case"xml":return Ks;default:return Us}}var lr=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;var n,r,o;this.apiUrl=(n=t.apiUrl)!=null?n:vc,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Cc(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders}setSSEEventCallback(t){this.onSSEEvent=t}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;let n=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys;return t==="init"?`${n}/v1/client/init`:`${n}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var t,n;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 r=await this.sessionInitPromise;return this.clientSession=r,(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.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 n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/v1/client/feedback`}async sendFeedback(t){var s,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let m=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:m}),m}let c=await this.buildPayload(t.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:t.messages.filter(Xs).map(m=>{var C,v,E;return{id:m.id,role:m.role,content:(E=(v=(C=m.contentParts)!=null?C:m.llmContent)!=null?v:m.rawContent)!=null?E:m.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!y.ok){let m=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:v}),v}if(y.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw n({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw n({type:"error",error:C}),C}if(!y.body){let m=new Error("No response body received");throw n({type:"error",error:m}),m}n({type:"status",status:"connected"});try{await this.streamResponse(y.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async buildAgentPayload(t){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Xs).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(t){let r={messages:t.slice().filter(Xs).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i: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 a=await s({messages:t,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(t,n,r,o,s){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(t);if(a===null)return!1;let i=()=>{if(r.current)return r.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return r.current=d,o(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,o(d)}return a.done&&(r.current&&(r.current.streaming=!1,o(r.current)),n({type:"status",status:"idle"})),a.error&&n({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(t,n,r){var mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,$t,Ft,It,H,te,J,We,Ce,Pe,Be,ut,ye,be,$e,de,bt,Gt,pn,un,ts,Ln,Xn,Ge,gn,Pn,an,vr,mn,dt,tn,vn,Cr,Gn,wr,Nn,fn,On,xt,hn,Sr,In,yn,W,Wn,Rn,Ar,Cn,Dn,Er,wn,Sn,Zn,Qn,ns,rs,ss,Tr,er,qe,Mr,nn,zt,os,as,kr,_n,An,is,ls,cs,js,jn,tr,ft,nr,rr,Lr,Pr,Ir,Wr,Vt,Zt,En,Re,Rr,Vn,ln,ds,sr,or,qn,Hn,ps,us,cn,Un,gs;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=G=>{let Fe=G.reasoning?{...G.reasoning,chunks:[...G.reasoning.chunks]}:void 0,we=G.toolCall?{...G.toolCall,chunks:G.toolCall.chunks?[...G.toolCall.chunks]:void 0}:void 0,Ne=G.tools?G.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...G,reasoning:Fe,toolCall:we,tools:Ne}},p=G=>{n({type:"message",message:g(G)})},y=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=G=>{if(G==null)return null;try{return String(G)}catch{return null}},U=G=>{var Fe,we,Ne,vt,Nt;return k((Nt=(vt=(Ne=(we=(Fe=G.stepId)!=null?Fe:G.step_id)!=null?we:G.step)!=null?Ne:G.parentId)!=null?vt:G.flowStepId)!=null?Nt:G.flow_step_id)},M=G=>{var Fe,we,Ne,vt,Nt,Ct,b;return k((b=(Ct=(Nt=(vt=(Ne=(we=(Fe=G.callId)!=null?Fe:G.call_id)!=null?we:G.requestId)!=null?Ne:G.request_id)!=null?vt:G.toolCallId)!=null?Nt:G.tool_call_id)!=null?Ct:G.stepId)!=null?b:G.step_id)},O=()=>y||(y={id:r!=null?r:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(y),y),S=(G,Fe)=>{E.lastId=Fe,G&&E.byStep.set(G,Fe)},N=(G,Fe)=>{var Nt;let we=(Nt=G.reasoningId)!=null?Nt:G.id,Ne=U(G);if(we){let Ct=String(we);return S(Ne,Ct),Ct}if(Ne){let Ct=E.byStep.get(Ne);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!Fe)return E.lastId;if(!Fe)return null;let vt=`reason-${c()}`;return S(Ne,vt),vt},Z=G=>{let Fe=C.get(G);if(Fe)return Fe;let we={id:`reason-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:G,status:"streaming",chunks:[]}};return C.set(G,we),p(we),we},K=(G,Fe)=>{x.lastId=Fe,G&&x.byCall.set(G,Fe)},re=new Set,z=new Map,pe=new Set,Le=new Map,Ye=G=>{if(!G)return!1;let Fe=G.replace(/_+/g,"_").replace(/^_|_$/g,"");return Fe==="emit_artifact_markdown"||Fe==="emit_artifact_component"},fe=(G,Fe)=>{var Nt;let we=(Nt=G.toolId)!=null?Nt:G.id,Ne=M(G);if(we){let Ct=String(we);return K(Ne,Ct),Ct}if(Ne){let Ct=x.byCall.get(Ne);if(Ct)return x.lastId=Ct,Ct}if(x.lastId&&!Fe)return x.lastId;if(!Fe)return null;let vt=`tool-${c()}`;return K(Ne,vt),vt},Q=G=>{let Fe=v.get(G);if(Fe)return Fe;let we={id:`tool-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:G,status:"pending"}};return v.set(G,we),p(we),we},Y=G=>{if(typeof G=="number"&&Number.isFinite(G))return G;if(typeof G=="string"){let Fe=Number(G);if(!Number.isNaN(Fe)&&Number.isFinite(Fe))return Fe;let we=Date.parse(G);if(!Number.isNaN(we))return we}return Date.now()},V=G=>{if(typeof G=="string")return G;if(G==null)return"";try{return JSON.stringify(G)}catch{return String(G)}},j=new Map,ce=new Map,he=null,gt=new Map,lt=(mt=this.config.iterationDisplay)!=null?mt:"separate";for(;;){let{done:G,value:Fe}=await o.read();if(G)break;a+=s.decode(Fe,{stream:!0});let we=a.split(`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(e=s),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Cs=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Us=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},zs=()=>{var n;let e=bc();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},Js=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let o=qi(t,Ui|zi);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?vs(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=vs(o.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},xc=e=>{let n=null,t=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?vs(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?vs(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>n,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=t)return n!==null?{text:n,raw:s}:null;try{let i=qi(s,Ui|zi),d=o(i);d!==null&&(n=d)}catch{}return t=s.length,{text:n||"",raw:s}},close:()=>{}}},Ks=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var vc="https://api.runtype.com/v1/dispatch",Ys="https://api.runtype.com",Xs=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Cc(e){switch(e){case"json":return Js;case"regex-json":return zs;case"xml":return Ks;default:return Us}}var lr=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,o;this.apiUrl=(t=n.apiUrl)!=null?t:vc,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:Cc(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 r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;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 r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var s,a;let n=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let o=await r.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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/v1/client/feedback`}async sendFeedback(n){var s,a;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 i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var o,s,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(s=(o=this.config).onSessionExpired)==null||s.call(o);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(n.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(Xs).map(m=>{var C,v,E;return{id:m.id,role:m.role,content:(E=(v=(C=m.contentParts)!=null?C:m.llmContent)!=null?v:m.rawContent)!=null?E:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let y=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!y.ok){let m=await y.json().catch(()=>({error:"Chat request failed"}));if(y.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(y.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!y.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(y.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({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 i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({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 i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ys}/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:t,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Xs).filter(o=>o.role==="user"||o.role==="assistant"||o.role==="system").filter(o=>!o.variant||o.variant==="assistant").sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i:o.content,createdAt:o.createdAt}}),r={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let o={};await Promise.all(this.contextProviders.map(async s=>{try{let a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}return r}async buildPayload(n){let r={messages:n.slice().filter(Xs).sort((o,s)=>{let a=new Date(o.createdAt).getTime(),i=new Date(s.createdAt).getTime();return a-i}).map(o=>{var s,a,i;return{role:o.role,content:(i=(a=(s=o.contentParts)!=null?s:o.llmContent)!=null?a:o.rawContent)!=null?i: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 a=await s({messages:n,config:this.config});a&&typeof a=="object"&&Object.assign(o,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(o).length&&(r.context=o)}if(this.requestMiddleware)try{let o=await this.requestMiddleware({payload:{...r},config:this.config});if(o&&typeof o=="object")return o}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",o)}return r}async handleCustomSSEEvent(n,t,r,o,s){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(n);if(a===null)return!1;let i=()=>{if(r.current)return r.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s()};return r.current=d,o(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,o(d)}return a.done&&(r.current&&(r.current.streaming=!1,o(r.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(n,t,r){var mt,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H,Z,z,Pe,Ce,Ie,Be,ut,ye,be,$e,de,bt,Gt,pn,un,ts,Ln,Xn,Ge,gn,Pn,an,vr,mn,dt,tn,vn,Cr,Gn,wr,Nn,fn,On,xt,hn,Sr,In,yn,W,Wn,Rn,Ar,Cn,Dn,Er,wn,Sn,Zn,Qn,ns,rs,ss,Tr,er,qe,Mr,nn,zt,os,as,kr,_n,An,is,ls,cs,js,jn,tr,ft,nr,rr,Lr,Pr,Ir,Wr,Vt,Zt,En,Re,Rr,Vn,ln,ds,sr,or,qn,Hn,ps,us,cn,Un,gs;let o=n.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=G=>{let Fe=G.reasoning?{...G.reasoning,chunks:[...G.reasoning.chunks]}:void 0,we=G.toolCall?{...G.toolCall,chunks:G.toolCall.chunks?[...G.toolCall.chunks]:void 0}:void 0,Ne=G.tools?G.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...G,reasoning:Fe,toolCall:we,tools:Ne}},p=G=>{t({type:"message",message:g(G)})},y=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=G=>{if(G==null)return null;try{return String(G)}catch{return null}},U=G=>{var Fe,we,Ne,vt,Nt;return k((Nt=(vt=(Ne=(we=(Fe=G.stepId)!=null?Fe:G.step_id)!=null?we:G.step)!=null?Ne:G.parentId)!=null?vt:G.flowStepId)!=null?Nt:G.flow_step_id)},M=G=>{var Fe,we,Ne,vt,Nt,Ct,b;return k((b=(Ct=(Nt=(vt=(Ne=(we=(Fe=G.callId)!=null?Fe:G.call_id)!=null?we:G.requestId)!=null?Ne:G.request_id)!=null?vt:G.toolCallId)!=null?Nt:G.tool_call_id)!=null?Ct:G.stepId)!=null?b:G.step_id)},O=()=>y||(y={id:r!=null?r:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(y),y),S=(G,Fe)=>{E.lastId=Fe,G&&E.byStep.set(G,Fe)},N=(G,Fe)=>{var Nt;let we=(Nt=G.reasoningId)!=null?Nt:G.id,Ne=U(G);if(we){let Ct=String(we);return S(Ne,Ct),Ct}if(Ne){let Ct=E.byStep.get(Ne);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!Fe)return E.lastId;if(!Fe)return null;let vt=`reason-${c()}`;return S(Ne,vt),vt},Q=G=>{let Fe=C.get(G);if(Fe)return Fe;let we={id:`reason-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:G,status:"streaming",chunks:[]}};return C.set(G,we),p(we),we},K=(G,Fe)=>{x.lastId=Fe,G&&x.byCall.set(G,Fe)},re=new Set,J=new Map,pe=new Set,Le=new Map,Ye=G=>{if(!G)return!1;let Fe=G.replace(/_+/g,"_").replace(/^_|_$/g,"");return Fe==="emit_artifact_markdown"||Fe==="emit_artifact_component"},fe=(G,Fe)=>{var Nt;let we=(Nt=G.toolId)!=null?Nt:G.id,Ne=M(G);if(we){let Ct=String(we);return K(Ne,Ct),Ct}if(Ne){let Ct=x.byCall.get(Ne);if(Ct)return x.lastId=Ct,Ct}if(x.lastId&&!Fe)return x.lastId;if(!Fe)return null;let vt=`tool-${c()}`;return K(Ne,vt),vt},ee=G=>{let Fe=v.get(G);if(Fe)return Fe;let we={id:`tool-${G}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:G,status:"pending"}};return v.set(G,we),p(we),we},Y=G=>{if(typeof G=="number"&&Number.isFinite(G))return G;if(typeof G=="string"){let Fe=Number(G);if(!Number.isNaN(Fe)&&Number.isFinite(Fe))return Fe;let we=Date.parse(G);if(!Number.isNaN(we))return we}return Date.now()},V=G=>{if(typeof G=="string")return G;if(G==null)return"";try{return JSON.stringify(G)}catch{return String(G)}},j=new Map,ce=new Map,he=null,gt=new Map,lt=(mt=this.config.iterationDisplay)!=null?mt:"separate";for(;;){let{done:G,value:Fe}=await o.read();if(G)break;a+=s.decode(Fe,{stream:!0});let we=a.split(`
|
|
5
5
|
|
|
6
|
-
`);a=(
|
|
7
|
-
`),Nt="message",Ct="";for(let T of vt)T.startsWith("event:")?Nt=T.replace("event:","").trim():T.startsWith("data:")&&(Ct+=T.replace("data:","").trim());if(!Ct)continue;let b;try{b=JSON.parse(Ct)}catch(T){n({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let De=Nt!=="message"?Nt:(le=b.type)!=null?le:"message";if((se=this.onSSEEvent)==null||se.call(this,De,b),this.parseSSEEvent){m.current=y;let T=await this.handleCustomSSEEvent(b,n,m,p,c);if(m.current&&!y&&(y=m.current),T)continue}if(De==="reason_start"){let T=(q=N(b,!0))!=null?q:`reason-${c()}`,w=Z(T);w.reasoning=(ne=w.reasoning)!=null?ne:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ee=w.reasoning.startedAt)!=null?Ee:Y((oe=b.startedAt)!=null?oe:b.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(De==="reason_delta"||De==="reason_chunk"){let T=(ee=(Ke=N(b,!1))!=null?Ke:N(b,!0))!=null?ee:`reason-${c()}`,w=Z(T);w.reasoning=(X=w.reasoning)!=null?X:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ve=w.reasoning.startedAt)!=null?Ve:Y((He=b.startedAt)!=null?He:b.timestamp);let I=(Dt=(jt=(et=b.reasoningText)!=null?et:b.text)!=null?jt:b.delta)!=null?Dt:"";if(I&&b.hidden!==!0&&w.reasoning.chunks.push(String(I)),w.reasoning.status=b.done?"complete":"streaming",b.done){w.reasoning.completedAt=Y((ie=b.completedAt)!=null?ie:b.timestamp);let ae=(Ue=w.reasoning.startedAt)!=null?Ue:Date.now();w.reasoning.durationMs=Math.max(0,((Te=w.reasoning.completedAt)!=null?Te:Date.now())-ae)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(De==="reason_complete"){let T=(_e=(tt=N(b,!1))!=null?tt:N(b,!0))!=null?_e:`reason-${c()}`,w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y((Xe=b.completedAt)!=null?Xe:b.timestamp);let ae=($t=w.reasoning.startedAt)!=null?$t:Date.now();w.reasoning.durationMs=Math.max(0,((Ft=w.reasoning.completedAt)!=null?Ft:Date.now())-ae),w.streaming=!1,p(w)}let I=U(b);I&&E.byStep.delete(I)}else if(De==="tool_start"){let T=(It=fe(b,!0))!=null?It:`tool-${c()}`,w=(H=b.toolName)!=null?H:b.name;if(Ye(w)){re.add(T);continue}let I=Q(T),ae=(te=I.toolCall)!=null?te:{id:T,status:"pending"};ae.name=w!=null?w:ae.name,ae.status="running",b.args!==void 0?ae.args=b.args:b.parameters!==void 0&&(ae.args=b.parameters),ae.startedAt=(We=ae.startedAt)!=null?We:Y((J=b.startedAt)!=null?J:b.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,I.toolCall=ae,I.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(I.agentMetadata={executionId:(Ce=Se==null?void 0:Se.executionId)!=null?Ce:b.executionId,iteration:(Pe=Se==null?void 0:Se.iteration)!=null?Pe:b.iteration}),p(I)}else if(De==="tool_chunk"||De==="tool_delta"){let T=(ut=(Be=fe(b,!1))!=null?Be:fe(b,!0))!=null?ut:`tool-${c()}`;if(re.has(T))continue;let w=Q(T),I=(ye=w.toolCall)!=null?ye:{id:T,status:"running"};I.startedAt=($e=I.startedAt)!=null?$e:Y((be=b.startedAt)!=null?be:b.timestamp);let ae=(Gt=(bt=(de=b.text)!=null?de:b.delta)!=null?bt:b.message)!=null?Gt:"";ae&&(I.chunks=(pn=I.chunks)!=null?pn:[],I.chunks.push(String(ae))),I.status="running",w.toolCall=I,w.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(Ln=w.agentMetadata)!=null?Ln:{executionId:(un=Se==null?void 0:Se.executionId)!=null?un:b.executionId,iteration:(ts=Se==null?void 0:Se.iteration)!=null?ts:b.iteration}),p(w)}else if(De==="tool_complete"){let T=(Ge=(Xn=fe(b,!1))!=null?Xn:fe(b,!0))!=null?Ge:`tool-${c()}`;if(re.has(T)){re.delete(T);continue}let w=Q(T),I=(gn=w.toolCall)!=null?gn:{id:T,status:"running"};I.status="complete",b.result!==void 0&&(I.result=b.result),typeof b.duration=="number"&&(I.duration=b.duration),I.completedAt=Y((Pn=b.completedAt)!=null?Pn:b.timestamp);let ae=(an=b.duration)!=null?an:b.executionTime;if(typeof ae=="number")I.durationMs=ae;else{let Mt=(vr=I.startedAt)!=null?vr:Date.now();I.durationMs=Math.max(0,((mn=I.completedAt)!=null?mn:Date.now())-Mt)}w.toolCall=I,w.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(vn=w.agentMetadata)!=null?vn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(tn=Se==null?void 0:Se.iteration)!=null?tn:b.iteration}),p(w);let nt=M(b);nt&&x.byCall.delete(nt)}else if(De==="step_chunk"||De==="step_delta"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=O(),ae=(Nn=(wr=(Gn=(Cr=b.text)!=null?Cr:b.delta)!=null?Gn:b.content)!=null?wr:b.chunk)!=null?Nn:"";if(ae){let nt=((fn=ce.get(I.id))!=null?fn:"")+ae;I.rawContent=nt,j.has(I.id)||j.set(I.id,this.createStreamParser());let Mt=j.get(I.id),wt=nt.trim().startsWith("{")||nt.trim().startsWith("[");if(wt&&ce.set(I.id,nt),Mt.__isPlainTextParser===!0){I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I);continue}let kt=Mt.processChunk(nt);if(kt instanceof Promise)kt.then(rt=>{var Et;let at=typeof rt=="string"?rt:(Et=rt==null?void 0:rt.text)!=null?Et:null;if(at!==null&&at.trim()!==""){let it=y;it&&it.id===I.id&&(it.content=at,p(it))}else if(!wt&&!nt.trim().startsWith("<")){let it=y;it&&it.id===I.id&&(it.content+=ae,ce.delete(it.id),j.delete(it.id),it.rawContent=void 0,p(it))}}).catch(()=>{I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I)});else{let rt=typeof kt=="string"?kt:(On=kt==null?void 0:kt.text)!=null?On:null;rt!==null&&rt.trim()!==""?(I.content=rt,p(I)):!wt&&!nt.trim().startsWith("<")&&(I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I))}}if(b.isComplete){let Se=(hn=(xt=b.result)==null?void 0:xt.response)!=null?hn:I.content;if(Se){let nt=ce.get(I.id),Mt=nt!=null?nt:V(Se);I.rawContent=Mt;let wt=j.get(I.id),Wt=null,kt=!1;if(wt&&(Wt=wt.getExtractedText(),Wt===null&&(Wt=Cs(Mt)),Wt===null)){let rt=wt.processChunk(Mt);rt instanceof Promise?(kt=!0,rt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Rt=y;Rt&&Rt.id===I.id&&(Rt.content=Et,Rt.streaming=!1,j.delete(Rt.id),ce.delete(Rt.id),p(Rt))}})):Wt=typeof rt=="string"?rt:(Sr=rt==null?void 0:rt.text)!=null?Sr:null}if(!kt){Wt!==null&&Wt.trim()!==""?I.content=Wt:ce.has(I.id)||(I.content=V(Se));let rt=j.get(I.id);if(rt){let at=(In=rt.close)==null?void 0:In.call(rt);at instanceof Promise&&at.catch(()=>{}),j.delete(I.id)}ce.delete(I.id),I.streaming=!1,p(I)}}}}else if(De==="step_complete"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=(yn=b.result)==null?void 0:yn.response,ae=O();if(I!=null){let Se=j.get(ae.id),nt=!1,Mt=!1;if(Se){let wt=Se.getExtractedText(),Wt=ce.get(ae.id),kt=Wt!=null?Wt:V(I);if(ae.rawContent=kt,wt!==null&&wt.trim()!=="")ae.content=wt,nt=!0;else{let rt=Cs(kt);if(rt!==null)ae.content=rt,nt=!0;else{let at=Se.processChunk(kt);if(at instanceof Promise)Mt=!0,at.then(Et=>{var Rt;let it=typeof Et=="string"?Et:(Rt=Et==null?void 0:Et.text)!=null?Rt:null;if(it!==null&&it.trim()!==""){let Jt=y;Jt&&Jt.id===ae.id&&(Jt.content=it,Jt.streaming=!1,j.delete(Jt.id),ce.delete(Jt.id),p(Jt))}else{let Jt=Se.getExtractedText(),rn=y;rn&&rn.id===ae.id&&(Jt!==null&&Jt.trim()!==""?rn.content=Jt:ce.has(rn.id)||(rn.content=V(I)),rn.streaming=!1,j.delete(rn.id),ce.delete(rn.id),p(rn))}});else{let Et=typeof at=="string"?at:(W=at==null?void 0:at.text)!=null?W:null;if(Et!==null&&Et.trim()!=="")ae.content=Et,nt=!0;else{let it=Se.getExtractedText();it!==null&&it.trim()!==""&&(ae.content=it,nt=!0)}}}}}if(!Mt){if(!ae.rawContent){let wt=ce.get(ae.id);ae.rawContent=wt!=null?wt:V(I)}if(!nt&&!ce.has(ae.id)&&(ae.content=V(I)),Se){let wt=(Wn=Se.close)==null?void 0:Wn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}}else j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}else if(De==="flow_complete"){let T=(Rn=b.result)==null?void 0:Rn.response;if(T!=null){let w=O(),I=ce.get(w.id),ae=I!=null?I:V(T);w.rawContent=ae;let Se=V(T),nt=j.get(w.id);if(nt){let Wt=Cs(ae);if(Wt!==null)Se=Wt;else{let kt=nt.processChunk(ae);kt instanceof Promise&&kt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Rt=y;Rt&&Rt.id===w.id&&(Rt.content=Et,Rt.streaming=!1,p(Rt))}});let rt=nt.getExtractedText();rt!==null&&(Se=rt)}}j.delete(w.id),ce.delete(w.id);let Mt=Se!==w.content,wt=w.streaming!==!1;Mt&&(w.content=Se),w.streaming=!1,(Mt||wt)&&p(w)}else if(y!==null){let w=y;j.delete(w.id),ce.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}n({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Ar=b.agentId)!=null?Ar:"virtual",agentName:(Cn=b.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(Dn=b.maxTurns)!=null?Dn:1,startedAt:Y(b.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=b.iteration),lt==="separate"&&b.iteration>1){let T=y;T&&(T.streaming=!1,p(T),gt.set(b.iteration-1,T),y=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let T=O();T.content+=(Er=b.delta)!=null?Er:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:he==null?void 0:he.agentName},p(T)}else if(b.contentType==="thinking"){let T=(wn=b.turnId)!=null?wn:`agent-think-${b.iteration}`,w=Z(T);w.reasoning=(Sn=w.reasoning)!=null?Sn:{id:T,status:"streaming",chunks:[]},w.reasoning.chunks.push((Zn=b.delta)!=null?Zn:""),w.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(w)}else if(b.contentType==="tool_input"){let T=(Qn=b.toolCallId)!=null?Qn:x.lastId;if(T){let w=v.get(T);w!=null&&w.toolCall&&(w.toolCall.chunks=(ns=w.toolCall.chunks)!=null?ns:[],w.toolCall.chunks.push((rs=b.delta)!=null?rs:""),p(w))}}}else if(De==="agent_turn_complete"){let T=b.turnId;if(T){let w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y(b.completedAt);let I=(ss=w.reasoning.startedAt)!=null?ss:Date.now();w.reasoning.durationMs=Math.max(0,((Tr=w.reasoning.completedAt)!=null?Tr:Date.now())-I),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let T=(er=b.toolCallId)!=null?er:`agent-tool-${c()}`;K(M(b),T);let w=Q(T),I=(qe=w.toolCall)!=null?qe:{id:T,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};I.name=(nn=(Mr=b.toolName)!=null?Mr:b.name)!=null?nn:I.name,I.status="running",b.parameters!==void 0&&(I.args=b.parameters),I.startedAt=Y((zt=b.startedAt)!=null?zt:b.timestamp),w.toolCall=I,w.streaming=!0,w.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(w)}else if(De==="agent_tool_delta"){let T=(os=b.toolCallId)!=null?os:x.lastId;if(T){let w=(as=v.get(T))!=null?as:Q(T);w.toolCall&&(w.toolCall.chunks=(kr=w.toolCall.chunks)!=null?kr:[],w.toolCall.chunks.push((_n=b.delta)!=null?_n:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(De==="agent_tool_complete"){let T=(An=b.toolCallId)!=null?An:x.lastId;if(T){let w=(is=v.get(T))!=null?is:Q(T);if(w.toolCall){w.toolCall.status="complete",b.result!==void 0&&(w.toolCall.result=b.result),typeof b.executionTime=="number"&&(w.toolCall.durationMs=b.executionTime),w.toolCall.completedAt=Y((ls=b.completedAt)!=null?ls:b.timestamp),w.streaming=!1,p(w);let I=M(b);I&&x.byCall.delete(I)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,w={id:T,role:"assistant",content:(cs=b.reflection)!=null?cs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(js=b.reflection)!=null?js:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(w)}else if(De==="agent_complete"){he&&(he.status=b.success?"complete":"error",he.completedAt=Y(b.completedAt),he.stopReason=b.stopReason);let T=y;T&&(T.streaming=!1,p(T)),n({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(tr=(jn=b.error)==null?void 0:jn.message)!=null?tr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):n({type:"error",error:new Error(T)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let T=(ft=b.approvalId)!=null?ft:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(nr=he==null?void 0:he.agentId)!=null?nr:"virtual",executionId:(Lr=(rr=b.executionId)!=null?rr:he==null?void 0:he.executionId)!=null?Lr:"",toolName:(Pr=b.toolName)!=null?Pr:"",toolType:b.toolType,description:(Wr=b.description)!=null?Wr:`Execute ${(Ir=b.toolName)!=null?Ir:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(Vt=b.approvalId)!=null?Vt:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Zt=he==null?void 0:he.agentId)!=null?Zt:"virtual",executionId:(Re=(En=b.executionId)!=null?En:he==null?void 0:he.executionId)!=null?Re:"",toolName:(Rr=b.toolName)!=null?Rr:"",toolType:b.toolType,description:(ln=b.description)!=null?ln:`Execute ${(Vn=b.toolName)!=null?Vn:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="agent_approval_complete"){let T=b.approvalId;if(T){let I={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(ds=b.decision)!=null?ds:"approved",agentId:(sr=he==null?void 0:he.agentId)!=null?sr:"virtual",executionId:(qn=(or=b.executionId)!=null?or:he==null?void 0:he.executionId)!=null?qn:"",toolName:(Hn=b.toolName)!=null?Hn:"",description:(ps=b.description)!=null?ps:"",resolvedAt:Date.now()}};p(I)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let T=b.artifactType,w=String(b.id),I=typeof b.title=="string"?b.title:void 0;if(n({type:"artifact_start",id:w,artifactType:T,title:I,component:typeof b.component=="string"?b.component:void 0}),Le.set(w,{markdown:"",title:I}),!pe.has(w)){pe.add(w);let ae={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:I,artifactType:T,status:"streaming"}})};z.set(w,ae),p(ae)}}else if(De==="artifact_delta"){let T=String(b.id),w=typeof b.delta=="string"?b.delta:String((us=b.delta)!=null?us:"");n({type:"artifact_delta",id:T,artDelta:w});let I=Le.get(T);I&&(I.markdown+=w)}else if(De==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};n({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let T=String(b.id);n({type:"artifact_complete",id:T});let w=z.get(T);if(w){w.streaming=!1;try{let I=JSON.parse((cn=w.rawContent)!=null?cn:"{}");if(I.props){I.props.status="complete";let ae=Le.get(T);ae!=null&&ae.markdown&&(I.props.markdown=ae.markdown)}w.rawContent=JSON.stringify(I)}catch{}Le.delete(T),p(w),z.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let w=String((Un=T.id)!=null?Un:`msg-${c()}`),I=T.role,Se={id:w,role:I==="user"?"user":I==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let nt=JSON.parse(Se.rawContent),Mt=(gs=nt==null?void 0:nt.props)==null?void 0:gs.artifactId;typeof Mt=="string"&&pe.add(Mt)}catch{}y=null,m.current=null,j.delete(w),ce.delete(w)}else De==="error"&&b.error&&n({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function wc(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function jr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function cr(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var ws="[Image]";function Sc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ac(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ec(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Tc(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Gs(e){return{type:"text",text:e}}function Mc(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function kc(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Lc(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Yi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pc=["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"],Mn=[...Yi,...Pc];function Ic(e){return Yi.includes(e)||e.startsWith("image/")}function Ss(e){return Ic(e.type)}async function Xi(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ss(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gi(e,t=Mn,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Wc(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Zi(e,t){let n=Wc(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var As=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),o=this.pcmToFloat32(n),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var Es=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let g=0;g<a.length;g++)i+=a[g]*a[g];let d=Math.sqrt(i/a.length);(r==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Vr=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Es;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((y,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=x=>{C||(C=!0,clearTimeout(E),m(new Error(x)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),y())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+g+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let k=x.code!==1006?` (code ${x.code})`:"";v("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new As(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let g=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:g});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let c=0;c<n.length;c++)r[c]=n.charCodeAt(c);let o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Kn=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vr(e.runtype);case"browser":if(!Kn.isSupported())throw new Error("Browser speech recognition not supported");return new Kn(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Zs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return dr({type:"runtype",runtype:e.runtype});if(Kn.isSupported())return dr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(e){try{return Zs(e),!0}catch{return!1}}var qr=class e{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=t=>{var n,r,o,s,a,i,d;t.type==="message"?(this.upsertMessage(t.message),(n=t.message.agentMetadata)!=null&&n.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(r=t.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(o=t.message.agentMetadata.iteration)!=null?o:0,maxTurns:0})):t.type==="status"?(this.setStatus(t.status),t.status==="connecting"?this.setStreaming(!0):(t.status==="idle"||t.status==="error")&&(this.setStreaming(!1),this.abortController=null,((s=this.agentExecution)==null?void 0:s.status)==="running"&&(this.agentExecution.status=t.status==="error"?"error":"complete"))):t.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new lr(t),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(t){var n,r,o;try{let s=t||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=dr(s);let a=(n=this.config.voiceRecognition)!=null?n:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var g,p,y,m,C,v;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((g=c.transcript)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((y=c.text)!=null&&y.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var g,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(g=this.callbacks).onVoiceStatusChanged)==null||p.call(g,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=t.runtype)==null?void 0:r.agentId)||"",clientToken:((o=t.runtype)==null?void 0:o.clientToken)||"",host:(s=t.runtype)==null?void 0:s.host,voiceId:(a=t.runtype)==null?void 0:a.voiceId,pauseDuration:(i=t.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=t.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=t.browser)==null?void 0:c.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n=this.client.getSSEEventCallback();this.config={...this.config,...t},this.client=new lr(this.config),n&&this.client.setSSEEventCallback(n)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=t,y={id:a!=null?a:n==="user"?jr():n==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...g!==void 0&&{voiceProcessing:g}};return this.upsertMessage(y),y}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:o==="user"?jr():o==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};n.push(m)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}async sendMessage(t,n){var c,g,p,y,m;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=jr(),s=cr(),a={id:o,role:"user",content:r||ws,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){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,v||(C instanceof Error?(p=(g=this.callbacks).onError)==null||p.call(g,C):(m=(y=this.callbacks).onError)==null||m.call(y,new Error(String(C))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=cr();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(c){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(g),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(t,n){var o,s,a;if(this.streaming)return;(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(t,n){var d,c,g;let r=`approval-${t.id}`,o={...t,status:n,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n):p=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),p){let y=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}y=p.body}else p instanceof ReadableStream&&(y=p);y?await this.connectStream(y):n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(p){(g=(c=this.callbacks).onError)==null||g.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,t)}speak(t,n){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t),s=r.getVoices();if(n.voice){let a=s.find(i=>i.name===n.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=n.pickVoice?n.pickVoice(s):e.pickBestVoice(s));n.rate!==void 0&&(o.rate=n.rate),n.pitch!==void 0&&(o.pitch=n.pitch),setTimeout(()=>r.speak(o),50)}static pickBestVoice(t){var r;let n=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of n){let s=t.find(a=>a.name===o);if(s)return s}return(r=t.find(o=>o.lang.startsWith("en")))!=null?r:t[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>s===r?{...o,...n}:o),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var f=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},bn=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};import*as Rc from"lucide";var ue=(e,t=24,n="currentColor",r=2)=>{try{let o=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=Rc[o];return s?Hc(s,t,n,r):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Hc(e,t,n,r){if(!e||!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],i=s[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}}}),o}var Ms={allowedTypes:Mn,maxFileSize:10*1024*1024,maxFiles:4};function Bc(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $c(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var pr=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ms.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ms.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ms.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ms.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let g=Gi(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,p);continue}try{let p=await Xi(c),y=Ss(c)?URL.createObjectURL(c):null,m={id:Bc(),file:c,previewUrl:y,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ss(t.file),r=f("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=f("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=f("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=$c(t.file.type),d=ue(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Zi(t.file.type,t.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=f("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-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="var(--persona-palette-colors-black-alpha-60, 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=ue("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Qi={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},el={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},tl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}}};function nl(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?nl(e,r):r}function Qs(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=nl(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function rl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function sl(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=sl(s,o):n[r]=o}return n}function Fc(e,t){return t?sl(e,t):e}function Ur(e,t={}){var o,s,a,i,d,c,g,p,y,m,C,v,E;let n={palette:Qi,semantic:el,components:tl},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...n.semantic.colors.interactive,...(y=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:y.interactive},feedback:{...n.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Fc(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let x=rl(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(t.plugins)for(let x of t.plugins)r=x.transform(r);return r}function eo(e){var d,c,g,p,y,m,C,v,E,x,k,U,M,O,S,N,Z,K,re,z,pe,Le,Ye,fe,Q,Y,V,j,ce,he,gt,lt,mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe;let t=Qs(e),n={};for(let[$t,Ft]of Object.entries(t)){let It=$t.replace(/\./g,"-");n[`--persona-${It}`]=Ft.value}n["--persona-primary"]=(d=n["--persona-semantic-colors-primary"])!=null?d:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(c=n["--persona-semantic-colors-secondary"])!=null?c:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(g=n["--persona-semantic-colors-accent"])!=null?g:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(p=n["--persona-semantic-colors-surface"])!=null?p:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(y=n["--persona-semantic-colors-background"])!=null?y:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(m=n["--persona-semantic-colors-container"])!=null?m:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(C=n["--persona-semantic-colors-text"])!=null?C:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(v=n["--persona-semantic-colors-text-muted"])!=null?v:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(E=n["--persona-semantic-colors-text-inverse"])!=null?E:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(x=n["--persona-semantic-colors-border"])!=null?x:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(k=n["--persona-semantic-colors-divider"])!=null?k:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(U=n["--persona-components-voice-recording-indicator"])!=null?U:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(M=n["--persona-components-voice-recording-background"])!=null?M:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(O=n["--persona-components-voice-processing-icon"])!=null?O:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(S=n["--persona-components-voice-speaking-icon"])!=null?S:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(N=n["--persona-components-approval-requested-background"])!=null?N:n["--persona-palette-colors-warning-50"],n["--persona-approval-border"]=(Z=n["--persona-components-approval-requested-border"])!=null?Z:n["--persona-palette-colors-warning-200"],n["--persona-approval-text"]=(K=n["--persona-components-approval-requested-text"])!=null?K:n["--persona-palette-colors-gray-900"],n["--persona-approval-approve-bg"]=(re=n["--persona-components-approval-approve-background"])!=null?re:n["--persona-palette-colors-success-500"],n["--persona-approval-deny-bg"]=(z=n["--persona-components-approval-deny-background"])!=null?z:n["--persona-palette-colors-error-500"],n["--persona-attachment-image-bg"]=(pe=n["--persona-components-attachment-image-background"])!=null?pe:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(Le=n["--persona-components-attachment-image-border"])!=null?Le:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(Ye=n["--persona-semantic-typography-fontFamily"])!=null?Ye:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(fe=n["--persona-semantic-typography-fontSize"])!=null?fe:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(Q=n["--persona-semantic-typography-fontWeight"])!=null?Q:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Y=n["--persona-semantic-typography-lineHeight"])!=null?Y:n["--persona-palette-typography-lineHeight-normal"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(j=n["--persona-palette-radius-md"])!=null?j:"0.375rem",n["--persona-radius-lg"]=(ce=n["--persona-palette-radius-lg"])!=null?ce:"0.5rem",n["--persona-radius-xl"]=(he=n["--persona-palette-radius-xl"])!=null?he:"0.75rem",n["--persona-launcher-radius"]=(lt=(gt=n["--persona-components-launcher-borderRadius"])!=null?gt:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-button-radius"]=(Pt=(mt=n["--persona-components-button-primary-borderRadius"])!=null?mt:n["--persona-palette-radius-full"])!=null?Pt:"9999px",n["--persona-panel-radius"]=(se=(le=n["--persona-components-panel-borderRadius"])!=null?le:n["--persona-radius-xl"])!=null?se:"0.75rem",n["--persona-input-radius"]=(ne=(q=n["--persona-components-input-borderRadius"])!=null?q:n["--persona-radius-lg"])!=null?ne:"0.5rem",n["--persona-message-user-radius"]=(Ee=(oe=n["--persona-components-message-user-borderRadius"])!=null?oe:n["--persona-radius-lg"])!=null?Ee:"0.5rem",n["--persona-message-assistant-radius"]=(ee=(Ke=n["--persona-components-message-assistant-borderRadius"])!=null?Ke:n["--persona-radius-lg"])!=null?ee:"0.5rem",n["--persona-header-bg"]=(X=n["--persona-components-header-background"])!=null?X:n["--persona-surface"],n["--persona-header-border"]=(He=n["--persona-components-header-border"])!=null?He:n["--persona-divider"],n["--persona-message-user-bg"]=(Ve=n["--persona-components-message-user-background"])!=null?Ve:n["--persona-accent"],n["--persona-message-user-text"]=(et=n["--persona-components-message-user-text"])!=null?et:n["--persona-text-inverse"],n["--persona-message-assistant-bg"]=(jt=n["--persona-components-message-assistant-background"])!=null?jt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Dt=n["--persona-components-message-assistant-text"])!=null?Dt:n["--persona-text"],n["--persona-message-assistant-border"]=(ie=n["--persona-components-message-assistant-border"])!=null?ie:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Ue=n["--persona-components-message-assistant-shadow"])!=null?Ue:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-md-inline-code-bg"]=(Te=n["--persona-components-markdown-inlineCode-background"])!=null?Te:n["--persona-container"],n["--persona-md-inline-code-color"]=(tt=n["--persona-components-markdown-inlineCode-foreground"])!=null?tt:n["--persona-text"],n["--persona-md-link-color"]=(Xe=(_e=n["--persona-components-markdown-link-foreground"])!=null?_e:n["--persona-accent"])!=null?Xe:"#3b82f6";let r=n["--persona-components-markdown-heading-h1-fontSize"];r&&(n["--persona-md-h1-size"]=r);let o=n["--persona-components-markdown-heading-h1-fontWeight"];o&&(n["--persona-md-h1-weight"]=o);let s=n["--persona-components-markdown-heading-h2-fontSize"];s&&(n["--persona-md-h2-size"]=s);let a=n["--persona-components-markdown-heading-h2-fontWeight"];a&&(n["--persona-md-h2-weight"]=a);let i=n["--persona-components-markdown-prose-fontFamily"];return i&&i!=="inherit"&&(n["--persona-md-prose-font-family"]=i),n}var to={primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.accent.600",surface:"palette.colors.gray.50",muted:"palette.colors.gray.500",container:"palette.colors.gray.100",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",messageBorder:"palette.colors.gray.200",inputBackground:"palette.colors.gray.50",callToAction:"palette.colors.gray.900",callToActionBackground:"palette.colors.gray.50",sendButtonBackgroundColor:"semantic.colors.primary",sendButtonTextColor:"semantic.colors.textInverse",sendButtonBorderColor:"semantic.colors.primary",closeButtonColor:"palette.colors.gray.500",closeButtonBackgroundColor:"transparent",clearChatIconColor:"palette.colors.gray.500",clearChatBackgroundColor:"transparent",micIconColor:"palette.colors.gray.900",micBackgroundColor:"transparent",recordingIconColor:"palette.colors.white",recordingBackgroundColor:"palette.colors.error.500",tooltipBackground:"palette.colors.gray.900",tooltipForeground:"palette.colors.white"},ol={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function no(e,t={}){if(!e)return{};let n={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,o]of Object.entries(e))if(o)if(r in to){let s=to[r],[a,i,d,c]=s.split(".");if(a==="palette"&&i==="colors"){let g=d;n.palette.colors[g]&&(n.palette.colors[g][c||"500"]=o)}else if(a==="semantic"){let g=s.replace("semantic.colors.","").split(".");g.length===1?n.semantic.colors[g[0]]=o:n.semantic.colors[g[0]]={...n.semantic.colors[g[0]],[g[1]]:o}}}else if(r in ol){n.palette.radius||(n.palette.radius={});let s=r.replace("radius","").toLowerCase();n.palette.radius[s||"md"]=o}else r==="inputFontFamily"?(n.palette.typography||(n.palette.typography={fontFamily:{}}),n.palette.typography.fontFamily={sans:o==="sans-serif"?"system-ui, sans-serif":void 0,serif:o==="serif"?"Georgia, serif":void 0,mono:o==="mono"?"monospace":void 0}):r==="inputFontWeight"?(n.palette.typography||(n.palette.typography={fontWeight:{}}),n.palette.typography.fontWeight={normal:o}):r==="panelBorder"?(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.border=o):r==="panelShadow"?(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.shadow=o):r==="panelBorderRadius"&&(n.components||(n.components={}),n.components.panel||(n.components.panel={}),n.components.panel.borderRadius=o);return t.warn!==!1&&console.warn("[Persona Widget] v1 theme configuration detected. v1 themes are deprecated in v2.0.0. Please migrate to the new semantic token system. See https://persona.sh/docs/v2-migration for guidance."),n}function Nc(e){let t=[],n=e;if(!n)return{valid:!0,warnings:[]};let r=Object.keys(n).filter(o=>!(o in to||o in ol||o==="inputFontFamily"||o==="inputFontWeight"||o.startsWith("panel")));return r.length>0&&t.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${r.join(", ")}`),{valid:!0,warnings:t}}var Oc={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=(e,t)=>{if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];ro(s)&&ro(o)?n[r]=so(s,o):n[r]=o}return n},Dc=e=>ro(e)&&("palette"in e||"semantic"in e||"components"in e),al=e=>{if(!e)return;let t=no(e,{warn:!1});return Dc(e)?so(t,e):t},ks=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},_c=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":ks()},il=e=>_c(e),jc=e=>Ur(e),Vc=e=>{var n;let t=Ur(void 0,{validate:!1});return Ur({...e,palette:{...t.palette,colors:{...Oc.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},ll=e=>{let t=il(e),n=al(e==null?void 0:e.theme),r=al(e==null?void 0:e.darkTheme);return t==="dark"?Vc(so(n,r)):jc(n)},qc=e=>eo(e),Yn=(e,t)=>{let n=ll(t),r=qc(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},oo=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(ks())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ks());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as Uc}from"idiomorph";var cl=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Uc.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&r&&(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};function dl(e,t){var n,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=e.llmContent)==null?void 0:c.length)!=null?g:0,(y=(p=e.approval)==null?void 0:p.status)!=null?y:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(E=(v=e.reasoning)==null?void 0:v.chunks)==null?void 0:E.length)!=null?x:0,(U=(k=e.contentParts)==null?void 0:k.length)!=null?U:0,t].join("\0")}function pl(){return new Map}function ul(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function gl(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function ml(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var zc={side:"right",width:"420px",collapsedWidth:"72px"},Ut=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},zr=e=>{var t,n;return{...zc,...(n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock)!=null?n:{}}};var dn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Jr=(e,t)=>{let n=f("button");n.type="button",n.innerHTML=`
|
|
6
|
+
`);a=(It=we.pop())!=null?It:"";for(let Ne of we){let vt=Ne.split(`
|
|
7
|
+
`),Nt="message",Ct="";for(let T of vt)T.startsWith("event:")?Nt=T.replace("event:","").trim():T.startsWith("data:")&&(Ct+=T.replace("data:","").trim());if(!Ct)continue;let b;try{b=JSON.parse(Ct)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let De=Nt!=="message"?Nt:(le=b.type)!=null?le:"message";if((se=this.onSSEEvent)==null||se.call(this,De,b),this.parseSSEEvent){m.current=y;let T=await this.handleCustomSSEEvent(b,t,m,p,c);if(m.current&&!y&&(y=m.current),T)continue}if(De==="reason_start"){let T=(q=N(b,!0))!=null?q:`reason-${c()}`,w=Q(T);w.reasoning=(ne=w.reasoning)!=null?ne:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ee=w.reasoning.startedAt)!=null?Ee:Y((oe=b.startedAt)!=null?oe:b.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",p(w)}else if(De==="reason_delta"||De==="reason_chunk"){let T=(te=(Ke=N(b,!1))!=null?Ke:N(b,!0))!=null?te:`reason-${c()}`,w=Q(T);w.reasoning=(X=w.reasoning)!=null?X:{id:T,status:"streaming",chunks:[]},w.reasoning.startedAt=(Ve=w.reasoning.startedAt)!=null?Ve:Y((He=b.startedAt)!=null?He:b.timestamp);let I=(Dt=(jt=(et=b.reasoningText)!=null?et:b.text)!=null?jt:b.delta)!=null?Dt:"";if(I&&b.hidden!==!0&&w.reasoning.chunks.push(String(I)),w.reasoning.status=b.done?"complete":"streaming",b.done){w.reasoning.completedAt=Y((ie=b.completedAt)!=null?ie:b.timestamp);let ae=(Ue=w.reasoning.startedAt)!=null?Ue:Date.now();w.reasoning.durationMs=Math.max(0,((Te=w.reasoning.completedAt)!=null?Te:Date.now())-ae)}w.streaming=w.reasoning.status!=="complete",p(w)}else if(De==="reason_complete"){let T=(_e=(tt=N(b,!1))!=null?tt:N(b,!0))!=null?_e:`reason-${c()}`,w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y((Xe=b.completedAt)!=null?Xe:b.timestamp);let ae=(Wt=w.reasoning.startedAt)!=null?Wt:Date.now();w.reasoning.durationMs=Math.max(0,((Rt=w.reasoning.completedAt)!=null?Rt:Date.now())-ae),w.streaming=!1,p(w)}let I=U(b);I&&E.byStep.delete(I)}else if(De==="tool_start"){let T=(Mt=fe(b,!0))!=null?Mt:`tool-${c()}`,w=(H=b.toolName)!=null?H:b.name;if(Ye(w)){re.add(T);continue}let I=ee(T),ae=(Z=I.toolCall)!=null?Z:{id:T,status:"pending"};ae.name=w!=null?w:ae.name,ae.status="running",b.args!==void 0?ae.args=b.args:b.parameters!==void 0&&(ae.args=b.parameters),ae.startedAt=(Pe=ae.startedAt)!=null?Pe:Y((z=b.startedAt)!=null?z:b.timestamp),ae.completedAt=void 0,ae.durationMs=void 0,I.toolCall=ae,I.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(I.agentMetadata={executionId:(Ce=Se==null?void 0:Se.executionId)!=null?Ce:b.executionId,iteration:(Ie=Se==null?void 0:Se.iteration)!=null?Ie:b.iteration}),p(I)}else if(De==="tool_chunk"||De==="tool_delta"){let T=(ut=(Be=fe(b,!1))!=null?Be:fe(b,!0))!=null?ut:`tool-${c()}`;if(re.has(T))continue;let w=ee(T),I=(ye=w.toolCall)!=null?ye:{id:T,status:"running"};I.startedAt=($e=I.startedAt)!=null?$e:Y((be=b.startedAt)!=null?be:b.timestamp);let ae=(Gt=(bt=(de=b.text)!=null?de:b.delta)!=null?bt:b.message)!=null?Gt:"";ae&&(I.chunks=(pn=I.chunks)!=null?pn:[],I.chunks.push(String(ae))),I.status="running",w.toolCall=I,w.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(Ln=w.agentMetadata)!=null?Ln:{executionId:(un=Se==null?void 0:Se.executionId)!=null?un:b.executionId,iteration:(ts=Se==null?void 0:Se.iteration)!=null?ts:b.iteration}),p(w)}else if(De==="tool_complete"){let T=(Ge=(Xn=fe(b,!1))!=null?Xn:fe(b,!0))!=null?Ge:`tool-${c()}`;if(re.has(T)){re.delete(T);continue}let w=ee(T),I=(gn=w.toolCall)!=null?gn:{id:T,status:"running"};I.status="complete",b.result!==void 0&&(I.result=b.result),typeof b.duration=="number"&&(I.duration=b.duration),I.completedAt=Y((Pn=b.completedAt)!=null?Pn:b.timestamp);let ae=(an=b.duration)!=null?an:b.executionTime;if(typeof ae=="number")I.durationMs=ae;else{let kt=(vr=I.startedAt)!=null?vr:Date.now();I.durationMs=Math.max(0,((mn=I.completedAt)!=null?mn:Date.now())-kt)}w.toolCall=I,w.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(w.agentMetadata=(vn=w.agentMetadata)!=null?vn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(tn=Se==null?void 0:Se.iteration)!=null?tn:b.iteration}),p(w);let nt=M(b);nt&&x.byCall.delete(nt)}else if(De==="step_chunk"||De==="step_delta"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=O(),ae=(Nn=(wr=(Gn=(Cr=b.text)!=null?Cr:b.delta)!=null?Gn:b.content)!=null?wr:b.chunk)!=null?Nn:"";if(ae){let nt=((fn=ce.get(I.id))!=null?fn:"")+ae;I.rawContent=nt,j.has(I.id)||j.set(I.id,this.createStreamParser());let kt=j.get(I.id),wt=nt.trim().startsWith("{")||nt.trim().startsWith("[");if(wt&&ce.set(I.id,nt),kt.__isPlainTextParser===!0){I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I);continue}let Lt=kt.processChunk(nt);if(Lt instanceof Promise)Lt.then(rt=>{var Et;let at=typeof rt=="string"?rt:(Et=rt==null?void 0:rt.text)!=null?Et:null;if(at!==null&&at.trim()!==""){let it=y;it&&it.id===I.id&&(it.content=at,p(it))}else if(!wt&&!nt.trim().startsWith("<")){let it=y;it&&it.id===I.id&&(it.content+=ae,ce.delete(it.id),j.delete(it.id),it.rawContent=void 0,p(it))}}).catch(()=>{I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I)});else{let rt=typeof Lt=="string"?Lt:(On=Lt==null?void 0:Lt.text)!=null?On:null;rt!==null&&rt.trim()!==""?(I.content=rt,p(I)):!wt&&!nt.trim().startsWith("<")&&(I.content+=ae,ce.delete(I.id),j.delete(I.id),I.rawContent=void 0,p(I))}}if(b.isComplete){let Se=(hn=(xt=b.result)==null?void 0:xt.response)!=null?hn:I.content;if(Se){let nt=ce.get(I.id),kt=nt!=null?nt:V(Se);I.rawContent=kt;let wt=j.get(I.id),Ht=null,Lt=!1;if(wt&&(Ht=wt.getExtractedText(),Ht===null&&(Ht=Cs(kt)),Ht===null)){let rt=wt.processChunk(kt);rt instanceof Promise?(Lt=!0,rt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Bt=y;Bt&&Bt.id===I.id&&(Bt.content=Et,Bt.streaming=!1,j.delete(Bt.id),ce.delete(Bt.id),p(Bt))}})):Ht=typeof rt=="string"?rt:(Sr=rt==null?void 0:rt.text)!=null?Sr:null}if(!Lt){Ht!==null&&Ht.trim()!==""?I.content=Ht:ce.has(I.id)||(I.content=V(Se));let rt=j.get(I.id);if(rt){let at=(In=rt.close)==null?void 0:In.call(rt);at instanceof Promise&&at.catch(()=>{}),j.delete(I.id)}ce.delete(I.id),I.streaming=!1,p(I)}}}}else if(De==="step_complete"){let T=b.stepType,w=b.executionType;if(T==="tool"||w==="context")continue;let I=(yn=b.result)==null?void 0:yn.response,ae=O();if(I!=null){let Se=j.get(ae.id),nt=!1,kt=!1;if(Se){let wt=Se.getExtractedText(),Ht=ce.get(ae.id),Lt=Ht!=null?Ht:V(I);if(ae.rawContent=Lt,wt!==null&&wt.trim()!=="")ae.content=wt,nt=!0;else{let rt=Cs(Lt);if(rt!==null)ae.content=rt,nt=!0;else{let at=Se.processChunk(Lt);if(at instanceof Promise)kt=!0,at.then(Et=>{var Bt;let it=typeof Et=="string"?Et:(Bt=Et==null?void 0:Et.text)!=null?Bt:null;if(it!==null&&it.trim()!==""){let Jt=y;Jt&&Jt.id===ae.id&&(Jt.content=it,Jt.streaming=!1,j.delete(Jt.id),ce.delete(Jt.id),p(Jt))}else{let Jt=Se.getExtractedText(),rn=y;rn&&rn.id===ae.id&&(Jt!==null&&Jt.trim()!==""?rn.content=Jt:ce.has(rn.id)||(rn.content=V(I)),rn.streaming=!1,j.delete(rn.id),ce.delete(rn.id),p(rn))}});else{let Et=typeof at=="string"?at:(W=at==null?void 0:at.text)!=null?W:null;if(Et!==null&&Et.trim()!=="")ae.content=Et,nt=!0;else{let it=Se.getExtractedText();it!==null&&it.trim()!==""&&(ae.content=it,nt=!0)}}}}}if(!kt){if(!ae.rawContent){let wt=ce.get(ae.id);ae.rawContent=wt!=null?wt:V(I)}if(!nt&&!ce.has(ae.id)&&(ae.content=V(I)),Se){let wt=(Wn=Se.close)==null?void 0:Wn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}}else j.delete(ae.id),ce.delete(ae.id),ae.streaming=!1,p(ae)}else if(De==="flow_complete"){let T=(Rn=b.result)==null?void 0:Rn.response;if(T!=null){let w=O(),I=ce.get(w.id),ae=I!=null?I:V(T);w.rawContent=ae;let Se=V(T),nt=j.get(w.id);if(nt){let Ht=Cs(ae);if(Ht!==null)Se=Ht;else{let Lt=nt.processChunk(ae);Lt instanceof Promise&&Lt.then(at=>{var it;let Et=typeof at=="string"?at:(it=at==null?void 0:at.text)!=null?it:null;if(Et!==null){let Bt=y;Bt&&Bt.id===w.id&&(Bt.content=Et,Bt.streaming=!1,p(Bt))}});let rt=nt.getExtractedText();rt!==null&&(Se=rt)}}j.delete(w.id),ce.delete(w.id);let kt=Se!==w.content,wt=w.streaming!==!1;kt&&(w.content=Se),w.streaming=!1,(kt||wt)&&p(w)}else if(y!==null){let w=y;j.delete(w.id),ce.delete(w.id),w.streaming!==!1&&(w.streaming=!1,p(w))}t({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Ar=b.agentId)!=null?Ar:"virtual",agentName:(Cn=b.agentName)!=null?Cn:"",status:"running",currentIteration:0,maxTurns:(Dn=b.maxTurns)!=null?Dn:1,startedAt:Y(b.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=b.iteration),lt==="separate"&&b.iteration>1){let T=y;T&&(T.streaming=!1,p(T),gt.set(b.iteration-1,T),y=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let T=O();T.content+=(Er=b.delta)!=null?Er:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:he==null?void 0:he.agentName},p(T)}else if(b.contentType==="thinking"){let T=(wn=b.turnId)!=null?wn:`agent-think-${b.iteration}`,w=Q(T);w.reasoning=(Sn=w.reasoning)!=null?Sn:{id:T,status:"streaming",chunks:[]},w.reasoning.chunks.push((Zn=b.delta)!=null?Zn:""),w.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(w)}else if(b.contentType==="tool_input"){let T=(Qn=b.toolCallId)!=null?Qn:x.lastId;if(T){let w=v.get(T);w!=null&&w.toolCall&&(w.toolCall.chunks=(ns=w.toolCall.chunks)!=null?ns:[],w.toolCall.chunks.push((rs=b.delta)!=null?rs:""),p(w))}}}else if(De==="agent_turn_complete"){let T=b.turnId;if(T){let w=C.get(T);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=Y(b.completedAt);let I=(ss=w.reasoning.startedAt)!=null?ss:Date.now();w.reasoning.durationMs=Math.max(0,((Tr=w.reasoning.completedAt)!=null?Tr:Date.now())-I),w.streaming=!1,p(w)}}}else if(De==="agent_tool_start"){let T=(er=b.toolCallId)!=null?er:`agent-tool-${c()}`;K(M(b),T);let w=ee(T),I=(qe=w.toolCall)!=null?qe:{id:T,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};I.name=(nn=(Mr=b.toolName)!=null?Mr:b.name)!=null?nn:I.name,I.status="running",b.parameters!==void 0&&(I.args=b.parameters),I.startedAt=Y((zt=b.startedAt)!=null?zt:b.timestamp),w.toolCall=I,w.streaming=!0,w.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(w)}else if(De==="agent_tool_delta"){let T=(os=b.toolCallId)!=null?os:x.lastId;if(T){let w=(as=v.get(T))!=null?as:ee(T);w.toolCall&&(w.toolCall.chunks=(kr=w.toolCall.chunks)!=null?kr:[],w.toolCall.chunks.push((_n=b.delta)!=null?_n:""),w.toolCall.status="running",w.streaming=!0,p(w))}}else if(De==="agent_tool_complete"){let T=(An=b.toolCallId)!=null?An:x.lastId;if(T){let w=(is=v.get(T))!=null?is:ee(T);if(w.toolCall){w.toolCall.status="complete",b.result!==void 0&&(w.toolCall.result=b.result),typeof b.executionTime=="number"&&(w.toolCall.durationMs=b.executionTime),w.toolCall.completedAt=Y((ls=b.completedAt)!=null?ls:b.timestamp),w.streaming=!1,p(w);let I=M(b);I&&x.byCall.delete(I)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,w={id:T,role:"assistant",content:(cs=b.reflection)!=null?cs:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(js=b.reflection)!=null?js:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(w)}else if(De==="agent_complete"){he&&(he.status=b.success?"complete":"error",he.completedAt=Y(b.completedAt),he.stopReason=b.stopReason);let T=y;T&&(T.streaming=!1,p(T)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(tr=(jn=b.error)==null?void 0:jn.message)!=null?tr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let T=(ft=b.approvalId)!=null?ft:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(nr=he==null?void 0:he.agentId)!=null?nr:"virtual",executionId:(Lr=(rr=b.executionId)!=null?rr:he==null?void 0:he.executionId)!=null?Lr:"",toolName:(Pr=b.toolName)!=null?Pr:"",toolType:b.toolType,description:(Wr=b.description)!=null?Wr:`Execute ${(Ir=b.toolName)!=null?Ir:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(Vt=b.approvalId)!=null?Vt:`approval-${c()}`,w={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Zt=he==null?void 0:he.agentId)!=null?Zt:"virtual",executionId:(Re=(En=b.executionId)!=null?En:he==null?void 0:he.executionId)!=null?Re:"",toolName:(Rr=b.toolName)!=null?Rr:"",toolType:b.toolType,description:(ln=b.description)!=null?ln:`Execute ${(Vn=b.toolName)!=null?Vn:"tool"}`,parameters:b.parameters}};p(w)}else if(De==="agent_approval_complete"){let T=b.approvalId;if(T){let I={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(ds=b.decision)!=null?ds:"approved",agentId:(sr=he==null?void 0:he.agentId)!=null?sr:"virtual",executionId:(qn=(or=b.executionId)!=null?or:he==null?void 0:he.executionId)!=null?qn:"",toolName:(Hn=b.toolName)!=null?Hn:"",description:(ps=b.description)!=null?ps:"",resolvedAt:Date.now()}};p(I)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let T=b.artifactType,w=String(b.id),I=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:w,artifactType:T,title:I,component:typeof b.component=="string"?b.component:void 0}),Le.set(w,{markdown:"",title:I}),!pe.has(w)){pe.add(w);let ae={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:I,artifactType:T,status:"streaming"}})};J.set(w,ae),p(ae)}}else if(De==="artifact_delta"){let T=String(b.id),w=typeof b.delta=="string"?b.delta:String((us=b.delta)!=null?us:"");t({type:"artifact_delta",id:T,artDelta:w});let I=Le.get(T);I&&(I.markdown+=w)}else if(De==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let w=J.get(T);if(w){w.streaming=!1;try{let I=JSON.parse((cn=w.rawContent)!=null?cn:"{}");if(I.props){I.props.status="complete";let ae=Le.get(T);ae!=null&&ae.markdown&&(I.props.markdown=ae.markdown)}w.rawContent=JSON.stringify(I)}catch{}Le.delete(T),p(w),J.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let w=String((Un=T.id)!=null?Un:`msg-${c()}`),I=T.role,Se={id:w,role:I==="user"?"user":I==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let nt=JSON.parse(Se.rawContent),kt=(gs=nt==null?void 0:nt.props)==null?void 0:gs.artifactId;typeof kt=="string"&&pe.add(kt)}catch{}y=null,m.current=null,j.delete(w),ce.delete(w)}else De==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function wc(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function jr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function cr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var ws="[Image]";function Sc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Ac(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function Ec(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function Tc(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Gs(e){return{type:"text",text:e}}function Mc(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function kc(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;n({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Lc(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Yi=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Pc=["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"],Mn=[...Yi,...Pc];function Ic(e){return Yi.includes(e)||e.startsWith("image/")}function Ss(e){return Ic(e.type)}async function Xi(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ss(e)?n({type:"image",image:o,mimeType:e.type,alt:e.name}):n({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Gi(e,n=Mn,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Wc(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Zi(e,n){let t=Wc(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var As=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),o=this.pcmToFloat32(t),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),o=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let s=0;s<t;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var Es=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,o,s){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let g=0;g<a.length;g++)i+=a[g]*a[g];let d=Math.sqrt(i/a.length);(r==="silence"?d<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Vr=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Es;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.location.protocol==="https:"?"wss:":"ws:",a=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${s}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((y,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=x=>{C||(C=!0,clearTimeout(E),m(new Error(x)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),y())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+g+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let k=x.code!==1006?` (code ${x.code})`:"";v("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(o=>o({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(o=>o("speaking")),this.playAudio(n.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(n.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new As(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,o;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(t=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(y=>y("processing")),this.processingStartCallbacks.forEach(y=>y());let g=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:g});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var s,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(s=this.config)==null?void 0:s.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),o=this.getFormatFromMimeType(n.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];t(a)},o.onerror=r,o.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);let o=n.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Kn=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function dr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Vr(e.runtype);case"browser":if(!Kn.isSupported())throw new Error("Browser speech recognition not supported");return new Kn(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Zs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return dr({type:"runtype",runtype:e.runtype});if(Kn.isSupported())return dr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(e){try{return Zs(e),!0}catch{return!1}}var qr=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,o,s,a,i,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.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:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(o=n.message.agentMetadata.iteration)!=null?o:0,maxTurns: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,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(o=>{var s;return{...o,sequence:(s=o.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new lr(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"}isVoiceSupported(){var n;return Ts((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,o;try{let s=n||this.getVoiceConfigFromConfig();if(!s)throw new Error("Voice configuration not provided");this.voiceProvider=dr(s);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(o=a.processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var g,p,y,m,C,v;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((g=c.transcript)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((y=c.text)!=null&&y.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var g,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(g=this.callbacks).onVoiceStatusChanged)==null||p.call(g,c)}),this.voiceProvider.connect()}catch(s){console.error("Failed to setup voice:",s)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,g;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((o=n.runtype)==null?void 0:o.clientToken)||"",host:(s=n.runtype)==null?void 0:s.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(g=n.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}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,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new lr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:g}=n,y={id:a!=null?a:t==="user"?jr():t==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...g!==void 0&&{voiceProcessing:g}};return this.upsertMessage(y),y}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 t=[];for(let r of n){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:o==="user"?jr():o==="assistant"?cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(n,t){var c,g,p,y,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let o=jr(),s=cr(),a={id:o,role:"user",content:r||ws,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){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,v||(C instanceof Error?(p=(g=this.callbacks).onError)==null||p.call(g,C):(m=(y=this.callbacks).onError)==null||m.call(y,new Error(String(C))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let n=cr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let g={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(g),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(n,t){var o,s,a;if(this.streaming)return;(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var d,c,g;let r=`approval-${n.id}`,o={...n,status:t,resolvedAt:Date.now()},s={id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:o};this.upsertMessage(s);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let y=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}y=p.body}else p instanceof ReadableStream&&(y=p);y?await this.connectStream(y):t==="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(p){(g=(c=this.callbacks).onError)==null||g.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var o;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(o=n.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let o=this.artifacts.get(n.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...n.props},n.component&&(o.component=n.component));break}case"artifact_complete":{let o=this.artifacts.get(n.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.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){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=r.content;o.trim()&&this.speak(o,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(n),s=r.getVoices();if(t.voice){let a=s.find(i=>i.name===t.voice);a&&(o.voice=a)}else s.length>0&&(o.voice=t.pickVoice?t.pickVoice(s):e.pickBestVoice(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),setTimeout(()=>r.speak(o),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let s=n.find(a=>a.name===o);if(s)return s}return(r=n.find(o=>o.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>s===r?{...o,...t}: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((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var f=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},bn=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import*as Rc from"lucide";var ue=(e,n=24,t="currentColor",r=2)=>{try{let o=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),s=Rc[o];return s?Hc(s,n,t,r):(console.warn(`Lucide icon "${e}" not found (tried "${o}"). Available icons: https://lucide.dev/icons`),null)}catch(o){return console.warn(`Failed to render Lucide icon "${e}":`,o),null}};function Hc(e,n,t,r){if(!e||!Array.isArray(e))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",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(Array.isArray(s)&&s.length>=2){let a=s[0],i=s[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),o.appendChild(d)}}}),o}var Ms={allowedTypes:Mn,maxFileSize:10*1024*1024,maxFiles:4};function Bc(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function $c(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-json":"file"}var pr=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ms.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ms.maxFileSize,maxFiles:(o=n.maxFiles)!=null?o:Ms.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:Ms.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 t,r,o,s,a,i,d;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=Gi(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(o=g.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,p);continue}try{let p=await Xi(c),y=Ss(c)?URL.createObjectURL(c):null,m={id:Bc(),file:c,previewUrl:y,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var s,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${n}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Ss(n.file),r=f("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=f("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=f("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=$c(n.file.type),d=ue(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=f("span");c.textContent=Zi(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=f("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-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="var(--persona-palette-colors-black-alpha-60, 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=ue("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(n.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Qi={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},el={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},tl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}}};function nl(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?nl(e,r):r}function Qs(e){let n={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=nl(e,a);d!==void 0&&(n[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function rl(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function sl(e,n){let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=sl(s,o):t[r]=o}return t}function Fc(e,n){return n?sl(e,n):e}function Ur(e,n={}){var o,s,a,i,d,c,g,p,y,m,C,v,E;let t={palette:Qi,semantic:el,components:tl},r={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(y=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:y.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Fc(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let x=rl(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let x of n.plugins)r=x.transform(r);return r}function eo(e){var d,c,g,p,y,m,C,v,E,x,k,U,M,O,S,N,Q,K,re,J,pe,Le,Ye,fe,ee,Y,V,j,ce,he,gt,lt,mt,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H;let n=Qs(e),t={};for(let[Z,z]of Object.entries(n)){let Pe=Z.replace(/\./g,"-");t[`--persona-${Pe}`]=z.value}t["--persona-primary"]=(d=t["--persona-semantic-colors-primary"])!=null?d:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(c=t["--persona-semantic-colors-secondary"])!=null?c:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(g=t["--persona-semantic-colors-accent"])!=null?g:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(p=t["--persona-semantic-colors-surface"])!=null?p:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(y=t["--persona-semantic-colors-background"])!=null?y:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(m=t["--persona-semantic-colors-container"])!=null?m:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(C=t["--persona-semantic-colors-text"])!=null?C:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(v=t["--persona-semantic-colors-text-muted"])!=null?v:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(E=t["--persona-semantic-colors-text-inverse"])!=null?E:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(x=t["--persona-semantic-colors-border"])!=null?x:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(k=t["--persona-semantic-colors-divider"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(U=t["--persona-components-voice-recording-indicator"])!=null?U:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(M=t["--persona-components-voice-recording-background"])!=null?M:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(S=t["--persona-components-voice-speaking-icon"])!=null?S:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(N=t["--persona-components-approval-requested-background"])!=null?N:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(Q=t["--persona-components-approval-requested-border"])!=null?Q:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(K=t["--persona-components-approval-requested-text"])!=null?K:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(re=t["--persona-components-approval-approve-background"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(J=t["--persona-components-approval-deny-background"])!=null?J:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(pe=t["--persona-components-attachment-image-background"])!=null?pe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Le=t["--persona-components-attachment-image-border"])!=null?Le:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(Ye=t["--persona-semantic-typography-fontFamily"])!=null?Ye:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(fe=t["--persona-semantic-typography-fontSize"])!=null?fe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ee=t["--persona-semantic-typography-fontWeight"])!=null?ee:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Y=t["--persona-semantic-typography-lineHeight"])!=null?Y:t["--persona-palette-typography-lineHeight-normal"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(j=t["--persona-palette-radius-md"])!=null?j:"0.375rem",t["--persona-radius-lg"]=(ce=t["--persona-palette-radius-lg"])!=null?ce:"0.5rem",t["--persona-radius-xl"]=(he=t["--persona-palette-radius-xl"])!=null?he:"0.75rem",t["--persona-launcher-radius"]=(lt=(gt=t["--persona-components-launcher-borderRadius"])!=null?gt:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-button-radius"]=(It=(mt=t["--persona-components-button-primary-borderRadius"])!=null?mt:t["--persona-palette-radius-full"])!=null?It:"9999px",t["--persona-panel-radius"]=(se=(le=t["--persona-components-panel-borderRadius"])!=null?le:t["--persona-radius-xl"])!=null?se:"0.75rem",t["--persona-input-radius"]=(ne=(q=t["--persona-components-input-borderRadius"])!=null?q:t["--persona-radius-lg"])!=null?ne:"0.5rem",t["--persona-message-user-radius"]=(Ee=(oe=t["--persona-components-message-user-borderRadius"])!=null?oe:t["--persona-radius-lg"])!=null?Ee:"0.5rem",t["--persona-message-assistant-radius"]=(te=(Ke=t["--persona-components-message-assistant-borderRadius"])!=null?Ke:t["--persona-radius-lg"])!=null?te:"0.5rem",t["--persona-header-bg"]=(X=t["--persona-components-header-background"])!=null?X:t["--persona-surface"],t["--persona-header-border"]=(He=t["--persona-components-header-border"])!=null?He:t["--persona-divider"],t["--persona-message-user-bg"]=(Ve=t["--persona-components-message-user-background"])!=null?Ve:t["--persona-accent"],t["--persona-message-user-text"]=(et=t["--persona-components-message-user-text"])!=null?et:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(jt=t["--persona-components-message-user-shadow"])!=null?jt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Dt=t["--persona-components-message-assistant-background"])!=null?Dt:t["--persona-surface"],t["--persona-message-assistant-text"]=(ie=t["--persona-components-message-assistant-text"])!=null?ie:t["--persona-text"],t["--persona-message-assistant-border"]=(Ue=t["--persona-components-message-assistant-border"])!=null?Ue:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Te=t["--persona-components-message-assistant-shadow"])!=null?Te:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(tt=t["--persona-components-toolBubble-shadow"])!=null?tt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(_e=t["--persona-components-reasoningBubble-shadow"])!=null?_e:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Xe=t["--persona-components-composer-shadow"])!=null?Xe:"none",t["--persona-md-inline-code-bg"]=(Wt=t["--persona-components-markdown-inlineCode-background"])!=null?Wt:t["--persona-container"],t["--persona-md-inline-code-color"]=(Rt=t["--persona-components-markdown-inlineCode-foreground"])!=null?Rt:t["--persona-text"],t["--persona-md-link-color"]=(H=(Mt=t["--persona-components-markdown-link-foreground"])!=null?Mt:t["--persona-accent"])!=null?H:"#3b82f6";let r=t["--persona-components-markdown-heading-h1-fontSize"];r&&(t["--persona-md-h1-size"]=r);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let s=t["--persona-components-markdown-heading-h2-fontSize"];s&&(t["--persona-md-h2-size"]=s);let a=t["--persona-components-markdown-heading-h2-fontWeight"];a&&(t["--persona-md-h2-weight"]=a);let i=t["--persona-components-markdown-prose-fontFamily"];return i&&i!=="inherit"&&(t["--persona-md-prose-font-family"]=i),t}var to={primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.accent.600",surface:"palette.colors.gray.50",muted:"palette.colors.gray.500",container:"palette.colors.gray.100",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",messageBorder:"palette.colors.gray.200",inputBackground:"palette.colors.gray.50",callToAction:"palette.colors.gray.900",callToActionBackground:"palette.colors.gray.50",sendButtonBackgroundColor:"semantic.colors.primary",sendButtonTextColor:"semantic.colors.textInverse",sendButtonBorderColor:"semantic.colors.primary",closeButtonColor:"palette.colors.gray.500",closeButtonBackgroundColor:"transparent",clearChatIconColor:"palette.colors.gray.500",clearChatBackgroundColor:"transparent",micIconColor:"palette.colors.gray.900",micBackgroundColor:"transparent",recordingIconColor:"palette.colors.white",recordingBackgroundColor:"palette.colors.error.500",tooltipBackground:"palette.colors.gray.900",tooltipForeground:"palette.colors.white"},ol={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function no(e,n={}){if(!e)return{};let t={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,o]of Object.entries(e))if(o)if(r in to){let s=to[r],[a,i,d,c]=s.split(".");if(a==="palette"&&i==="colors"){let g=d;t.palette.colors[g]&&(t.palette.colors[g][c||"500"]=o)}else if(a==="semantic"){let g=s.replace("semantic.colors.","").split(".");g.length===1?t.semantic.colors[g[0]]=o:t.semantic.colors[g[0]]={...t.semantic.colors[g[0]],[g[1]]:o}}}else if(r in ol){t.palette.radius||(t.palette.radius={});let s=r.replace("radius","").toLowerCase();t.palette.radius[s||"md"]=o}else r==="inputFontFamily"?(t.palette.typography||(t.palette.typography={fontFamily:{}}),t.palette.typography.fontFamily={sans:o==="sans-serif"?"system-ui, sans-serif":void 0,serif:o==="serif"?"Georgia, serif":void 0,mono:o==="mono"?"monospace":void 0}):r==="inputFontWeight"?(t.palette.typography||(t.palette.typography={fontWeight:{}}),t.palette.typography.fontWeight={normal:o}):r==="panelBorder"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.border=o):r==="panelShadow"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.shadow=o):r==="panelBorderRadius"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.borderRadius=o):r==="messageUserShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.user||(t.components.message.user={}),t.components.message.user.shadow=o):r==="messageAssistantShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.assistant||(t.components.message.assistant={}),t.components.message.assistant.shadow=o):r==="toolBubbleShadow"?(t.components||(t.components={}),t.components.toolBubble||(t.components.toolBubble={}),t.components.toolBubble.shadow=o):r==="reasoningBubbleShadow"?(t.components||(t.components={}),t.components.reasoningBubble||(t.components.reasoningBubble={}),t.components.reasoningBubble.shadow=o):r==="composerShadow"&&(t.components||(t.components={}),t.components.composer||(t.components.composer={}),t.components.composer.shadow=o);return n.warn!==!1&&console.warn("[Persona Widget] v1 theme configuration detected. v1 themes are deprecated in v2.0.0. Please migrate to the new semantic token system. See https://persona.sh/docs/v2-migration for guidance."),t}function Nc(e){let n=[],t=e;if(!t)return{valid:!0,warnings:[]};let r=new Set(["panelBorder","panelShadow","panelBorderRadius","messageUserShadow","messageAssistantShadow","toolBubbleShadow","reasoningBubbleShadow","composerShadow"]),o=Object.keys(t).filter(s=>!(s in to||s in ol||s==="inputFontFamily"||s==="inputFontWeight"||s.startsWith("panel")||r.has(s)));return o.length>0&&n.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${o.join(", ")}`),{valid:!0,warnings:n}}var Oc={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},ro=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),so=(e,n)=>{if(!e)return n;if(!n)return e;let t={...e};for(let[r,o]of Object.entries(n)){let s=t[r];ro(s)&&ro(o)?t[r]=so(s,o):t[r]=o}return t},Dc=e=>ro(e)&&("palette"in e||"semantic"in e||"components"in e),al=e=>{if(!e)return;let n=no(e,{warn:!1});return Dc(e)?so(n,e):n},ks=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},_c=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":ks()},il=e=>_c(e),jc=e=>Ur(e),Vc=e=>{var t;let n=Ur(void 0,{validate:!1});return Ur({...e,palette:{...n.palette,colors:{...Oc.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},ll=e=>{let n=il(e),t=al(e==null?void 0:e.theme),r=al(e==null?void 0:e.darkTheme);return n==="dark"?Vc(so(t,r)):jc(t)},qc=e=>eo(e),Yn=(e,n)=>{var s;let t=ll(n),r=qc(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let o=(s=n==null?void 0:n.toolCall)==null?void 0:s.shadow;o!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",o.trim()===""?"none":o)},oo=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ks())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ks());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as Uc}from"idiomorph";var cl=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Uc.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){if(o instanceof HTMLElement&&r&&(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-animation")))return!1}}})};function dl(e,n){var t,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=e.llmContent)==null?void 0:c.length)!=null?g:0,(y=(p=e.approval)==null?void 0:p.status)!=null?y:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(E=(v=e.reasoning)==null?void 0:v.chunks)==null?void 0:E.length)!=null?x:0,(U=(k=e.contentParts)==null?void 0:k.length)!=null?U:0,n].join("\0")}function pl(){return new Map}function ul(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function gl(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function ml(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}var _t={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var zc={side:"right",width:"420px",collapsedWidth:"72px"},Ut=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},zr=e=>{var n,t;return{...zc,...(t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock)!=null?t:{}}};var dn={"bottom-right":"persona-bottom-6 persona-right-6","bottom-left":"persona-bottom-6 persona-left-6","top-right":"persona-top-6 persona-right-6","top-left":"persona-top-6 persona-left-6"};var Jr=(e,n)=>{let t=f("button");t.type="button",t.innerHTML=`
|
|
8
8
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
9
9
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
10
|
<span class="persona-flex persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,12 +12,12 @@ import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let t=
|
|
|
12
12
|
<span class="persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
13
13
|
</span>
|
|
14
14
|
<span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
|
|
15
|
-
`,n.addEventListener("click",t);let r=s=>{var U,M,O,S,N,Z,K,re,z,pe,Le,Ye;let a=(U=s.launcher)!=null?U:{},i=Ut(s),d=n.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=n.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(O=a.subtitle)!=null?O:"Get answers fast");let g=n.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=n.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let fe=(S=a.agentIconSize)!=null?S:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let Q=parseFloat(fe)||24,Y=ue(a.agentIconName,Q*.6,"var(--persona-text-inverse, #ffffff)",2);Y?(p.appendChild(Y),p.style.display=""):(p.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(Z=a.agentIconText)!=null?Z:"\u{1F4AC}",p.style.display="")}let y=n.querySelector("[data-role='launcher-image']");if(y){let fe=(K=a.agentIconSize)!=null?K:"40px";y.style.height=fe,y.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let m=n.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let fe=(re=a.callToActionIconSize)!=null?re:"32px";m.style.height=fe,m.style.width=fe,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let Q=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Q=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Y=parseFloat(fe)||24,V=Math.max(Y-Q,8),j=ue(a.callToActionIconName,V,"currentColor",2);j?m.appendChild(j):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(pe=a.callToActionIconText)!=null?pe:"\u2197"}let C=a.position&&dn[a.position]?dn[a.position]:dn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${v} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";if(n.style.border=(Le=a.border)!=null?Le:x,n.style.boxShadow=(Ye=a.shadow)!=null?Ye:k,i){let fe=zr(s);n.style.width=`calc(${fe.collapsedWidth} - 16px)`,n.style.minWidth="40px",n.style.maxWidth=`calc(${fe.collapsedWidth} - 16px)`,n.style.justifyContent="center",n.style.padding="12px 0"}else n.style.width="",n.style.minWidth="",n.style.maxWidth="",n.style.justifyContent="",n.style.padding=""},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var $n=e=>{var re,z,pe,Le,Ye,fe,Q,Y,V,j,ce,he,gt,lt,mt,Pt,le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue;let{config:t,showClose:n=!0}=e,r=f("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomWidth="1px",r.style.borderBottomStyle="solid",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))";let o=(re=t==null?void 0:t.launcher)!=null?re:{},s=(z=o.headerIconSize)!=null?z:"48px",a=(pe=o.closeButtonSize)!=null?pe:"32px",i=(Le=o.closeButtonPlacement)!=null?Le:"inline",d=(Ye=o.headerIconHidden)!=null?Ye:!1,c=o.headerIconName,g=f("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-bg-persona-primary persona-text-white persona-text-xl");if(g.style.height=s,g.style.width=s,!d)if(c){let Te=parseFloat(s)||24,tt=ue(c,Te*.6,"var(--persona-text-inverse, #ffffff)",1);tt?g.replaceChildren(tt):g.textContent=(Q=(fe=t==null?void 0:t.launcher)==null?void 0:fe.agentIconText)!=null?Q:"\u{1F4AC}"}else if((Y=t==null?void 0:t.launcher)!=null&&Y.iconUrl){let Te=f("img");Te.src=t.launcher.iconUrl,Te.alt="",Te.className="persona-rounded-xl persona-object-cover",Te.style.height=s,Te.style.width=s,g.replaceChildren(Te)}else g.textContent=(j=(V=t==null?void 0:t.launcher)==null?void 0:V.agentIconText)!=null?j:"\u{1F4AC}";let p=f("div","persona-flex persona-flex-col"),y=f("span","persona-text-base persona-font-semibold");y.textContent=(he=(ce=t==null?void 0:t.launcher)==null?void 0:ce.title)!=null?he:"Chat Assistant";let m=f("span","persona-text-xs persona-text-persona-muted");m.textContent=(lt=(gt=t==null?void 0:t.launcher)==null?void 0:gt.subtitle)!=null?lt:"Here to help you get answers fast",p.append(y,m),d?r.append(p):r.append(g,p);let C=(mt=o.clearChat)!=null?mt:{},v=(Pt=C.enabled)!=null?Pt:!0,E=(le=C.placement)!=null?le:"inline",x=null,k=null;if(v){let Te=(se=C.size)!=null?se:"32px",tt=(q=C.iconName)!=null?q:"refresh-cw",_e=(ne=C.iconColor)!=null?ne:"",Xe=(oe=C.backgroundColor)!=null?oe:"",$t=(Ee=C.borderWidth)!=null?Ee:"",Ft=(Ke=C.borderColor)!=null?Ke:"",It=(ee=C.borderRadius)!=null?ee:"",H=(X=C.paddingX)!=null?X:"",te=(He=C.paddingY)!=null?He:"",J=(Ve=C.tooltipText)!=null?Ve:"Clear chat",We=(et=C.showTooltip)!=null?et:!0;k=f("div",E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),x=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),x.style.height=Te,x.style.width=Te,x.type="button",x.setAttribute("aria-label",J);let Ce=ue(tt,"20px",_e||"",1);if(Ce&&x.appendChild(Ce),_e&&(x.style.color=_e,x.classList.remove("persona-text-persona-muted")),Xe&&(x.style.backgroundColor=Xe,x.classList.remove("hover:persona-bg-gray-100")),$t||Ft){let Pe=$t||"0px",Be=Ft||"transparent";x.style.border=`${Pe} solid ${Be}`,x.classList.remove("persona-border-none")}if(It&&(x.style.borderRadius=It,x.classList.remove("persona-rounded-full")),H?(x.style.paddingLeft=H,x.style.paddingRight=H):(x.style.paddingLeft="",x.style.paddingRight=""),te?(x.style.paddingTop=te,x.style.paddingBottom=te):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),We&&J&&x&&k){let Pe=null,Be=()=>{if(Pe||!x)return;let ye=x.ownerDocument,be=ye.body;if(!be)return;Pe=bn(ye,"div","persona-clear-chat-tooltip"),Pe.textContent=J;let $e=bn(ye,"div");$e.className="persona-clear-chat-tooltip-arrow",Pe.appendChild($e);let de=x.getBoundingClientRect();Pe.style.position="fixed",Pe.style.left=`${de.left+de.width/2}px`,Pe.style.top=`${de.top-8}px`,Pe.style.transform="translate(-50%, -100%)",be.appendChild(Pe)},ut=()=>{Pe&&Pe.parentNode&&(Pe.parentNode.removeChild(Pe),Pe=null)};k.addEventListener("mouseenter",Be),k.addEventListener("mouseleave",ut),x.addEventListener("focus",Be),x.addEventListener("blur",ut),k._cleanupTooltip=()=>{ut(),k&&(k.removeEventListener("mouseenter",Be),k.removeEventListener("mouseleave",ut)),x&&(x.removeEventListener("focus",Be),x.removeEventListener("blur",ut))}}E==="inline"&&r.appendChild(k)}let U=f("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&E==="inline"?"":"persona-ml-auto"),M=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=a,M.style.width=a,M.type="button";let O=(jt=o.closeButtonTooltipText)!=null?jt:"Close chat",S=(Dt=o.closeButtonShowTooltip)!=null?Dt:!0;M.setAttribute("aria-label",O),M.style.display=n?"":"none";let N=(ie=o.closeButtonIconName)!=null?ie:"x",Z=(Ue=o.closeButtonIconText)!=null?Ue:"\xD7",K=ue(N,"20px",o.closeButtonColor||"",1);if(K?M.appendChild(K):M.textContent=Z,o.closeButtonColor?(M.style.color=o.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),o.closeButtonBackgroundColor?(M.style.backgroundColor=o.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Te=o.closeButtonBorderWidth||"0px",tt=o.closeButtonBorderColor||"transparent";M.style.border=`${Te} solid ${tt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(o.closeButtonBorderRadius?(M.style.borderRadius=o.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),o.closeButtonPaddingX?(M.style.paddingLeft=o.closeButtonPaddingX,M.style.paddingRight=o.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),o.closeButtonPaddingY?(M.style.paddingTop=o.closeButtonPaddingY,M.style.paddingBottom=o.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),U.appendChild(M),S&&O){let Te=null,tt=()=>{if(Te)return;let Xe=M.ownerDocument,$t=Xe.body;if(!$t)return;Te=bn(Xe,"div","persona-clear-chat-tooltip"),Te.textContent=O;let Ft=bn(Xe,"div");Ft.className="persona-clear-chat-tooltip-arrow",Te.appendChild(Ft);let It=M.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${It.left+It.width/2}px`,Te.style.top=`${It.top-8}px`,Te.style.transform="translate(-50%, -100%)",$t.appendChild(Te)},_e=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};U.addEventListener("mouseenter",tt),U.addEventListener("mouseleave",_e),M.addEventListener("focus",tt),M.addEventListener("blur",_e),U._cleanupTooltip=()=>{_e(),U.removeEventListener("mouseenter",tt),U.removeEventListener("mouseleave",_e),M.removeEventListener("focus",tt),M.removeEventListener("blur",_e)}}return i!=="top-right"&&r.appendChild(U),{header:r,iconHolder:g,headerTitle:y,headerSubtitle:m,closeButton:M,closeButtonWrapper:U,clearChatButton:x,clearChatButtonWrapper:k}},ur=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};var fl=e=>$n({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat});function Jc(e,t,n){var r,o;if(t!=null&&t.length)for(let s of t){let a=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(a.type="button",a.setAttribute("aria-label",(o=(r=s.ariaLabel)!=null?r:s.label)!=null?o:s.id),s.icon){let i=ue(s.icon,14,"currentColor",2);i&&a.appendChild(i)}else s.label&&(a.textContent=s.label);a.addEventListener("click",()=>n==null?void 0:n(s.id)),e.appendChild(a)}}var hl=e=>{var x,k,U,M,O;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(x=t==null?void 0:t.launcher)!=null?x:{},i=f("div","persona-flex persona-items-center persona-justify-between persona-bg-persona-surface persona-px-6 persona-py-4 persona-border-b-persona-divider"),d=f("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=f("span","persona-text-base persona-font-semibold persona-truncate");c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),Jc(d,o==null?void 0:o.trailingActions,(U=o==null?void 0:o.onAction)!=null?U:s),i.appendChild(d);let g=(M=a.closeButtonSize)!=null?M:"32px",p=f("div",""),y=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");y.style.height=g,y.style.width=g,y.type="button",y.setAttribute("aria-label","Close chat"),y.style.display=n?"":"none";let m=(O=a.closeButtonIconName)!=null?O:"x",C=ue(m,"20px",a.closeButtonColor||"",2);C?y.appendChild(C):y.textContent="\xD7",r&&y.addEventListener("click",r),p.appendChild(y),i.appendChild(p);let v=f("div");v.style.display="none";let E=f("span");return E.style.display="none",{header:i,iconHolder:v,headerTitle:c,headerSubtitle:E,closeButton:y,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ao={default:fl,minimal:hl},yl=e=>{var t;return(t=ao[e])!=null?t:ao.default},Kr=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),g=f("div");g.style.display="none";let p=f("span"),y=f("span"),m=f("button");m.style.display="none";let C=f("div");return C.style.display="none",{header:c,iconHolder:g,headerTitle:p,headerSubtitle:y,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=yl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Kc=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Yr=e=>{var le,se,q,ne,oe,Ee,Ke,ee,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,$t,Ft,It,H,te,J,We,Ce,Pe,Be,ut;let{config:t}=e,n=f("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4"),r=f("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),o=f("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let s=f("textarea");s.setAttribute("data-persona-composer-input",""),s.placeholder=(se=(le=t==null?void 0:t.copy)==null?void 0:le.inputPlaceholder)!=null?se:"Type your message\u2026",s.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",s.rows=1;let a=(ne=(q=t==null?void 0:t.theme)==null?void 0:q.inputFontFamily)!=null?ne:"sans-serif",i=(Ee=(oe=t==null?void 0:t.theme)==null?void 0:oe.inputFontWeight)!=null?Ee:"400";s.style.fontFamily=Kc(a),s.style.fontWeight=i;let g=3*20;s.style.maxHeight=`${g}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let ye=Math.min(s.scrollHeight,g);s.style.height=`${ye}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let y=(Ke=t==null?void 0:t.sendButton)!=null?Ke:{},m=(ee=y.useIcon)!=null?ee:!1,C=(X=y.iconText)!=null?X:"\u2191",v=y.iconName,E=(He=y.tooltipText)!=null?He:"Send message",x=(Ve=y.showTooltip)!=null?Ve:!1,k=(et=y.size)!=null?et:"40px",U=y.backgroundColor,M=y.textColor,O=f("div","persona-send-button-wrapper"),S=f("button",m?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(S.type="submit",S.setAttribute("data-persona-composer-submit",""),m){if(S.style.width=k,S.style.height=k,S.style.minWidth=k,S.style.minHeight=k,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",v){let ye=parseFloat(k)||24,be=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",$e=ue(v,ye,be,2);$e?(S.appendChild($e),S.style.color=be):(S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white"))}else S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white");U?S.style.backgroundColor=U:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Dt=(jt=t==null?void 0:t.copy)==null?void 0:jt.sendButtonLabel)!=null?Dt:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(y.borderWidth&&(S.style.borderWidth=y.borderWidth,S.style.borderStyle="solid"),y.borderColor&&(S.style.borderColor=y.borderColor),y.paddingX?(S.style.paddingLeft=y.paddingX,S.style.paddingRight=y.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),y.paddingY?(S.style.paddingTop=y.paddingY,S.style.paddingBottom=y.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),x&&E){let ye=f("div","persona-send-button-tooltip");ye.textContent=E,O.appendChild(ye)}O.appendChild(S);let N=(ie=t==null?void 0:t.voiceRecognition)!=null?ie:{},Z=N.enabled===!0,K=null,re=null,z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),pe=((Ue=N.provider)==null?void 0:Ue.type)==="runtype";if(Z&&(z||pe)){re=f("div","persona-send-button-wrapper"),K=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),K.type="button",K.setAttribute("data-persona-composer-mic",""),K.setAttribute("aria-label","Start voice recognition");let ye=(Te=N.iconName)!=null?Te:"mic",be=(tt=N.iconSize)!=null?tt:k,$e=parseFloat(be)||24,de=(_e=N.backgroundColor)!=null?_e:U,bt=(Xe=N.iconColor)!=null?Xe:M;K.style.width=be,K.style.height=be,K.style.minWidth=be,K.style.minHeight=be,K.style.fontSize="18px",K.style.lineHeight="1";let Gt=bt||"currentColor",pn=ue(ye,$e,Gt,1.5);pn?(K.appendChild(pn),K.style.color=Gt):(K.textContent="\u{1F3A4}",K.style.color=Gt),de?K.style.backgroundColor=de:K.classList.add("persona-bg-persona-primary"),bt?K.style.color=bt:!bt&&!M&&K.classList.add("persona-text-white"),N.borderWidth&&(K.style.borderWidth=N.borderWidth,K.style.borderStyle="solid"),N.borderColor&&(K.style.borderColor=N.borderColor),N.paddingX&&(K.style.paddingLeft=N.paddingX,K.style.paddingRight=N.paddingX),N.paddingY&&(K.style.paddingTop=N.paddingY,K.style.paddingBottom=N.paddingY),re.appendChild(K);let un=($t=N.tooltipText)!=null?$t:"Start voice recognition";if(((Ft=N.showTooltip)!=null?Ft:!1)&&un){let Ln=f("div","persona-send-button-tooltip");Ln.textContent=un,re.appendChild(Ln)}}let Ye=(It=t==null?void 0:t.attachments)!=null?It:{},fe=Ye.enabled===!0,Q=null,Y=null,V=null,j=null;if(fe){j=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),j.style.display="none",V=f("input"),V.type="file",V.accept=((H=Ye.allowedTypes)!=null?H:Mn).join(","),V.multiple=((te=Ye.maxFiles)!=null?te:4)>1,V.style.display="none",V.setAttribute("aria-label","Attach files"),Y=f("div","persona-send-button-wrapper"),Q=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),Q.type="button",Q.setAttribute("aria-label",(J=Ye.buttonTooltipText)!=null?J:"Attach file");let ye=(We=Ye.buttonIconName)!=null?We:"paperclip",be=k,$e=parseFloat(be)||40,de=Math.round($e*.6);Q.style.width=be,Q.style.height=be,Q.style.minWidth=be,Q.style.minHeight=be,Q.style.fontSize="18px",Q.style.lineHeight="1",Q.style.backgroundColor="transparent",Q.style.color="var(--persona-primary, #111827)",Q.style.border="none",Q.style.borderRadius="6px",Q.style.transition="background-color 0.15s ease",Q.addEventListener("mouseenter",()=>{Q.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),Q.addEventListener("mouseleave",()=>{Q.style.backgroundColor="transparent"});let bt=ue(ye,de,"currentColor",1.5);bt?Q.appendChild(bt):Q.textContent="\u{1F4CE}",Q.addEventListener("click",un=>{un.preventDefault(),V==null||V.click()}),Y.appendChild(Q);let Gt=(Ce=Ye.buttonTooltipText)!=null?Ce:"Attach file",pn=f("div","persona-send-button-tooltip");pn.textContent=Gt,Y.appendChild(pn)}o.addEventListener("click",ye=>{ye.target!==S&&ye.target!==O&&ye.target!==K&&ye.target!==re&&ye.target!==Q&&ye.target!==Y&&s.focus()}),j&&(j.style.gap="8px",o.append(j)),V&&o.append(V),o.append(s);let ce=f("div","persona-flex persona-items-center persona-justify-between persona-w-full"),he=f("div","persona-flex persona-items-center persona-gap-2");Y&&he.append(Y);let gt=f("div","persona-flex persona-items-center persona-gap-1");re&>.append(re),gt.append(O),ce.append(he,gt),o.append(ce);let lt=f("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");lt.setAttribute("data-persona-composer-status","");let mt=(Pe=t==null?void 0:t.statusIndicator)!=null?Pe:{},Pt=(Be=mt.visible)!=null?Be:!0;return lt.style.display=Pt?"":"none",lt.textContent=(ut=mt.idleText)!=null?ut:"Online",n.append(r,o,lt),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:S,sendButtonWrapper:O,micButton:K,micButtonWrapper:re,statusText:lt,attachmentButton:Q,attachmentButtonWrapper:Y,attachmentInput:V,attachmentPreviewsContainer:j,actionsRow:ce,leftActions:he,rightActions:gt}};var bl=e=>{var c,g,p,y,m,C,v;let t=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Ut(e)){let E=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return E.appendChild(x),{wrapper:E,panel:x}}if(!t){let E=f("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=f("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(y=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?y:"100%";return E.style.width=k,x.style.width="100%",E.appendChild(x),{wrapper:E,panel:x}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},o=r.position&&dn[r.position]?dn[r.position]:dn["bottom-right"],s=f("div",`persona-widget-wrapper persona-fixed ${o} persona-z-50 persona-transition`),a=f("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(v=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?v:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,s.appendChild(a),{wrapper:s,panel:a}},xl=(e,t=!0)=>{var v,E,x,k,U,M,O,S,N;let n=f("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border"),r=(v=e==null?void 0:e.layout)==null?void 0:v.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Kr(e,r,{showClose:t}):$n({config:e,showClose:t}),a=f("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container";let i=f("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm"),d=f("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let c=f("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(M=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",i.append(d,c);let g=f("div","persona-flex persona-flex-col persona-gap-3"),p=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((S=e==null?void 0:e.copy)==null?void 0:S.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Yr({config:e}),C=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;return o?ur(n,s,e):(s.header.style.display="none",ur(n,s,e)),n.append(a),C||(m.footer.style.display="none"),n.append(m.footer),{container:n,body:a,messagesWrapper:g,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle: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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Yc=320,Xc=320,Gc=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Zc=(e,t,n)=>{if(e.length===0)return null;try{let r=f("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var p;let c=f("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Yc}px`,c.style.maxHeight=`${Xc}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),c.src=i.image,r.appendChild(c)}),o===0?(a(),null):r}catch{return n==null||n(),null}},gr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="0ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},Cl=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:gr};if(t){let o=t(r);if(o!==null)return o}return gr()},Qc=(e,t)=>{let n=f("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=f("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},vl=(e,t)=>{let n=f("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return t.format?n.textContent=t.format(r):n.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),n},ed=(e,t="bubble")=>{let n=["vanilla-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},wl=(e,t,n)=>{var m,C,v,E,x,k;let r=(m=t.showCopy)!=null?m:!0,o=(C=t.showUpvote)!=null?C:!0,s=(v=t.showDownvote)!=null?v:!0;if(!r&&!o&&!s){let U=f("div");return U.style.display="none",U.id=`actions-${e.id}`,U.setAttribute("data-actions-for",e.id),U}let a=(E=t.visibility)!=null?E:"hover",i=(x=t.align)!=null?x:"right",d=(k=t.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=f("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let y=(U,M,O)=>{let S=document.createElement("button");S.className="persona-message-action-btn",S.setAttribute("aria-label",M),S.setAttribute("title",M),S.setAttribute("data-action",O);let N=ue(U,14,"currentColor",2);return N&&S.appendChild(N),S};return r&&p.appendChild(y("copy","Copy message","copy")),o&&p.appendChild(y("thumbs-up","Upvote","upvote")),s&&p.appendChild(y("thumbs-down","Downvote","downvote")),p},Xr=(e,t,n,r,o,s)=>{var re,z,pe,Le,Ye,fe,Q;let a=n!=null?n:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,g=(z=d==null?void 0:d.show)!=null?z:!1,p=(pe=c==null?void 0:c.show)!=null?pe:!1,y=(Le=d==null?void 0:d.position)!=null?Le:"left",m=(Ye=c==null?void 0:c.position)!=null?Ye:"below",C=ed(e.role,i),v=f("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Gc(e),x=(Q=(fe=e.content)==null?void 0:fe.trim())!=null?Q:"",U=E.length>0&&x===ws,M=document.createElement("div");M.classList.add("persona-message-content");let O=t({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),S=null;if(U?(S=document.createElement("div"),S.innerHTML=O,S.style.display="none",M.appendChild(S)):M.innerHTML=O,p&&m==="inline"&&e.createdAt){let Y=vl(e,c);Y.classList.add("persona-ml-2","persona-inline"),M.appendChild(Y)}if(E.length>0){let Y=Zc(E,!U&&!!x,()=>{U&&S&&(S.style.display="")});Y?v.appendChild(Y):U&&S&&(S.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let Y=vl(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Cl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Y&&v.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=wl(e,r,o);v.appendChild(Y)}if(!g||e.role==="system")return v;let Z=f("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=Qc(d,e.role);return y==="right"||y==="left"&&e.role==="user"?Z.append(v,K):Z.append(K,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Z},td=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Xr(e,t,n,r,o,s)};var mr=new Set,Sl=(e,t)=>{let n=mr.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t");if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let s=r.querySelector(".persona-ml-auto"),a=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=ue(n?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=n?"Hide":"Show"}o.style.display=n?"":"none"},io=e=>{let t=e.reasoning,n=f("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),!t)return n;let r=mr.has(e.id),o=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");o.type="button",o.setAttribute("aria-expanded",r?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=f("div","persona-flex persona-flex-col persona-text-left"),a=f("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",s.appendChild(a);let i=f("span","persona-text-xs persona-text-persona-primary");i.textContent=Ji(t),s.appendChild(i),t.status==="complete"?a.style.display="none":a.style.display="";let d=f("div","persona-flex persona-items-center"),g=ue(r?"chevron-up":"chevron-down",16,"currentColor",2);g?d.appendChild(g):d.textContent=r?"Hide":"Show";let p=f("div","persona-flex persona-items-center persona-ml-auto");p.append(d),o.append(s,p);let y=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");y.style.display=r?"":"none";let m=t.chunks.join(""),C=f("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),y.appendChild(C),(()=>{o.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=ue(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",y.style.display=r?"":"none"})(),n.append(o,y),n};var fr=new Set,Al=(e,t,n)=>{var c;let r=fr.has(e),o=(c=n==null?void 0:n.toolCall)!=null?c:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t");if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let i=s.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=o.toggleTextColor||o.headerTextColor||"currentColor",p=ue(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},lo=(e,t)=>{var v;let n=e.toolCall,r=(v=t==null?void 0:t.toolCall)!=null?v:{},o=f("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!n)return o;let s=fr.has(e.id),a=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",s?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(a.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(a.style.paddingLeft=r.headerPaddingX,a.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(a.style.paddingTop=r.headerPaddingY,a.style.paddingBottom=r.headerPaddingY);let i=f("div","persona-flex persona-flex-col persona-text-left"),d=f("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(d.style.color=r.headerTextColor),d.textContent=Ki(n),i.appendChild(d);let c=f("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=ue(s?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=s?"Hide":"Show";let y=f("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");y.append(c),a.append(i,y);let m=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=s?"":"none",r.contentBackgroundColor&&(m.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(m.style.color=r.contentTextColor),r.contentPaddingX&&(m.style.paddingLeft=r.contentPaddingX,m.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(m.style.paddingTop=r.contentPaddingY,m.style.paddingBottom=r.contentPaddingY),n.name){let E=f("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?E.style.color=r.contentTextColor:r.headerTextColor&&(E.style.color=r.headerTextColor),E.textContent=n.name,m.appendChild(E)}if(n.args!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Arguments";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=_r(n.args),E.append(x,k),m.appendChild(E)}if(n.chunks&&n.chunks.length){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Activity";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=n.chunks.join(`
|
|
16
|
-
`),E.append(x,k),m.appendChild(E)}if(n.status==="complete"&&n.result!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Result";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=_r(n.result),E.append(x,k),m.appendChild(E)}if(n.status==="complete"&&typeof n.duration=="number"){let E=f("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${n.duration}ms`,m.appendChild(E)}return(()=>{a.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=ue(s?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",m.style.display=s?"":"none"})(),o.append(a,m),o};var co=(e,t)=>{var v,E,x,k,U,M,O,S,N,Z,K,re;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=f("div",["persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!n)return s;let a=f("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=f("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",c=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=r==null?void 0:r.titleColor)!=null?x:"currentColor",g=ue(d,20,c,2);g&&i.appendChild(g);let p=f("div","persona-flex-1 persona-min-w-0"),y=f("div","persona-flex persona-items-center persona-gap-2"),m=f("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",y.appendChild(m),!o){let z=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",n.status),n.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):n.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):n.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),y.appendChild(z)}p.appendChild(y);let C=f("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=n.description,p.appendChild(C),n.parameters){let z=f("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(z.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(z.style.color=r.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=_r(n.parameters),p.appendChild(z)}if(o){let z=f("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let pe=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");pe.type="button",pe.style.backgroundColor=(U=r==null?void 0:r.approveButtonColor)!=null?U:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",pe.setAttribute("data-approval-action","approve");let Le=ue("shield-check",14,(O=r==null?void 0:r.approveButtonTextColor)!=null?O:"#ffffff",2);Le&&(Le.style.marginRight="4px",pe.appendChild(Le));let Ye=document.createTextNode((S=r==null?void 0:r.approveLabel)!=null?S:"Approve");pe.appendChild(Ye);let fe=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");fe.type="button",fe.style.backgroundColor=(N=r==null?void 0:r.denyButtonColor)!=null?N:"transparent",fe.style.color=(Z=r==null?void 0:r.denyButtonTextColor)!=null?Z:"var(--persona-feedback-error, #dc2626)",fe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,fe.setAttribute("data-approval-action","deny");let Q=ue("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);Q&&(Q.style.marginRight="4px",fe.appendChild(Q));let Y=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");fe.appendChild(Y),z.append(pe,fe),p.appendChild(z)}return a.append(i,p),s.appendChild(a),s};var El=e=>{let t=[];return{buttons:t,render:(r,o,s,a,i)=>{if(e.innerHTML="",t.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=o?o.isStreaming():!1,y=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let C=f("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=y(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),g.appendChild(C),t.push(C)}),e.appendChild(g)}}};var Gr=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Zr=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};function hr(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var nd={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},rd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sd=["flowName","stepName","reasoningText","text","name","tool","toolName"],od=100;function ad(e,t){let n={...nd,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return rd}function id(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function ld(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function cd(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function dd(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function pd(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function ud(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=f("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=f("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function po(e,t,n,r,o,s,a,i){var y;let d=o.has(e.id),c=f("div","persona-border-b persona-border-persona-divider persona-text-xs");hr(c,(y=r.classNames)==null?void 0:y.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var pe,Le;let m=f("div",""),C=f("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=f("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=ue(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let x=f("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(pe=r.timestampFormat)!=null?pe:"relative";x.textContent=k==="relative"?id(e.timestamp,n):ld(e.timestamp);let U=null;r.showSequenceNumbers!==!1&&(U=f("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),U.textContent=String(t+1));let M=ad(e.type,r.badgeColors),O=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");O.style.backgroundColor=M.bg,O.style.color=M.text,O.style.borderColor=M.text+"50",O.textContent=e.type;let S=(Le=r.descriptionFields)!=null?Le:sd,N=cd(e.payload,S),Z=null;N&&(Z=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Z.textContent=N);let K=f("div","persona-flex-1 persona-min-w-0"),re=f("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),z=ue("clipboard","12px","currentColor",1.5);return z&&re.appendChild(z),re.addEventListener("click",async Ye=>{Ye.stopPropagation(),await dd(pd(e)),re.innerHTML="";let fe=ue("check","12px","currentColor",1.5);fe&&re.appendChild(fe),setTimeout(()=>{re.innerHTML="";let Q=ue("clipboard","12px","currentColor",1.5);Q&&re.appendChild(Q)},1500)}),C.appendChild(v),C.appendChild(x),U&&C.appendChild(U),C.appendChild(O),Z&&C.appendChild(Z),C.appendChild(K),C.appendChild(re),m.appendChild(C),d&&m.appendChild(ud(e,a,i)),m}}function Tl(e){var c,g;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[]}=e,a=(g=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?g:{},i=s.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&o){let p=i.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>d().element,onClose:r});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,y=f("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hr(y,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},U=0,M=!1,O=0,S=0,N=!1,Z=null,K=!1,re=0,z=new Set,pe=new Map,Le="",Ye="",fe=null,Q,Y,V,j,ce;function he(){let te=f("div","persona-flex persona-flex-col persona-flex-shrink-0"),J=f("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");hr(J,p==null?void 0:p.headerBar);let We=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");We.textContent="Events",Q=f("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Q.textContent="0";let Ce=f("div","persona-flex-1");Y=f("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Pe=f("option","");Pe.value="",Pe.textContent="All events",Y.appendChild(Pe),V=f("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),V.type="button",V.title="Copy All";let ut=ue("clipboard-copy","12px","currentColor",1.5);ut&&V.appendChild(ut);let ye=f("span","persona-text-xs");ye.textContent="Copy All",V.appendChild(ye),J.appendChild(We),J.appendChild(Q),J.appendChild(Ce),J.appendChild(Y),J.appendChild(V);let be=f("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hr(be,p==null?void 0:p.searchBar);let $e=ue("search","14px","var(--persona-muted, #9ca3af)",1.5),de=f("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");$e&&de.appendChild($e),j=f("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),hr(j,p==null?void 0:p.searchInput),j.type="text",j.placeholder="Search event payloads...",ce=f("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ce.type="button",ce.style.display="none";let bt=ue("x","12px","currentColor",2);return bt&&ce.appendChild(bt),be.appendChild(de),be.appendChild(j),be.appendChild(ce),te.appendChild(J),te.appendChild(be),te}let gt,lt=s.find(te=>te.renderEventStreamToolbar);if(lt!=null&<.renderEventStreamToolbar&&o){let te=lt.renderEventStreamToolbar({config:o,defaultRenderer:()=>he(),eventCount:t.getSize(),filteredCount:0,onFilterChange:J=>{C=J,X(),et()},onSearchChange:J=>{v=J,X(),et()}});gt=te!=null?te:he()}else gt=he();let mt=f("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");mt.style.display="none";let Pt=f("div","persona-flex-1 persona-min-h-0 persona-relative"),le=f("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");le.style.height="100%";let se=f("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");hr(se,p==null?void 0:p.scrollIndicator),se.style.display="none";let q=ue("arrow-down","12px","currentColor",2);q&&se.appendChild(q);let ne=f("span","");se.appendChild(ne);let oe=f("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");oe.style.display="none",Pt.appendChild(le),Pt.appendChild(oe),Pt.appendChild(se),y.setAttribute("tabindex","0"),y.appendChild(gt),y.appendChild(mt),y.appendChild(Pt);function Ee(){let te=t.getAll(),J={};for(let ye of te)J[ye.type]=(J[ye.type]||0)+1;let We=Object.keys(J).sort(),Ce=We.length!==x.length||!We.every((ye,be)=>ye===x[be]),Pe=!Ce&&We.some(ye=>J[ye]!==k[ye]),Be=te.length!==Object.values(k).reduce((ye,be)=>ye+be,0);if(!Ce&&!Pe&&!Be||(x=We,k=J,!Y))return;let ut=Y.value;if(Y.options[0].textContent="All events",Ce){for(;Y.options.length>1;)Y.remove(1);for(let ye of We){let be=f("option","");be.value=ye,be.textContent=`${ye} (${J[ye]||0})`,Y.appendChild(be)}ut&&We.includes(ut)?Y.value=ut:ut&&(Y.value="",C="")}else for(let ye=1;ye<Y.options.length;ye++){let be=Y.options[ye];be.textContent=`${be.value} (${J[be.value]||0})`}}function Ke(){let te=t.getAll();if(C&&(te=te.filter(J=>J.type===C)),v){let J=v.toLowerCase();te=te.filter(We=>We.type.toLowerCase().includes(J)||We.payload.toLowerCase().includes(J))}return te}function ee(){return C!==""||v!==""}function X(){U=0,O=0,M=!1,se.style.display="none"}function He(te){z.has(te)?z.delete(te):z.add(te),fe=te;let J=le.scrollTop,We=M;K=!0,M=!0,et(),le.scrollTop=J,M=We,K=!1}function Ve(){return le.scrollHeight-le.scrollTop-le.clientHeight<=50}function et(){S=Date.now(),N=!1,Ee();let te=t.getEvictedCount();te>0?(mt.textContent=`${te.toLocaleString()} older events truncated`,mt.style.display=""):mt.style.display="none",m=Ke();let J=m.length,We=t.getSize()>0;Q&&(Q.textContent=String(t.getSize())),J===0&&We&&ee()?(oe.textContent=v?`No events matching '${v}'`:"No events matching filter",oe.style.display="",le.style.display="none"):(oe.style.display="none",le.style.display=""),V&&(V.title=ee()?`Copy Filtered (${J})`:"Copy All"),M&&J>U&&(O+=J-U,ne.textContent=`${O} new event${O===1?"":"s"}`,se.style.display=""),U=J;let Ce=t.getAll(),Pe=Ce.length>0?Ce[0].timestamp:0,Be=new Set(m.map(be=>be.id));for(let be of z)Be.has(be)||z.delete(be);let ut=C!==Le||v!==Ye,ye=pe.size===0&&m.length>0;if(ut||ye||m.length===0){le.innerHTML="",pe.clear();let be=document.createDocumentFragment();for(let $e=0;$e<m.length;$e++){let de=po(m[$e],$e,Pe,a,z,He,s,o);pe.set(m[$e].id,de),be.appendChild(de)}le.appendChild(be),Le=C,Ye=v,fe=null}else{if(fe!==null){let $e=pe.get(fe);if($e&&$e.parentNode===le){let de=m.findIndex(bt=>bt.id===fe);if(de>=0){let bt=po(m[de],de,Pe,a,z,He,s,o);le.insertBefore(bt,$e),$e.remove(),pe.set(fe,bt)}}fe=null}let be=new Set(m.map($e=>$e.id));for(let[$e,de]of pe)be.has($e)||(de.remove(),pe.delete($e));for(let $e=0;$e<m.length;$e++){let de=m[$e];if(!pe.has(de.id)){let bt=po(de,$e,Pe,a,z,He,s,o);pe.set(de.id,bt),le.appendChild(bt)}}}M||(le.scrollTop=le.scrollHeight)}function jt(){if(Date.now()-S>=od){Z!==null&&(cancelAnimationFrame(Z),Z=null),et();return}N||(N=!0,Z=requestAnimationFrame(()=>{Z=null,et()}))}let Dt=(te,J)=>{if(!V)return;V.innerHTML="";let We=ue(te,"12px","currentColor",1.5);We&&V.appendChild(We);let Ce=f("span","persona-text-xs");Ce.textContent="Copy All",V.appendChild(Ce),setTimeout(()=>{V.innerHTML="";let Pe=ue("clipboard-copy","12px","currentColor",1.5);Pe&&V.appendChild(Pe);let Be=f("span","persona-text-xs");Be.textContent="Copy All",V.appendChild(Be),V.disabled=!1},J)},ie=async()=>{if(V){V.disabled=!0;try{let te;ee()?te=m:n?(te=await n(),te.length===0&&(te=t.getAll())):te=t.getAll();let J=te.map(We=>{try{return JSON.parse(We.payload)}catch{return We.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),Dt("check",1500)}catch{Dt("x",1500)}}},Ue=()=>{Y&&(C=Y.value,X(),et())},Te=()=>{!j||!ce||(ce.style.display=j.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=j.value,X(),et()},150))},tt=()=>{!j||!ce||(j.value="",v="",ce.style.display="none",E&&clearTimeout(E),X(),et())},_e=()=>{if(K)return;let te=le.scrollTop,J=te>re;re=te,Ve()&&J?(M=!1,O=0,se.style.display="none"):Ve()||(M=!0)},Xe=te=>{te.deltaY<0&&(M=!0)},$t=()=>{le.scrollTop=le.scrollHeight,M=!1,O=0,se.style.display="none"},Ft=te=>{let J=te.target;if(!J||J.closest("button"))return;let We=J.closest("[data-event-id]");if(!We)return;let Ce=We.getAttribute("data-event-id");Ce&&He(Ce)},It=te=>{if((te.metaKey||te.ctrlKey)&&te.key==="f"){te.preventDefault(),j==null||j.focus(),j==null||j.select();return}te.key==="Escape"&&(j&&document.activeElement===j?(tt(),j.blur(),y.focus()):r&&r())};V&&V.addEventListener("click",ie),Y&&Y.addEventListener("change",Ue),j&&j.addEventListener("input",Te),ce&&ce.addEventListener("click",tt),le.addEventListener("scroll",_e),le.addEventListener("wheel",Xe,{passive:!0}),le.addEventListener("click",Ft),se.addEventListener("click",$t),y.addEventListener("keydown",It);function H(){E&&clearTimeout(E),Z!==null&&(cancelAnimationFrame(Z),Z=null),N=!1,pe.clear(),V&&V.removeEventListener("click",ie),Y&&Y.removeEventListener("change",Ue),j&&j.removeEventListener("input",Te),ce&&ce.removeEventListener("click",tt),le.removeEventListener("scroll",_e),le.removeEventListener("wheel",Xe),le.removeEventListener("click",Ft),se.removeEventListener("click",$t),y.removeEventListener("keydown",It)}return{element:y,update:jt,destroy:H}}}var Ml=e=>{let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",a=document.createElement("div");a.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.backgroundColor="var(--persona-bg, #ffffff)",a.style.cursor="pointer",a.tabIndex=0,a.setAttribute("role","button"),a.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&a.setAttribute("data-open-artifact",n);let i=document.createElement("div");i.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.color="var(--persona-muted, #9ca3af)",i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let c=document.createElement("div");c.className="persona-truncate persona-text-sm persona-font-medium",c.style.color="var(--persona-text, #1f2937)",c.textContent=t;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #3b82f6)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let y=document.createElement("span");y.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(y)}else g.textContent=s;if(d.append(c,g),a.append(i,d),r==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${t}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",n),a.append(p)}return a};var uo=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},Fn=new uo;Fn.register("PersonaArtifactCard",Ml);function gd(e){var o;let t=f("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=f("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function Qr(e,t,n=""){let r=f("button",`persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-p-1 persona-text-persona-primary hover:persona-bg-persona-container ${n}`);r.type="button",r.setAttribute("aria-label",t),r.title=t;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function es(e,t,n){let r=f("button",`persona-artifact-doc-icon-btn ${n}`.trim());r.type="button",r.setAttribute("aria-label",t),r.title=t;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function kl(e){let t=f("button","persona-artifact-doc-copy-btn");t.type="button",t.setAttribute("aria-label","Copy"),t.title="Copy";let n=ue("copy",e?14:16,"currentColor",2);if(n&&t.appendChild(n),e){let r=f("span","persona-artifact-doc-copy-label");r.textContent="Copy",t.appendChild(r)}return t}function md(){let e=f("button","persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn");e.type="button",e.setAttribute("aria-label","More copy options"),e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false");let t=ue("chevron-down",14,"currentColor",2);return t&&e.appendChild(t),e}function Ll(e,t){var mt,Pt,le,se;let n=(Pt=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:Pt.layout,o=((le=n==null?void 0:n.toolbarPreset)!=null?le:"default")==="document",s=(se=n==null?void 0:n.panePadding)==null?void 0:se.trim(),a=e.markdown?ir(e.markdown):null,i=q=>a?a(q):Dr(q),d=typeof document!="undefined"?f("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,c=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")};d&&d.addEventListener("click",()=>{var q;c(),(q=t.onDismiss)==null||q.call(t)});let g=f("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");o&&g.classList.add("persona-artifact-pane-document");let p=f("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");o&&p.classList.add("persona-artifact-toolbar-document");let y=f("span","persona-text-xs persona-font-medium persona-truncate");y.textContent="Artifacts";let m=f("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");m.type="button",m.textContent="Close",m.setAttribute("aria-label","Close artifacts panel"),m.addEventListener("click",()=>{var q;c(),(q=t.onDismiss)==null||q.call(t)});let C="rendered",v=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=o?es("eye","Rendered view","persona-artifact-view-btn"):Qr("eye","Rendered view",""),x=o?es("code-2","Source","persona-artifact-code-btn"):Qr("code-2","Source",""),k=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,M=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,O=n==null?void 0:n.documentToolbarCopyMenuItems,S=!!(M&&O&&O.length>0),N=null,Z,K=null,re=null;if(o&&(U||M)&&!S){if(Z=kl(U),M){let q=ue("chevron-down",14,"currentColor",2);q&&Z.appendChild(q)}}else if(o&&S){N=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Z=kl(U),K=md(),N.append(Z,K),re=f("div","persona-artifact-doc-copy-menu persona-absolute persona-right-0 persona-top-full persona-z-20 persona-mt-1 persona-min-w-[10rem] persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-py-1 persona-shadow-md persona-hidden"),N.appendChild(re);for(let q of O){let ne=f("button","persona-block persona-w-full persona-text-left persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary hover:persona-bg-persona-container");ne.type="button",ne.textContent=q.label,ne.dataset.copyMenuId=q.id,re.appendChild(ne)}}else o?Z=es("copy","Copy",""):Z=Qr("copy","Copy","");let z=o?es("refresh-cw","Refresh",""):Qr("refresh-cw","Refresh",""),pe=o?es("x","Close",""):Qr("x","Close",""),Le=()=>{var Ke,ee,X;let q=(Ke=j.find(He=>He.id===ce))!=null?Ke:j[j.length-1],ne=(ee=q==null?void 0:q.id)!=null?ee:null,oe=(q==null?void 0:q.artifactType)==="markdown"&&(X=q.markdown)!=null?X:"",Ee=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:oe,jsonPayload:Ee,id:ne}},Ye=async()=>{var Ke;let{markdown:q,jsonPayload:ne}=Le(),oe=(Ke=j.find(ee=>ee.id===ce))!=null?Ke:j[j.length-1],Ee=(oe==null?void 0:oe.artifactType)==="markdown"?q:oe?ne:"";try{await navigator.clipboard.writeText(Ee)}catch{}};if(Z.addEventListener("click",async()=>{let q=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(q&&S){let{markdown:ne,jsonPayload:oe,id:Ee}=Le();try{await q({actionId:"primary",artifactId:Ee,markdown:ne,jsonPayload:oe})}catch{}return}await Ye()}),K&&re){let q=()=>{re.classList.add("persona-hidden"),K.setAttribute("aria-expanded","false")};K.addEventListener("click",ne=>{ne.stopPropagation(),re.classList.contains("persona-hidden")?(re.classList.remove("persona-hidden"),K.setAttribute("aria-expanded","true")):q()}),typeof document!="undefined"&&document.addEventListener("click",q),re.addEventListener("click",async ne=>{let oe=ne.target.closest("button[data-copy-menu-id]");if(!(oe!=null&&oe.dataset.copyMenuId))return;ne.stopPropagation();let Ee=oe.dataset.copyMenuId,{markdown:Ke,jsonPayload:ee,id:X}=Le(),He=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{He?await He({actionId:Ee,artifactId:X,markdown:Ke,jsonPayload:ee}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Ke):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(ee):await navigator.clipboard.writeText(Ke||ee)}catch{}q()})}z.addEventListener("click",async()=>{var q;try{await((q=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:q.call(n))}catch{}gt()}),pe.addEventListener("click",()=>{var q;c(),(q=t.onDismiss)==null||q.call(t)});let fe=()=>{o&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),x.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",fe(),gt()}),x.addEventListener("click",()=>{C="source",fe(),gt()});let Q=f("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(p.replaceChildren(),v.append(E,x),N?k.append(N,z,pe):k.append(Z,z,pe),p.append(v,Q,k),fe()):(p.appendChild(y),p.appendChild(m)),s&&(p.style.paddingLeft=s,p.style.paddingRight=s);let Y=f("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),V=f("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Y.style.paddingLeft=s,Y.style.paddingRight=s,V.style.padding=s),g.appendChild(p),g.appendChild(Y),g.appendChild(V);let j=[],ce=null,he=!1,gt=()=>{var Ee,Ke,ee,X;let q=o&&j.length<=1;Y.classList.toggle("persona-hidden",q),Y.replaceChildren();for(let He of j){let Ve=f("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary hover:persona-bg-persona-container");Ve.type="button",Ve.textContent=He.title||He.id.slice(0,8),He.id===ce&&Ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ve.addEventListener("click",()=>t.onSelect(He.id)),Y.appendChild(Ve)}V.replaceChildren();let ne=ce&&j.find(He=>He.id===ce)||j[j.length-1];if(!ne)return;if(o){let He=ne.artifactType==="markdown"?"MD":(Ee=ne.component)!=null?Ee:"Component",et=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Q.textContent=`${et} \xB7 ${He}`}else y.textContent="Artifacts";if(ne.artifactType==="markdown"){if(o&&C==="source"){let Ve=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ve.textContent=(Ke=ne.markdown)!=null?Ke:"",V.appendChild(Ve);return}let He=f("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=i((ee=ne.markdown)!=null?ee:""),V.appendChild(He);return}let oe=ne.component?Fn.get(ne.component):void 0;if(oe){let Ve={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let et=oe((X=ne.props)!=null?X:{},Ve);if(et){V.appendChild(et);return}}catch{}}V.appendChild(gd(ne))},lt=()=>{var ne;let q=j.length>0;if(g.classList.toggle("persona-hidden",!q),d){let oe=typeof g.closest=="function"?g.closest("#persona-root"):null,Ke=((ne=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&Ke&&he?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(q){var ne,oe,Ee;j=q.artifacts,ce=(Ee=(oe=q.selectedId)!=null?oe:(ne=q.artifacts[q.artifacts.length-1])==null?void 0:ne.id)!=null?Ee:null,j.length>0&&(he=!0),gt(),lt()},setMobileOpen(q){he=q,!q&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):lt()}}}function on(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function Pl(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!on(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function fd(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ls(e,t){var d,c,g,p,y,m,C,v,E,x;if(!on(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),fd(e),Pl(e,t);return}let n=(c=(d=t.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=n==null?void 0:n.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=n==null?void 0:n.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(y=n==null?void 0:n.paneMaxWidth)!=null?y:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=n==null?void 0:n.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(C=n==null?void 0:n.panePadding)==null?void 0:C.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=n==null?void 0:n.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Pl(e,t)}var Il=["panel","seamless"];function Ps(e,t){var i,d,c,g,p,y;for(let m of Il)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!on(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=n==null?void 0:n.paneAppearance)!=null?c:"panel",o=Il.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(g=n==null?void 0:n.paneBorderRadius)==null?void 0:g.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=n==null?void 0:n.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((y=n.unifiedSplitOuterRadius)==null?void 0:y.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Wl(e,t){var n,r,o;return!t||!on(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function hd(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function yd(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function bd(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function xd(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Rl(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Hl(e,t,n,r,o,s){let a=hd(o,200),i=xd(t,n,r,200);i=Math.max(a,i);let d=yd(s);return d!==null&&(i=Math.min(i,d)),bd(e,a,i)}var Bl={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"}},go=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=Bl[a])!=null?v:Bl.init;s.classList.add("persona-form-card","persona-space-y-4");let d=f("div","persona-space-y-1"),c=f("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=f("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var S,N;let k=f("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${t.id}-${a}-${x.name}`;let U=f("span","persona-text-xs persona-font-medium persona-text-persona-muted");U.textContent=x.label,k.appendChild(U);let M=(S=x.type)!=null?S:"text",O;M==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=M),O.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",O.id=`${t.id}-${a}-${x.name}`,O.name=x.name,O.placeholder=(N=x.placeholder)!=null?N:"",x.required&&(O.required=!0),k.appendChild(O),g.appendChild(k)});let p=f("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=f("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=f("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(y),p.appendChild(m),g.appendChild(p),s.replaceChildren(d,g),g.addEventListener("submit",async x=>{var O,S;x.preventDefault();let k=(O=n.formEndpoint)!=null?O:"/form",U=new FormData(g),M={};U.forEach((N,Z)=>{M[Z]=N}),M.type=a,m.disabled=!0,y.textContent="Submitting\u2026";try{let N=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!N.ok)throw new Error(`Form submission failed (${N.status})`);let Z=await N.json();y.textContent=(S=Z.message)!=null?S:"Thanks! We'll be in touch soon.",Z.success&&Z.nextPrompt&&await r.sendMessage(String(Z.nextPrompt))}catch(N){y.textContent=N instanceof Error?N.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mo=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},Is=new mo;var $l={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"},Fl={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"},yt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:$l,darkTheme:Fl,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px",collapsedWidth:"72px"},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 fo(e){var t,n,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U,M,O;return e?{...yt,...e,theme:{...yt.theme,...e.theme},darkTheme:{...yt.darkTheme,...e.darkTheme},launcher:{...yt.launcher,...e.launcher,dock:{...(t=yt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=yt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...yt.copy,...e.copy},sendButton:{...yt.sendButton,...e.sendButton},statusIndicator:{...yt.statusIndicator,...e.statusIndicator},voiceRecognition:{...yt.voiceRecognition,...e.voiceRecognition},features:(()=>{var K,re;let S=(K=yt.features)==null?void 0:K.artifacts,N=(re=e.features)==null?void 0:re.artifacts,Z=S===void 0&&N===void 0?void 0:{...S,...N,layout:{...S==null?void 0:S.layout,...N==null?void 0:N.layout}};return{...yt.features,...e.features,...Z!==void 0?{artifacts:Z}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:yt.suggestionChips,suggestionChipsConfig:{...yt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...yt.layout,...e.layout,header:{...(a=yt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=yt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=yt.layout)==null?void 0:g.messages)==null?void 0:p.avatar,...(m=(y=e.layout)==null?void 0:y.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=yt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(x=(E=e.layout)==null?void 0:E.messages)==null?void 0:x.timestamp}},slots:{...(k=yt.layout)==null?void 0:k.slots,...(U=e.layout)==null?void 0:U.slots}},markdown:{...yt.markdown,...e.markdown,options:{...(M=yt.markdown)==null?void 0:M.options,...(O=e.markdown)==null?void 0:O.options}},messageActions:{...yt.messageActions,...e.messageActions}}:yt}var Nl=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var vd=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Cd=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=vd(e),n=Cd(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ho=e=>typeof e=="string"?e:e==null?"":String(e),yr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ho(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=ho(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ho(n.text)}}},Ol=e=>Array.isArray(e)?e.map(t=>String(t)):[],Rs=e=>{let t=new Set(Ol(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(Ol(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&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 i=a?e.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let g=()=>{e.emit("action:resubmit",d)},p=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:g});if(!p)continue;if(p.handled){let y=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:y,resubmit:p.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:n}};var wd=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Sd=e=>e.map(t=>({...t,streaming:!1})),yo=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?wd(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?Sd(n.messages):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Ad,STR as Ed,OBJ as Td}from"partial-json";function Md(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function kd(e,t){if(!Md(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function bo(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=Ad(n,Ed|Td),s=kd(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Ld(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function xo(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=Fn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Pd(){let e=bo();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function vo(e){if(!e.rawContent)return!1;try{let t=JSON.parse(e.rawContent);return typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string"}catch{return!1}}function Co(e){if(!e.rawContent)return null;try{let t=JSON.parse(e.rawContent);if(typeof t=="object"&&t!==null&&"component"in t&&typeof t.component=="string")return{component:t.component,props:t.props&&typeof t.props=="object"&&t.props!==null?t.props:{},raw:e.rawContent}}catch{}return null}var Id=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function wo(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Id}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let p=null,y=document.createElement("div");y.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,m.appendChild(v),y.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let S=1;S<=5;S++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),N.title=c[S-1],N.dataset.rating=String(S),N.innerHTML=`
|
|
15
|
+
`,t.addEventListener("click",n);let r=s=>{var U,M,O,S,N,Q,K,re,J,pe,Le,Ye;let a=(U=s.launcher)!=null?U:{},i=Ut(s),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(O=a.subtitle)!=null?O:"Get answers fast");let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let fe=(S=a.agentIconSize)!=null?S:"40px";if(p.style.height=fe,p.style.width=fe,p.innerHTML="",a.agentIconName){let ee=parseFloat(fe)||24,Y=ue(a.agentIconName,ee*.6,"var(--persona-text-inverse, #ffffff)",2);Y?(p.appendChild(Y),p.style.display=""):(p.textContent=(N=a.agentIconText)!=null?N:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(Q=a.agentIconText)!=null?Q:"\u{1F4AC}",p.style.display="")}let y=t.querySelector("[data-role='launcher-image']");if(y){let fe=(K=a.agentIconSize)!=null?K:"40px";y.style.height=fe,y.style.width=fe,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(y.src=a.iconUrl,y.style.display="block"):y.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let fe=(re=a.callToActionIconSize)!=null?re:"32px";m.style.height=fe,m.style.width=fe,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Y=parseFloat(fe)||24,V=Math.max(Y-ee,8),j=ue(a.callToActionIconName,V,"currentColor",2);j?m.appendChild(j):m.textContent=(J=a.callToActionIconText)!=null?J:"\u2197"}else m.textContent=(pe=a.callToActionIconText)!=null?pe:"\u2197"}let C=a.position&&dn[a.position]?dn[a.position]:dn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${v} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";if(t.style.border=(Le=a.border)!=null?Le:x,t.style.boxShadow=(Ye=a.shadow)!=null?Ye:k,i){let fe=zr(s);t.style.width=`calc(${fe.collapsedWidth} - 16px)`,t.style.minWidth="40px",t.style.maxWidth=`calc(${fe.collapsedWidth} - 16px)`,t.style.justifyContent="center",t.style.padding="12px 0"}else t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.justifyContent="",t.style.padding=""},o=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:o}};var $n=e=>{var re,J,pe,Le,Ye,fe,ee,Y,V,j,ce,he,gt,lt,mt,It,le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,jt,Dt,ie,Ue;let{config:n,showClose:t=!0}=e,r=f("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomWidth="1px",r.style.borderBottomStyle="solid",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))";let o=(re=n==null?void 0:n.launcher)!=null?re:{},s=(J=o.headerIconSize)!=null?J:"48px",a=(pe=o.closeButtonSize)!=null?pe:"32px",i=(Le=o.closeButtonPlacement)!=null?Le:"inline",d=(Ye=o.headerIconHidden)!=null?Ye:!1,c=o.headerIconName,g=f("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-bg-persona-primary persona-text-white persona-text-xl");if(g.style.height=s,g.style.width=s,!d)if(c){let Te=parseFloat(s)||24,tt=ue(c,Te*.6,"var(--persona-text-inverse, #ffffff)",1);tt?g.replaceChildren(tt):g.textContent=(ee=(fe=n==null?void 0:n.launcher)==null?void 0:fe.agentIconText)!=null?ee:"\u{1F4AC}"}else if((Y=n==null?void 0:n.launcher)!=null&&Y.iconUrl){let Te=f("img");Te.src=n.launcher.iconUrl,Te.alt="",Te.className="persona-rounded-xl persona-object-cover",Te.style.height=s,Te.style.width=s,g.replaceChildren(Te)}else g.textContent=(j=(V=n==null?void 0:n.launcher)==null?void 0:V.agentIconText)!=null?j:"\u{1F4AC}";let p=f("div","persona-flex persona-flex-col"),y=f("span","persona-text-base persona-font-semibold");y.textContent=(he=(ce=n==null?void 0:n.launcher)==null?void 0:ce.title)!=null?he:"Chat Assistant";let m=f("span","persona-text-xs persona-text-persona-muted");m.textContent=(lt=(gt=n==null?void 0:n.launcher)==null?void 0:gt.subtitle)!=null?lt:"Here to help you get answers fast",p.append(y,m),d?r.append(p):r.append(g,p);let C=(mt=o.clearChat)!=null?mt:{},v=(It=C.enabled)!=null?It:!0,E=(le=C.placement)!=null?le:"inline",x=null,k=null;if(v){let Te=(se=C.size)!=null?se:"32px",tt=(q=C.iconName)!=null?q:"refresh-cw",_e=(ne=C.iconColor)!=null?ne:"",Xe=(oe=C.backgroundColor)!=null?oe:"",Wt=(Ee=C.borderWidth)!=null?Ee:"",Rt=(Ke=C.borderColor)!=null?Ke:"",Mt=(te=C.borderRadius)!=null?te:"",H=(X=C.paddingX)!=null?X:"",Z=(He=C.paddingY)!=null?He:"",z=(Ve=C.tooltipText)!=null?Ve:"Clear chat",Pe=(et=C.showTooltip)!=null?et:!0;k=f("div",E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),x=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),x.style.height=Te,x.style.width=Te,x.type="button",x.setAttribute("aria-label",z);let Ce=ue(tt,"20px",_e||"",1);if(Ce&&x.appendChild(Ce),_e&&(x.style.color=_e,x.classList.remove("persona-text-persona-muted")),Xe&&(x.style.backgroundColor=Xe,x.classList.remove("hover:persona-bg-gray-100")),Wt||Rt){let Ie=Wt||"0px",Be=Rt||"transparent";x.style.border=`${Ie} solid ${Be}`,x.classList.remove("persona-border-none")}if(Mt&&(x.style.borderRadius=Mt,x.classList.remove("persona-rounded-full")),H?(x.style.paddingLeft=H,x.style.paddingRight=H):(x.style.paddingLeft="",x.style.paddingRight=""),Z?(x.style.paddingTop=Z,x.style.paddingBottom=Z):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),Pe&&z&&x&&k){let Ie=null,Be=()=>{if(Ie||!x)return;let ye=x.ownerDocument,be=ye.body;if(!be)return;Ie=bn(ye,"div","persona-clear-chat-tooltip"),Ie.textContent=z;let $e=bn(ye,"div");$e.className="persona-clear-chat-tooltip-arrow",Ie.appendChild($e);let de=x.getBoundingClientRect();Ie.style.position="fixed",Ie.style.left=`${de.left+de.width/2}px`,Ie.style.top=`${de.top-8}px`,Ie.style.transform="translate(-50%, -100%)",be.appendChild(Ie)},ut=()=>{Ie&&Ie.parentNode&&(Ie.parentNode.removeChild(Ie),Ie=null)};k.addEventListener("mouseenter",Be),k.addEventListener("mouseleave",ut),x.addEventListener("focus",Be),x.addEventListener("blur",ut),k._cleanupTooltip=()=>{ut(),k&&(k.removeEventListener("mouseenter",Be),k.removeEventListener("mouseleave",ut)),x&&(x.removeEventListener("focus",Be),x.removeEventListener("blur",ut))}}E==="inline"&&r.appendChild(k)}let U=f("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&E==="inline"?"":"persona-ml-auto"),M=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=a,M.style.width=a,M.type="button";let O=(jt=o.closeButtonTooltipText)!=null?jt:"Close chat",S=(Dt=o.closeButtonShowTooltip)!=null?Dt:!0;M.setAttribute("aria-label",O),M.style.display=t?"":"none";let N=(ie=o.closeButtonIconName)!=null?ie:"x",Q=(Ue=o.closeButtonIconText)!=null?Ue:"\xD7",K=ue(N,"20px",o.closeButtonColor||"",1);if(K?M.appendChild(K):M.textContent=Q,o.closeButtonColor?(M.style.color=o.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),o.closeButtonBackgroundColor?(M.style.backgroundColor=o.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),o.closeButtonBorderWidth||o.closeButtonBorderColor){let Te=o.closeButtonBorderWidth||"0px",tt=o.closeButtonBorderColor||"transparent";M.style.border=`${Te} solid ${tt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(o.closeButtonBorderRadius?(M.style.borderRadius=o.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),o.closeButtonPaddingX?(M.style.paddingLeft=o.closeButtonPaddingX,M.style.paddingRight=o.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),o.closeButtonPaddingY?(M.style.paddingTop=o.closeButtonPaddingY,M.style.paddingBottom=o.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),U.appendChild(M),S&&O){let Te=null,tt=()=>{if(Te)return;let Xe=M.ownerDocument,Wt=Xe.body;if(!Wt)return;Te=bn(Xe,"div","persona-clear-chat-tooltip"),Te.textContent=O;let Rt=bn(Xe,"div");Rt.className="persona-clear-chat-tooltip-arrow",Te.appendChild(Rt);let Mt=M.getBoundingClientRect();Te.style.position="fixed",Te.style.left=`${Mt.left+Mt.width/2}px`,Te.style.top=`${Mt.top-8}px`,Te.style.transform="translate(-50%, -100%)",Wt.appendChild(Te)},_e=()=>{Te&&Te.parentNode&&(Te.parentNode.removeChild(Te),Te=null)};U.addEventListener("mouseenter",tt),U.addEventListener("mouseleave",_e),M.addEventListener("focus",tt),M.addEventListener("blur",_e),U._cleanupTooltip=()=>{_e(),U.removeEventListener("mouseenter",tt),U.removeEventListener("mouseleave",_e),M.removeEventListener("focus",tt),M.removeEventListener("blur",_e)}}return i!=="top-right"&&r.appendChild(U),{header:r,iconHolder:g,headerTitle:y,headerSubtitle:m,closeButton:M,closeButtonWrapper:U,clearChatButton:x,clearChatButtonWrapper:k}},ur=(e,n,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(n.header),o==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};var fl=e=>$n({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat});function Jc(e,n,t){var r,o;if(n!=null&&n.length)for(let s of n){let a=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(a.type="button",a.setAttribute("aria-label",(o=(r=s.ariaLabel)!=null?r:s.label)!=null?o:s.id),s.icon){let i=ue(s.icon,14,"currentColor",2);i&&a.appendChild(i)}else s.label&&(a.textContent=s.label);a.addEventListener("click",()=>t==null?void 0:t(s.id)),e.appendChild(a)}}var hl=e=>{var x,k,U,M,O;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(x=n==null?void 0:n.launcher)!=null?x:{},i=f("div","persona-flex persona-items-center persona-justify-between persona-bg-persona-surface persona-px-6 persona-py-4 persona-border-b-persona-divider"),d=f("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=f("span","persona-text-base persona-font-semibold persona-truncate");c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),Jc(d,o==null?void 0:o.trailingActions,(U=o==null?void 0:o.onAction)!=null?U:s),i.appendChild(d);let g=(M=a.closeButtonSize)!=null?M:"32px",p=f("div",""),y=f("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");y.style.height=g,y.style.width=g,y.type="button",y.setAttribute("aria-label","Close chat"),y.style.display=t?"":"none";let m=(O=a.closeButtonIconName)!=null?O:"x",C=ue(m,"20px",a.closeButtonColor||"",2);C?y.appendChild(C):y.textContent="\xD7",r&&y.addEventListener("click",r),p.appendChild(y),i.appendChild(p);let v=f("div");v.style.display="none";let E=f("span");return E.style.display="none",{header:i,iconHolder:v,headerTitle:c,headerSubtitle:E,closeButton:y,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ao={default:fl,minimal:hl},yl=e=>{var n;return(n=ao[e])!=null?n:ao.default},Kr=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),g=f("div");g.style.display="none";let p=f("span"),y=f("span"),m=f("button");m.style.display="none";let C=f("div");return C.style.display="none",{header:c,iconHolder:g,headerTitle:p,headerSubtitle:y,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",s=yl(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});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 Kc=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Yr=e=>{var le,se,q,ne,oe,Ee,Ke,te,X,He,Ve,et,jt,Dt,ie,Ue,Te,tt,_e,Xe,Wt,Rt,Mt,H,Z,z,Pe,Ce,Ie,Be,ut;let{config:n}=e,t=f("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4"),r=f("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),o=f("form","persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3");o.setAttribute("data-persona-composer-form",""),o.style.outline="none";let s=f("textarea");s.setAttribute("data-persona-composer-input",""),s.placeholder=(se=(le=n==null?void 0:n.copy)==null?void 0:le.inputPlaceholder)!=null?se:"Type your message\u2026",s.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",s.rows=1;let a=(ne=(q=n==null?void 0:n.theme)==null?void 0:q.inputFontFamily)!=null?ne:"sans-serif",i=(Ee=(oe=n==null?void 0:n.theme)==null?void 0:oe.inputFontWeight)!=null?Ee:"400";s.style.fontFamily=Kc(a),s.style.fontWeight=i;let g=3*20;s.style.maxHeight=`${g}px`,s.style.overflowY="auto";let p=()=>{s.style.height="auto";let ye=Math.min(s.scrollHeight,g);s.style.height=`${ye}px`};s.addEventListener("input",p),s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.addEventListener("focus",()=>{s.style.border="none",s.style.outline="none",s.style.borderWidth="0",s.style.borderStyle="none",s.style.borderColor="transparent",s.style.boxShadow="none"}),s.addEventListener("blur",()=>{s.style.border="none",s.style.outline="none"});let y=(Ke=n==null?void 0:n.sendButton)!=null?Ke:{},m=(te=y.useIcon)!=null?te:!1,C=(X=y.iconText)!=null?X:"\u2191",v=y.iconName,E=(He=y.tooltipText)!=null?He:"Send message",x=(Ve=y.showTooltip)!=null?Ve:!1,k=(et=y.size)!=null?et:"40px",U=y.backgroundColor,M=y.textColor,O=f("div","persona-send-button-wrapper"),S=f("button",m?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(S.type="submit",S.setAttribute("data-persona-composer-submit",""),m){if(S.style.width=k,S.style.height=k,S.style.minWidth=k,S.style.minHeight=k,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",v){let ye=parseFloat(k)||24,be=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",$e=ue(v,ye,be,2);$e?(S.appendChild($e),S.style.color=be):(S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white"))}else S.textContent=C,M?S.style.color=M:S.classList.add("persona-text-white");U?S.style.backgroundColor=U:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Dt=(jt=n==null?void 0:n.copy)==null?void 0:jt.sendButtonLabel)!=null?Dt:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(y.borderWidth&&(S.style.borderWidth=y.borderWidth,S.style.borderStyle="solid"),y.borderColor&&(S.style.borderColor=y.borderColor),y.paddingX?(S.style.paddingLeft=y.paddingX,S.style.paddingRight=y.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),y.paddingY?(S.style.paddingTop=y.paddingY,S.style.paddingBottom=y.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),x&&E){let ye=f("div","persona-send-button-tooltip");ye.textContent=E,O.appendChild(ye)}O.appendChild(S);let N=(ie=n==null?void 0:n.voiceRecognition)!=null?ie:{},Q=N.enabled===!0,K=null,re=null,J=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),pe=((Ue=N.provider)==null?void 0:Ue.type)==="runtype";if(Q&&(J||pe)){re=f("div","persona-send-button-wrapper"),K=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),K.type="button",K.setAttribute("data-persona-composer-mic",""),K.setAttribute("aria-label","Start voice recognition");let ye=(Te=N.iconName)!=null?Te:"mic",be=(tt=N.iconSize)!=null?tt:k,$e=parseFloat(be)||24,de=(_e=N.backgroundColor)!=null?_e:U,bt=(Xe=N.iconColor)!=null?Xe:M;K.style.width=be,K.style.height=be,K.style.minWidth=be,K.style.minHeight=be,K.style.fontSize="18px",K.style.lineHeight="1";let Gt=bt||"currentColor",pn=ue(ye,$e,Gt,1.5);pn?(K.appendChild(pn),K.style.color=Gt):(K.textContent="\u{1F3A4}",K.style.color=Gt),de?K.style.backgroundColor=de:K.classList.add("persona-bg-persona-primary"),bt?K.style.color=bt:!bt&&!M&&K.classList.add("persona-text-white"),N.borderWidth&&(K.style.borderWidth=N.borderWidth,K.style.borderStyle="solid"),N.borderColor&&(K.style.borderColor=N.borderColor),N.paddingX&&(K.style.paddingLeft=N.paddingX,K.style.paddingRight=N.paddingX),N.paddingY&&(K.style.paddingTop=N.paddingY,K.style.paddingBottom=N.paddingY),re.appendChild(K);let un=(Wt=N.tooltipText)!=null?Wt:"Start voice recognition";if(((Rt=N.showTooltip)!=null?Rt:!1)&&un){let Ln=f("div","persona-send-button-tooltip");Ln.textContent=un,re.appendChild(Ln)}}let Ye=(Mt=n==null?void 0:n.attachments)!=null?Mt:{},fe=Ye.enabled===!0,ee=null,Y=null,V=null,j=null;if(fe){j=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),j.style.display="none",V=f("input"),V.type="file",V.accept=((H=Ye.allowedTypes)!=null?H:Mn).join(","),V.multiple=((Z=Ye.maxFiles)!=null?Z:4)>1,V.style.display="none",V.setAttribute("aria-label","Attach files"),Y=f("div","persona-send-button-wrapper"),ee=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ee.type="button",ee.setAttribute("aria-label",(z=Ye.buttonTooltipText)!=null?z:"Attach file");let ye=(Pe=Ye.buttonIconName)!=null?Pe:"paperclip",be=k,$e=parseFloat(be)||40,de=Math.round($e*.6);ee.style.width=be,ee.style.height=be,ee.style.minWidth=be,ee.style.minHeight=be,ee.style.fontSize="18px",ee.style.lineHeight="1",ee.style.backgroundColor="transparent",ee.style.color="var(--persona-primary, #111827)",ee.style.border="none",ee.style.borderRadius="6px",ee.style.transition="background-color 0.15s ease",ee.addEventListener("mouseenter",()=>{ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ee.addEventListener("mouseleave",()=>{ee.style.backgroundColor="transparent"});let bt=ue(ye,de,"currentColor",1.5);bt?ee.appendChild(bt):ee.textContent="\u{1F4CE}",ee.addEventListener("click",un=>{un.preventDefault(),V==null||V.click()}),Y.appendChild(ee);let Gt=(Ce=Ye.buttonTooltipText)!=null?Ce:"Attach file",pn=f("div","persona-send-button-tooltip");pn.textContent=Gt,Y.appendChild(pn)}o.addEventListener("click",ye=>{ye.target!==S&&ye.target!==O&&ye.target!==K&&ye.target!==re&&ye.target!==ee&&ye.target!==Y&&s.focus()}),j&&(j.style.gap="8px",o.append(j)),V&&o.append(V),o.append(s);let ce=f("div","persona-flex persona-items-center persona-justify-between persona-w-full"),he=f("div","persona-flex persona-items-center persona-gap-2");Y&&he.append(Y);let gt=f("div","persona-flex persona-items-center persona-gap-1");re&>.append(re),gt.append(O),ce.append(he,gt),o.append(ce);let lt=f("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");lt.setAttribute("data-persona-composer-status","");let mt=(Ie=n==null?void 0:n.statusIndicator)!=null?Ie:{},It=(Be=mt.visible)!=null?Be:!0;return lt.style.display=It?"":"none",lt.textContent=(ut=mt.idleText)!=null?ut:"Online",t.append(r,o,lt),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:S,sendButtonWrapper:O,micButton:K,micButtonWrapper:re,statusText:lt,attachmentButton:ee,attachmentButtonWrapper:Y,attachmentInput:V,attachmentPreviewsContainer:j,actionsRow:ce,leftActions:he,rightActions:gt}};var bl=e=>{var c,g,p,y,m,C,v;let n=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Ut(e)){let E=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=f("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return E.appendChild(x),{wrapper:E,panel:x}}if(!n){let E=f("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=f("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(y=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?y:"100%";return E.style.width=k,x.style.width="100%",E.appendChild(x),{wrapper:E,panel:x}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},o=r.position&&dn[r.position]?dn[r.position]:dn["bottom-right"],s=f("div",`persona-widget-wrapper persona-fixed ${o} persona-z-50 persona-transition`),a=f("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(v=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?v:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,s.appendChild(a),{wrapper:s,panel:a}},xl=(e,n=!0)=>{var v,E,x,k,U,M,O,S,N;let t=f("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border"),r=(v=e==null?void 0:e.layout)==null?void 0:v.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Kr(e,r,{showClose:n}):$n({config:e,showClose:n}),a=f("div","persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6");a.id="persona-scroll-container";let i=f("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm"),d=f("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let c=f("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(M=(U=e==null?void 0:e.copy)==null?void 0:U.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",i.append(d,c);let g=f("div","persona-flex persona-flex-col persona-gap-3"),p=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((S=e==null?void 0:e.copy)==null?void 0:S.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Yr({config:e}),C=((N=e==null?void 0:e.layout)==null?void 0:N.showFooter)!==!1;return o?ur(t,s,e):(s.header.style.display="none",ur(t,s,e)),t.append(a),C||(m.footer.style.display="none"),t.append(m.footer),{container:t,body:a,messagesWrapper:g,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle: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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var Yc=320,Xc=320,Gc=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Zc=(e,n,t)=>{if(e.length===0)return null;try{let r=f("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let c=f("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Yc}px`,c.style.maxHeight=`${Xc}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;o+=1,c.addEventListener("error",()=>{g||(g=!0,o=Math.max(0,o-1),c.remove(),o===0&&a())}),c.addEventListener("load",()=>{g=!0}),c.src=i.image,r.appendChild(c)}),o===0?(a(),null):r}catch{return t==null||t(),null}},gr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(o),e},Cl=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:gr};if(n){let o=n(r);if(o!==null)return o}return gr()},Qc=(e,n)=>{let t=f("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=f("img");o.src=r,o.alt=n==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(o)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},vl=(e,n)=>{let t=f("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},ed=(e,n="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},wl=(e,n,t)=>{var m,C,v,E,x,k;let r=(m=n.showCopy)!=null?m:!0,o=(C=n.showUpvote)!=null?C:!0,s=(v=n.showDownvote)!=null?v:!0;if(!r&&!o&&!s){let U=f("div");return U.style.display="none",U.id=`actions-${e.id}`,U.setAttribute("data-actions-for",e.id),U}let a=(E=n.visibility)!=null?E:"hover",i=(x=n.align)!=null?x:"right",d=(k=n.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=f("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let y=(U,M,O)=>{let S=document.createElement("button");S.className="persona-message-action-btn",S.setAttribute("aria-label",M),S.setAttribute("title",M),S.setAttribute("data-action",O);let N=ue(U,14,"currentColor",2);return N&&S.appendChild(N),S};return r&&p.appendChild(y("copy","Copy message","copy")),o&&p.appendChild(y("thumbs-up","Upvote","upvote")),s&&p.appendChild(y("thumbs-down","Downvote","downvote")),p},Xr=(e,n,t,r,o,s)=>{var re,J,pe,Le,Ye,fe,ee;let a=t!=null?t:{},i=(re=a.layout)!=null?re:"bubble",d=a.avatar,c=a.timestamp,g=(J=d==null?void 0:d.show)!=null?J:!1,p=(pe=c==null?void 0:c.show)!=null?pe:!1,y=(Le=d==null?void 0:d.position)!=null?Le:"left",m=(Ye=c==null?void 0:c.position)!=null?Ye:"below",C=ed(e.role,i),v=f("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=Gc(e),x=(ee=(fe=e.content)==null?void 0:fe.trim())!=null?ee:"",U=E.length>0&&x===ws,M=document.createElement("div");M.classList.add("persona-message-content");let O=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),S=null;if(U?(S=document.createElement("div"),S.innerHTML=O,S.style.display="none",M.appendChild(S)):M.innerHTML=O,p&&m==="inline"&&e.createdAt){let Y=vl(e,c);Y.classList.add("persona-ml-2","persona-inline"),M.appendChild(Y)}if(E.length>0){let Y=Zc(E,!U&&!!x,()=>{U&&S&&(S.style.display="")});Y?v.appendChild(Y):U&&S&&(S.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let Y=vl(e,c);Y.classList.add("persona-mt-1"),v.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=Cl("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);Y&&v.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let Y=wl(e,r,o);v.appendChild(Y)}if(!g||e.role==="system")return v;let Q=f("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),K=Qc(d,e.role);return y==="right"||y==="left"&&e.role==="user"?Q.append(v,K):Q.append(K,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Q},td=(e,n,t,r,o,s)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Xr(e,n,t,r,o,s)};var mr=new Set,Sl=(e,n)=>{let t=mr.has(e),r=n.querySelector('button[data-expand-header="true"]'),o=n.querySelector(".persona-border-t");if(!r||!o)return;r.setAttribute("aria-expanded",t?"true":"false");let s=r.querySelector(".persona-ml-auto"),a=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=ue(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}o.style.display=t?"":"none"},io=e=>{let n=e.reasoning,t=f("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!n)return t;let r=mr.has(e.id),o=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");o.type="button",o.setAttribute("aria-expanded",r?"true":"false"),o.setAttribute("data-expand-header","true"),o.setAttribute("data-bubble-type","reasoning");let s=f("div","persona-flex persona-flex-col persona-text-left"),a=f("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",s.appendChild(a);let i=f("span","persona-text-xs persona-text-persona-primary");i.textContent=Ji(n),s.appendChild(i),n.status==="complete"?a.style.display="none":a.style.display="";let d=f("div","persona-flex persona-items-center"),g=ue(r?"chevron-up":"chevron-down",16,"currentColor",2);g?d.appendChild(g):d.textContent=r?"Hide":"Show";let p=f("div","persona-flex persona-items-center persona-ml-auto");p.append(d),o.append(s,p);let y=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");y.style.display=r?"":"none";let m=n.chunks.join(""),C=f("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),y.appendChild(C),(()=>{o.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=ue(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",y.style.display=r?"":"none"})(),t.append(o,y),t};var fr=new Set,Al=(e,n,t)=>{var c;let r=fr.has(e),o=(c=t==null?void 0:t.toolCall)!=null?c:{},s=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t");if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let i=s.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=o.toggleTextColor||o.headerTextColor||"currentColor",p=ue(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},lo=(e,n)=>{var v;let t=e.toolCall,r=(v=n==null?void 0:n.toolCall)!=null?v:{},o=f("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),!t)return o;let s=fr.has(e.id),a=f("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",s?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(a.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(a.style.paddingLeft=r.headerPaddingX,a.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(a.style.paddingTop=r.headerPaddingY,a.style.paddingBottom=r.headerPaddingY);let i=f("div","persona-flex persona-flex-col persona-text-left"),d=f("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(d.style.color=r.headerTextColor),d.textContent=Ki(t),i.appendChild(d);let c=f("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=ue(s?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=s?"Hide":"Show";let y=f("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");y.append(c),a.append(i,y);let m=f("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=s?"":"none",r.contentBackgroundColor&&(m.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(m.style.color=r.contentTextColor),r.contentPaddingX&&(m.style.paddingLeft=r.contentPaddingX,m.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(m.style.paddingTop=r.contentPaddingY,m.style.paddingBottom=r.contentPaddingY),t.name){let E=f("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?E.style.color=r.contentTextColor:r.headerTextColor&&(E.style.color=r.headerTextColor),E.textContent=t.name,m.appendChild(E)}if(t.args!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Arguments";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=_r(t.args),E.append(x,k),m.appendChild(E)}if(t.chunks&&t.chunks.length){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Activity";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=t.chunks.join(`
|
|
16
|
+
`),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&t.result!==void 0){let E=f("div","persona-space-y-1"),x=f("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Result";let k=f("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-border-gray-100 persona-bg-white persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=_r(t.result),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&typeof t.duration=="number"){let E=f("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${t.duration}ms`,m.appendChild(E)}return(()=>{a.setAttribute("aria-expanded",s?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=ue(s?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=s?"Hide":"Show",m.style.display=s?"":"none"})(),o.append(a,m),o};var co=(e,n)=>{var v,E,x,k,U,M,O,S,N,Q,K,re;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.approval:void 0,o=(t==null?void 0:t.status)==="pending",s=f("div",["persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return s;let a=f("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=f("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=r==null?void 0:r.titleColor)!=null?x:"currentColor",g=ue(d,20,c,2);g&&i.appendChild(g);let p=f("div","persona-flex-1 persona-min-w-0"),y=f("div","persona-flex persona-items-center persona-gap-2"),m=f("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",y.appendChild(m),!o){let J=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");J.setAttribute("data-approval-status",t.status),t.status==="approved"?(J.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",J.style.color="var(--persona-palette-colors-success-700, #15803d)",J.textContent="Approved"):t.status==="denied"?(J.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",J.style.color="var(--persona-palette-colors-error-700, #b91c1c)",J.textContent="Denied"):t.status==="timeout"&&(J.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",J.style.color="var(--persona-palette-colors-warning-700, #b45309)",J.textContent="Timeout"),y.appendChild(J)}p.appendChild(y);let C=f("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let J=f("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(J.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(J.style.color=r.parameterTextColor),J.style.fontSize="0.75rem",J.style.lineHeight="1rem",J.textContent=_r(t.parameters),p.appendChild(J)}if(o){let J=f("div","persona-flex persona-gap-2 persona-mt-2");J.setAttribute("data-approval-buttons","true");let pe=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");pe.type="button",pe.style.backgroundColor=(U=r==null?void 0:r.approveButtonColor)!=null?U:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",pe.setAttribute("data-approval-action","approve");let Le=ue("shield-check",14,(O=r==null?void 0:r.approveButtonTextColor)!=null?O:"#ffffff",2);Le&&(Le.style.marginRight="4px",pe.appendChild(Le));let Ye=document.createTextNode((S=r==null?void 0:r.approveLabel)!=null?S:"Approve");pe.appendChild(Ye);let fe=f("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");fe.type="button",fe.style.backgroundColor=(N=r==null?void 0:r.denyButtonColor)!=null?N:"transparent",fe.style.color=(Q=r==null?void 0:r.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",fe.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,fe.setAttribute("data-approval-action","deny");let ee=ue("shield-x",14,(K=r==null?void 0:r.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",fe.appendChild(ee));let Y=document.createTextNode((re=r==null?void 0:r.denyLabel)!=null?re:"Deny");fe.appendChild(Y),J.append(pe,fe),p.appendChild(J)}return a.append(i,p),s.appendChild(a),s};var El=e=>{let n=[];return{buttons:n,render:(r,o,s,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:o?o.getMessages():[]).some(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=o?o.isStreaming():!1,y=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let C=f("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=y(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!o||o.isStreaming()||(s.value="",o.sendMessage(m))}),g.appendChild(C),n.push(C)}),e.appendChild(g)}}};var Gr=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;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),(t=this.store)==null||t.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 t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.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 Zr=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}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 r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)r.put(o)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{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=()=>{t(s.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{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=()=>{t(s.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of n)r.put(o)}catch{}}};function hr(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var nd={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},rd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},sd=["flowName","stepName","reasoningText","text","name","tool","toolName"],od=100;function ad(e,n){let t={...nd,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return rd}function id(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function ld(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),o=String(n.getSeconds()).padStart(2,"0"),s=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${o}.${s}`}function cd(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let o=r.split("."),s=t;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function dd(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function pd(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function ud(e,n,t){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=n.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&t){let i=s.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=f("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=f("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function po(e,n,t,r,o,s,a,i){var y;let d=o.has(e.id),c=f("div","persona-border-b persona-border-persona-divider persona-text-xs");hr(c,(y=r.classNames)==null?void 0:y.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var pe,Le;let m=f("div",""),C=f("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");C.setAttribute("data-event-id",e.id);let v=f("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=ue(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let x=f("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(pe=r.timestampFormat)!=null?pe:"relative";x.textContent=k==="relative"?id(e.timestamp,t):ld(e.timestamp);let U=null;r.showSequenceNumbers!==!1&&(U=f("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),U.textContent=String(n+1));let M=ad(e.type,r.badgeColors),O=f("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");O.style.backgroundColor=M.bg,O.style.color=M.text,O.style.borderColor=M.text+"50",O.textContent=e.type;let S=(Le=r.descriptionFields)!=null?Le:sd,N=cd(e.payload,S),Q=null;N&&(Q=f("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Q.textContent=N);let K=f("div","persona-flex-1 persona-min-w-0"),re=f("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),J=ue("clipboard","12px","currentColor",1.5);return J&&re.appendChild(J),re.addEventListener("click",async Ye=>{Ye.stopPropagation(),await dd(pd(e)),re.innerHTML="";let fe=ue("check","12px","currentColor",1.5);fe&&re.appendChild(fe),setTimeout(()=>{re.innerHTML="";let ee=ue("clipboard","12px","currentColor",1.5);ee&&re.appendChild(ee)},1500)}),C.appendChild(v),C.appendChild(x),U&&C.appendChild(U),C.appendChild(O),Q&&C.appendChild(Q),C.appendChild(K),C.appendChild(re),m.appendChild(C),d&&m.appendChild(ud(e,a,i)),m}}function Tl(e){var c,g;let{buffer:n,getFullHistory:t,onClose:r,config:o,plugins:s=[]}=e,a=(g=(c=o==null?void 0:o.features)==null?void 0:c.eventStream)!=null?g:{},i=s.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&o){let p=i.renderEventStreamView({config:o,events:n.getAll(),defaultRenderer:()=>d().element,onClose:r});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,y=f("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");hr(y,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},U=0,M=!1,O=0,S=0,N=!1,Q=null,K=!1,re=0,J=new Set,pe=new Map,Le="",Ye="",fe=null,ee,Y,V,j,ce;function he(){let Z=f("div","persona-flex persona-flex-col persona-flex-shrink-0"),z=f("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");hr(z,p==null?void 0:p.headerBar);let Pe=f("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",ee=f("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),ee.textContent="0";let Ce=f("div","persona-flex-1");Y=f("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Ie=f("option","");Ie.value="",Ie.textContent="All events",Y.appendChild(Ie),V=f("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),V.type="button",V.title="Copy All";let ut=ue("clipboard-copy","12px","currentColor",1.5);ut&&V.appendChild(ut);let ye=f("span","persona-text-xs");ye.textContent="Copy All",V.appendChild(ye),z.appendChild(Pe),z.appendChild(ee),z.appendChild(Ce),z.appendChild(Y),z.appendChild(V);let be=f("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");hr(be,p==null?void 0:p.searchBar);let $e=ue("search","14px","var(--persona-muted, #9ca3af)",1.5),de=f("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");$e&&de.appendChild($e),j=f("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),hr(j,p==null?void 0:p.searchInput),j.type="text",j.placeholder="Search event payloads...",ce=f("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),ce.type="button",ce.style.display="none";let bt=ue("x","12px","currentColor",2);return bt&&ce.appendChild(bt),be.appendChild(de),be.appendChild(j),be.appendChild(ce),Z.appendChild(z),Z.appendChild(be),Z}let gt,lt=s.find(Z=>Z.renderEventStreamToolbar);if(lt!=null&<.renderEventStreamToolbar&&o){let Z=lt.renderEventStreamToolbar({config:o,defaultRenderer:()=>he(),eventCount:n.getSize(),filteredCount:0,onFilterChange:z=>{C=z,X(),et()},onSearchChange:z=>{v=z,X(),et()}});gt=Z!=null?Z:he()}else gt=he();let mt=f("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");mt.style.display="none";let It=f("div","persona-flex-1 persona-min-h-0 persona-relative"),le=f("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");le.style.height="100%";let se=f("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");hr(se,p==null?void 0:p.scrollIndicator),se.style.display="none";let q=ue("arrow-down","12px","currentColor",2);q&&se.appendChild(q);let ne=f("span","");se.appendChild(ne);let oe=f("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");oe.style.display="none",It.appendChild(le),It.appendChild(oe),It.appendChild(se),y.setAttribute("tabindex","0"),y.appendChild(gt),y.appendChild(mt),y.appendChild(It);function Ee(){let Z=n.getAll(),z={};for(let ye of Z)z[ye.type]=(z[ye.type]||0)+1;let Pe=Object.keys(z).sort(),Ce=Pe.length!==x.length||!Pe.every((ye,be)=>ye===x[be]),Ie=!Ce&&Pe.some(ye=>z[ye]!==k[ye]),Be=Z.length!==Object.values(k).reduce((ye,be)=>ye+be,0);if(!Ce&&!Ie&&!Be||(x=Pe,k=z,!Y))return;let ut=Y.value;if(Y.options[0].textContent="All events",Ce){for(;Y.options.length>1;)Y.remove(1);for(let ye of Pe){let be=f("option","");be.value=ye,be.textContent=`${ye} (${z[ye]||0})`,Y.appendChild(be)}ut&&Pe.includes(ut)?Y.value=ut:ut&&(Y.value="",C="")}else for(let ye=1;ye<Y.options.length;ye++){let be=Y.options[ye];be.textContent=`${be.value} (${z[be.value]||0})`}}function Ke(){let Z=n.getAll();if(C&&(Z=Z.filter(z=>z.type===C)),v){let z=v.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(z)||Pe.payload.toLowerCase().includes(z))}return Z}function te(){return C!==""||v!==""}function X(){U=0,O=0,M=!1,se.style.display="none"}function He(Z){J.has(Z)?J.delete(Z):J.add(Z),fe=Z;let z=le.scrollTop,Pe=M;K=!0,M=!0,et(),le.scrollTop=z,M=Pe,K=!1}function Ve(){return le.scrollHeight-le.scrollTop-le.clientHeight<=50}function et(){S=Date.now(),N=!1,Ee();let Z=n.getEvictedCount();Z>0?(mt.textContent=`${Z.toLocaleString()} older events truncated`,mt.style.display=""):mt.style.display="none",m=Ke();let z=m.length,Pe=n.getSize()>0;ee&&(ee.textContent=String(n.getSize())),z===0&&Pe&&te()?(oe.textContent=v?`No events matching '${v}'`:"No events matching filter",oe.style.display="",le.style.display="none"):(oe.style.display="none",le.style.display=""),V&&(V.title=te()?`Copy Filtered (${z})`:"Copy All"),M&&z>U&&(O+=z-U,ne.textContent=`${O} new event${O===1?"":"s"}`,se.style.display=""),U=z;let Ce=n.getAll(),Ie=Ce.length>0?Ce[0].timestamp:0,Be=new Set(m.map(be=>be.id));for(let be of J)Be.has(be)||J.delete(be);let ut=C!==Le||v!==Ye,ye=pe.size===0&&m.length>0;if(ut||ye||m.length===0){le.innerHTML="",pe.clear();let be=document.createDocumentFragment();for(let $e=0;$e<m.length;$e++){let de=po(m[$e],$e,Ie,a,J,He,s,o);pe.set(m[$e].id,de),be.appendChild(de)}le.appendChild(be),Le=C,Ye=v,fe=null}else{if(fe!==null){let $e=pe.get(fe);if($e&&$e.parentNode===le){let de=m.findIndex(bt=>bt.id===fe);if(de>=0){let bt=po(m[de],de,Ie,a,J,He,s,o);le.insertBefore(bt,$e),$e.remove(),pe.set(fe,bt)}}fe=null}let be=new Set(m.map($e=>$e.id));for(let[$e,de]of pe)be.has($e)||(de.remove(),pe.delete($e));for(let $e=0;$e<m.length;$e++){let de=m[$e];if(!pe.has(de.id)){let bt=po(de,$e,Ie,a,J,He,s,o);pe.set(de.id,bt),le.appendChild(bt)}}}M||(le.scrollTop=le.scrollHeight)}function jt(){if(Date.now()-S>=od){Q!==null&&(cancelAnimationFrame(Q),Q=null),et();return}N||(N=!0,Q=requestAnimationFrame(()=>{Q=null,et()}))}let Dt=(Z,z)=>{if(!V)return;V.innerHTML="";let Pe=ue(Z,"12px","currentColor",1.5);Pe&&V.appendChild(Pe);let Ce=f("span","persona-text-xs");Ce.textContent="Copy All",V.appendChild(Ce),setTimeout(()=>{V.innerHTML="";let Ie=ue("clipboard-copy","12px","currentColor",1.5);Ie&&V.appendChild(Ie);let Be=f("span","persona-text-xs");Be.textContent="Copy All",V.appendChild(Be),V.disabled=!1},z)},ie=async()=>{if(V){V.disabled=!0;try{let Z;te()?Z=m:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let z=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(z,null,2)),Dt("check",1500)}catch{Dt("x",1500)}}},Ue=()=>{Y&&(C=Y.value,X(),et())},Te=()=>{!j||!ce||(ce.style.display=j.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=j.value,X(),et()},150))},tt=()=>{!j||!ce||(j.value="",v="",ce.style.display="none",E&&clearTimeout(E),X(),et())},_e=()=>{if(K)return;let Z=le.scrollTop,z=Z>re;re=Z,Ve()&&z?(M=!1,O=0,se.style.display="none"):Ve()||(M=!0)},Xe=Z=>{Z.deltaY<0&&(M=!0)},Wt=()=>{le.scrollTop=le.scrollHeight,M=!1,O=0,se.style.display="none"},Rt=Z=>{let z=Z.target;if(!z||z.closest("button"))return;let Pe=z.closest("[data-event-id]");if(!Pe)return;let Ce=Pe.getAttribute("data-event-id");Ce&&He(Ce)},Mt=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),j==null||j.focus(),j==null||j.select();return}Z.key==="Escape"&&(j&&document.activeElement===j?(tt(),j.blur(),y.focus()):r&&r())};V&&V.addEventListener("click",ie),Y&&Y.addEventListener("change",Ue),j&&j.addEventListener("input",Te),ce&&ce.addEventListener("click",tt),le.addEventListener("scroll",_e),le.addEventListener("wheel",Xe,{passive:!0}),le.addEventListener("click",Rt),se.addEventListener("click",Wt),y.addEventListener("keydown",Mt);function H(){E&&clearTimeout(E),Q!==null&&(cancelAnimationFrame(Q),Q=null),N=!1,pe.clear(),V&&V.removeEventListener("click",ie),Y&&Y.removeEventListener("change",Ue),j&&j.removeEventListener("input",Te),ce&&ce.removeEventListener("click",tt),le.removeEventListener("scroll",_e),le.removeEventListener("wheel",Xe),le.removeEventListener("click",Rt),se.removeEventListener("click",Wt),y.removeEventListener("keydown",Mt)}return{element:y,update:jt,destroy:H}}}var Ml=e=>{let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",t=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",a=document.createElement("div");a.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.backgroundColor="var(--persona-bg, #ffffff)",a.style.cursor="pointer",a.tabIndex=0,a.setAttribute("role","button"),a.setAttribute("aria-label",`Open ${n} in artifact panel`),t&&a.setAttribute("data-open-artifact",t);let i=document.createElement("div");i.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.color="var(--persona-muted, #9ca3af)",i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let c=document.createElement("div");c.className="persona-truncate persona-text-sm persona-font-medium",c.style.color="var(--persona-text, #1f2937)",c.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #3b82f6)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let y=document.createElement("span");y.textContent=`Generating ${s.toLowerCase()}...`,g.appendChild(y)}else g.textContent=s;if(d.append(c,g),a.append(i,d),r==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${n}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",t),a.append(p)}return a};var uo=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}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(([t,r])=>{this.register(t,r)})}},Fn=new uo;Fn.register("PersonaArtifactCard",Ml);function gd(e){var o;let n=f("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=f("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let r=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),n.appendChild(t),n.appendChild(r),n}function Qr(e,n,t=""){let r=f("button",`persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-p-1 persona-text-persona-primary hover:persona-bg-persona-container ${t}`);r.type="button",r.setAttribute("aria-label",n),r.title=n;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function es(e,n,t){let r=f("button",`persona-artifact-doc-icon-btn ${t}`.trim());r.type="button",r.setAttribute("aria-label",n),r.title=n;let o=ue(e,16,"currentColor",2);return o&&r.appendChild(o),r}function kl(e){let n=f("button","persona-artifact-doc-copy-btn");n.type="button",n.setAttribute("aria-label","Copy"),n.title="Copy";let t=ue("copy",e?14:16,"currentColor",2);if(t&&n.appendChild(t),e){let r=f("span","persona-artifact-doc-copy-label");r.textContent="Copy",n.appendChild(r)}return n}function md(){let e=f("button","persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn");e.type="button",e.setAttribute("aria-label","More copy options"),e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false");let n=ue("chevron-down",14,"currentColor",2);return n&&e.appendChild(n),e}function Ll(e,n){var mt,It,le,se;let t=(It=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:It.layout,o=((le=t==null?void 0:t.toolbarPreset)!=null?le:"default")==="document",s=(se=t==null?void 0:t.panePadding)==null?void 0:se.trim(),a=e.markdown?ir(e.markdown):null,i=q=>a?a(q):Dr(q),d=typeof document!="undefined"?f("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,c=()=>{d==null||d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")};d&&d.addEventListener("click",()=>{var q;c(),(q=n.onDismiss)==null||q.call(n)});let g=f("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");o&&g.classList.add("persona-artifact-pane-document");let p=f("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");o&&p.classList.add("persona-artifact-toolbar-document");let y=f("span","persona-text-xs persona-font-medium persona-truncate");y.textContent="Artifacts";let m=f("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");m.type="button",m.textContent="Close",m.setAttribute("aria-label","Close artifacts panel"),m.addEventListener("click",()=>{var q;c(),(q=n.onDismiss)==null||q.call(n)});let C="rendered",v=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),E=o?es("eye","Rendered view","persona-artifact-view-btn"):Qr("eye","Rendered view",""),x=o?es("code-2","Source","persona-artifact-code-btn"):Qr("code-2","Source",""),k=f("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),U=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,M=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,O=t==null?void 0:t.documentToolbarCopyMenuItems,S=!!(M&&O&&O.length>0),N=null,Q,K=null,re=null;if(o&&(U||M)&&!S){if(Q=kl(U),M){let q=ue("chevron-down",14,"currentColor",2);q&&Q.appendChild(q)}}else if(o&&S){N=f("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=kl(U),K=md(),N.append(Q,K),re=f("div","persona-artifact-doc-copy-menu persona-absolute persona-right-0 persona-top-full persona-z-20 persona-mt-1 persona-min-w-[10rem] persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-py-1 persona-shadow-md persona-hidden"),N.appendChild(re);for(let q of O){let ne=f("button","persona-block persona-w-full persona-text-left persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary hover:persona-bg-persona-container");ne.type="button",ne.textContent=q.label,ne.dataset.copyMenuId=q.id,re.appendChild(ne)}}else o?Q=es("copy","Copy",""):Q=Qr("copy","Copy","");let J=o?es("refresh-cw","Refresh",""):Qr("refresh-cw","Refresh",""),pe=o?es("x","Close",""):Qr("x","Close",""),Le=()=>{var Ke,te,X;let q=(Ke=j.find(He=>He.id===ce))!=null?Ke:j[j.length-1],ne=(te=q==null?void 0:q.id)!=null?te:null,oe=(q==null?void 0:q.artifactType)==="markdown"&&(X=q.markdown)!=null?X:"",Ee=q?JSON.stringify({component:q.component,props:q.props},null,2):"";return{markdown:oe,jsonPayload:Ee,id:ne}},Ye=async()=>{var Ke;let{markdown:q,jsonPayload:ne}=Le(),oe=(Ke=j.find(te=>te.id===ce))!=null?Ke:j[j.length-1],Ee=(oe==null?void 0:oe.artifactType)==="markdown"?q:oe?ne:"";try{await navigator.clipboard.writeText(Ee)}catch{}};if(Q.addEventListener("click",async()=>{let q=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(q&&S){let{markdown:ne,jsonPayload:oe,id:Ee}=Le();try{await q({actionId:"primary",artifactId:Ee,markdown:ne,jsonPayload:oe})}catch{}return}await Ye()}),K&&re){let q=()=>{re.classList.add("persona-hidden"),K.setAttribute("aria-expanded","false")};K.addEventListener("click",ne=>{ne.stopPropagation(),re.classList.contains("persona-hidden")?(re.classList.remove("persona-hidden"),K.setAttribute("aria-expanded","true")):q()}),typeof document!="undefined"&&document.addEventListener("click",q),re.addEventListener("click",async ne=>{let oe=ne.target.closest("button[data-copy-menu-id]");if(!(oe!=null&&oe.dataset.copyMenuId))return;ne.stopPropagation();let Ee=oe.dataset.copyMenuId,{markdown:Ke,jsonPayload:te,id:X}=Le(),He=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{He?await He({actionId:Ee,artifactId:X,markdown:Ke,jsonPayload:te}):Ee==="markdown"||Ee==="md"?await navigator.clipboard.writeText(Ke):Ee==="json"||Ee==="source"?await navigator.clipboard.writeText(te):await navigator.clipboard.writeText(Ke||te)}catch{}q()})}J.addEventListener("click",async()=>{var q;try{await((q=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:q.call(t))}catch{}gt()}),pe.addEventListener("click",()=>{var q;c(),(q=n.onDismiss)==null||q.call(n)});let fe=()=>{o&&(E.setAttribute("aria-pressed",C==="rendered"?"true":"false"),x.setAttribute("aria-pressed",C==="source"?"true":"false"))};E.addEventListener("click",()=>{C="rendered",fe(),gt()}),x.addEventListener("click",()=>{C="source",fe(),gt()});let ee=f("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(p.replaceChildren(),v.append(E,x),N?k.append(N,J,pe):k.append(Q,J,pe),p.append(v,ee,k),fe()):(p.appendChild(y),p.appendChild(m)),s&&(p.style.paddingLeft=s,p.style.paddingRight=s);let Y=f("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),V=f("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Y.style.paddingLeft=s,Y.style.paddingRight=s,V.style.padding=s),g.appendChild(p),g.appendChild(Y),g.appendChild(V);let j=[],ce=null,he=!1,gt=()=>{var Ee,Ke,te,X;let q=o&&j.length<=1;Y.classList.toggle("persona-hidden",q),Y.replaceChildren();for(let He of j){let Ve=f("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary hover:persona-bg-persona-container");Ve.type="button",Ve.textContent=He.title||He.id.slice(0,8),He.id===ce&&Ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ve.addEventListener("click",()=>n.onSelect(He.id)),Y.appendChild(Ve)}V.replaceChildren();let ne=ce&&j.find(He=>He.id===ce)||j[j.length-1];if(!ne)return;if(o){let He=ne.artifactType==="markdown"?"MD":(Ee=ne.component)!=null?Ee:"Component",et=(ne.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";ee.textContent=`${et} \xB7 ${He}`}else y.textContent="Artifacts";if(ne.artifactType==="markdown"){if(o&&C==="source"){let Ve=f("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ve.textContent=(Ke=ne.markdown)!=null?Ke:"",V.appendChild(Ve);return}let He=f("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");He.innerHTML=i((te=ne.markdown)!=null?te:""),V.appendChild(He);return}let oe=ne.component?Fn.get(ne.component):void 0;if(oe){let Ve={message:{id:ne.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let et=oe((X=ne.props)!=null?X:{},Ve);if(et){V.appendChild(et);return}}catch{}}V.appendChild(gd(ne))},lt=()=>{var ne;let q=j.length>0;if(g.classList.toggle("persona-hidden",!q),d){let oe=typeof g.closest=="function"?g.closest("#persona-root"):null,Ke=((ne=oe==null?void 0:oe.classList.contains("persona-artifact-narrow-host"))!=null?ne:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;q&&Ke&&he?(d.classList.remove("persona-hidden"),g.classList.add("persona-artifact-drawer-open")):(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open"))}};return{element:g,backdrop:d,update(q){var ne,oe,Ee;j=q.artifacts,ce=(Ee=(oe=q.selectedId)!=null?oe:(ne=q.artifacts[q.artifacts.length-1])==null?void 0:ne.id)!=null?Ee:null,j.length>0&&(he=!0),gt(),lt()},setMobileOpen(q){he=q,!q&&d?(d.classList.add("persona-hidden"),g.classList.remove("persona-artifact-drawer-open")):lt()}}}function on(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function Pl(e,n){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!on(n))return;let t=(a=(s=n.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),o=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function fd(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function Ls(e,n){var d,c,g,p,y,m,C,v,E,x;if(!on(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),fd(e),Pl(e,n);return}let t=(c=(d=n.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(y=t==null?void 0:t.paneMaxWidth)!=null?y:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Pl(e,n)}var Il=["panel","seamless"];function Ps(e,n){var i,d,c,g,p,y;for(let m of Il)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!on(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",o=Il.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((y=t.unifiedSplitOuterRadius)==null?void 0:y.trim())||s;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Wl(e,n){var t,r,o;return!n||!on(e)?!1:((o=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function hd(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function yd(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function bd(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function xd(e,n,t,r){let o=e-r-2*n-t;return Math.max(0,o)}function Rl(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Hl(e,n,t,r,o,s){let a=hd(o,200),i=xd(n,t,r,200);i=Math.max(a,i);let d=yd(s);return d!==null&&(i=Math.min(i,d)),bd(e,a,i)}var Bl={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"}},go=(e,n,t,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var C,v,E;if(s.dataset.enhanced==="true")return;let a=(C=s.dataset.tvForm)!=null?C:"init";s.dataset.enhanced="true";let i=(v=Bl[a])!=null?v:Bl.init;s.classList.add("persona-form-card","persona-space-y-4");let d=f("div","persona-space-y-1"),c=f("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=f("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var S,N;let k=f("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${x.name}`;let U=f("span","persona-text-xs persona-font-medium persona-text-persona-muted");U.textContent=x.label,k.appendChild(U);let M=(S=x.type)!=null?S:"text",O;M==="textarea"?(O=document.createElement("textarea"),O.rows=3):(O=document.createElement("input"),O.type=M),O.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",O.id=`${n.id}-${a}-${x.name}`,O.name=x.name,O.placeholder=(N=x.placeholder)!=null?N:"",x.required&&(O.required=!0),k.appendChild(O),g.appendChild(k)});let p=f("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),y=f("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=f("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(y),p.appendChild(m),g.appendChild(p),s.replaceChildren(d,g),g.addEventListener("submit",async x=>{var O,S;x.preventDefault();let k=(O=t.formEndpoint)!=null?O:"/form",U=new FormData(g),M={};U.forEach((N,Q)=>{M[Q]=N}),M.type=a,m.disabled=!0,y.textContent="Submitting\u2026";try{let N=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!N.ok)throw new Error(`Form submission failed (${N.status})`);let Q=await N.json();y.textContent=(S=Q.message)!=null?S:"Thanks! We'll be in touch soon.",Q.success&&Q.nextPrompt&&await r.sendMessage(String(Q.nextPrompt))}catch(N){y.textContent=N instanceof Error?N.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mo=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,o;return((r=t.priority)!=null?r:0)-((o=n.priority)!=null?o:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(s=>s.id));return[...t.filter(s=>!r.has(s.id)),...n].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Is=new mo;var $l={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"},Fl={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"},yt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:$l,darkTheme:Fl,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px",collapsedWidth:"72px"},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 fo(e){var n,t,r,o,s,a,i,d,c,g,p,y,m,C,v,E,x,k,U,M,O;return e?{...yt,...e,theme:{...yt.theme,...e.theme},darkTheme:{...yt.darkTheme,...e.darkTheme},launcher:{...yt.launcher,...e.launcher,dock:{...(n=yt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=yt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...yt.copy,...e.copy},sendButton:{...yt.sendButton,...e.sendButton},statusIndicator:{...yt.statusIndicator,...e.statusIndicator},voiceRecognition:{...yt.voiceRecognition,...e.voiceRecognition},features:(()=>{var K,re;let S=(K=yt.features)==null?void 0:K.artifacts,N=(re=e.features)==null?void 0:re.artifacts,Q=S===void 0&&N===void 0?void 0:{...S,...N,layout:{...S==null?void 0:S.layout,...N==null?void 0:N.layout}};return{...yt.features,...e.features,...Q!==void 0?{artifacts:Q}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:yt.suggestionChips,suggestionChipsConfig:{...yt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...yt.layout,...e.layout,header:{...(a=yt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=yt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=yt.layout)==null?void 0:g.messages)==null?void 0:p.avatar,...(m=(y=e.layout)==null?void 0:y.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=yt.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(x=(E=e.layout)==null?void 0:E.messages)==null?void 0:x.timestamp}},slots:{...(k=yt.layout)==null?void 0:k.slots,...(U=e.layout)==null?void 0:U.slots}},markdown:{...yt.markdown,...e.markdown,options:{...(M=yt.markdown)==null?void 0:M.options,...(O=e.markdown)==null?void 0:O.options}},messageActions:{...yt.messageActions,...e.messageActions}}:yt}var Nl=()=>{let e=new Map,n=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>t(o,s)),t=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:n,off:t,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var vd=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Cd=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let o=t;o<n.length;o+=1){let s=n[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return n.slice(t,o+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=vd(e),t=Cd(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},ho=e=>typeof e=="string"?e:e==null?"":String(e),yr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ho(e.payload.text)},messageAndClick:(e,n)=>{var o;if(e.type!=="message_and_click")return;let t=e.payload,r=ho(t.element);if(r&&((o=n.document)!=null&&o.querySelector)){let s=n.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:ho(t.text)}}},Ol=e=>Array.isArray(e)?e.map(n=>String(n)):[],Rs=e=>{let n=new Set(Ol(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Ol(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||n.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&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 i=a?e.parsers.reduce((c,g)=>c||(g==null?void 0:g({text:a,message:s.message}))||null,null):null;if(!i)return null;n.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let g=()=>{e.emit("action:resubmit",d)},p=c(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:g});if(!p)continue;if(p.handled){let y=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:y,resubmit:p.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var wd=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Sd=e=>e.map(n=>({...n,streaming:!1})),yo=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?wd(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let o={...t,messages:t.messages?Sd(t.messages):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Ad,STR as Ed,OBJ as Td}from"partial-json";function Md(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function kd(e,n){if(!Md(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function bo(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let o=Ad(t,Ed|Td),s=kd(o,t);s&&(e=s)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function Ld(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function xo(e,n){let{config:t,message:r,onPropsUpdate:o}=n,s=Fn.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:t,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Pd(){let e=bo();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function vo(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Co(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var Id=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function wo(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Id}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let p=null,y=document.createElement("div");y.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=o,m.appendChild(v),y.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let S=1;S<=5;S++){let N=document.createElement("button");N.type="button",N.className="persona-feedback-rating-btn persona-feedback-star-btn",N.setAttribute("role","radio"),N.setAttribute("aria-checked","false"),N.setAttribute("aria-label",`${S} star${S>1?"s":""}: ${c[S-1]}`),N.title=c[S-1],N.dataset.rating=String(S),N.innerHTML=`
|
|
17
17
|
<svg class="persona-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
|
-
`,N.addEventListener("click",()=>{p=S,x.forEach((Z,K)=>{let re=K<S;Z.classList.toggle("selected",re),Z.setAttribute("aria-checked",K===S-1?"true":"false")})}),x.push(N),E.appendChild(N)}y.appendChild(E);let k=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),S.appendChild(k),y.appendChild(S)}let U=document.createElement("div");U.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{n==null||n(),g.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let S=(k==null?void 0:k.value.trim())||void 0;await t(p,S),g.remove()}catch(S){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),U.appendChild(M),U.appendChild(O),y.appendChild(U),g.appendChild(y),g}function So(e){let{onSubmit:t,onDismiss:n,title:r="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:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let y=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,C.appendChild(E),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let U=document.createElement("span");U.className="persona-feedback-label-low",U.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(U),k.appendChild(M);let O=document.createElement("div");O.className="persona-feedback-numbers";let S=[];for(let z=0;z<=10;z++){let pe=document.createElement("button");pe.type="button",pe.className="persona-feedback-rating-btn persona-feedback-number-btn",pe.setAttribute("role","radio"),pe.setAttribute("aria-checked","false"),pe.setAttribute("aria-label",`Rating ${z} out of 10`),pe.textContent=String(z),pe.dataset.rating=String(z),z<=6?pe.classList.add("persona-feedback-detractor"):z<=8?pe.classList.add("persona-feedback-passive"):pe.classList.add("persona-feedback-promoter"),pe.addEventListener("click",()=>{y=z,S.forEach((Le,Ye)=>{Le.classList.toggle("selected",Ye===z),Le.setAttribute("aria-checked",Ye===z?"true":"false")})}),S.push(pe),O.appendChild(pe)}x.appendChild(k),x.appendChild(O),m.appendChild(x);let N=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),z.appendChild(N),m.appendChild(z)}let Z=document.createElement("div");Z.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{n==null||n(),p.remove()});let re=document.createElement("button");return re.type="button",re.className="persona-feedback-btn persona-feedback-btn-submit",re.textContent=a,re.addEventListener("click",async()=>{if(y===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}re.disabled=!0,re.textContent="Submitting...";try{let z=(N==null?void 0:N.value.trim())||void 0;await t(y,z),p.remove()}catch(z){re.disabled=!1,re.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),Z.appendChild(K),Z.appendChild(re),m.appendChild(Z),p.appendChild(m),p}var br="persona-chat-history",Wd=30*1e3,Rd={"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 Hd(e){var r,o,s;if(!e)return[];let t=[],n=Array.from((r=e.items)!=null?r:[]);for(let a of n){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){t.push(i);continue}let d=(o=Rd[i.type])!=null?o:"png";t.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(t.length>0)return t;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&t.push(a);return t}function Bd(e){var t,n,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(t=e.storage)!=null?t:"session",keyPrefix:(n=e.keyPrefix)!=null?n:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function $d(e){try{let t=e==="local"?localStorage:sessionStorage,n="__persist_test__";return t.setItem(n,"1"),t.removeItem(n),t}catch{return null}}var Ao=e=>!e||typeof e!="object"?{}:{...e},Dl=e=>e.map(t=>({...t,streaming:!1})),_l=(e,t,n)=>{let r=e!=null&&e.markdown?ir(e.markdown):null;return o=>{var i,d,c;let s=(i=o.text)!=null?i:"",a=(d=o.message.rawContent)!=null?d:null;if(t){let g=t.process({text:s,raw:a!=null?a:s,message:o.message,streaming:o.streaming});g!==null&&(s=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&n&&n())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(c=a!=null?a:o.text)!=null?c:""}):r?r(s):Dr(s)}},Eo=(e,t,n)=>{var ae,Se,nt,Mt,wt,Wt,kt,rt,at,Et,it,Rt,Jt,rn,Wo,Ro,Ho,Bo,$o,Fo,No,Oo,Do,_o,jo,Vo,qo,Uo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ea,ta;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=fo(t),o=Is.getForInstance(r.plugins);r.components&&Fn.registerAll(r.components);let s=Nl(),a=(ae=r.storageAdapter)!=null?ae:yo(),i={},d=null,c=l=>{if(r.onStateLoaded)try{return r.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return c(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=c(u);h.metadata&&(i=Ao(h.metadata)),(Se=h.messages)!=null&&Se.length&&(r={...r,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=c({messages:[],metadata:{}});(nt=l.messages)!=null&&nt.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>i,p=l=>{var h;i=(h=l({...i}))!=null?h:{},kr()},y=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick],C=Rs({parsers:y,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(Mt=r.launcher)==null?void 0:Mt.enabled)!=null?wt:!0,E=(kt=(Wt=r.launcher)==null?void 0:Wt.autoExpand)!=null?kt:!1,x=(rt=r.autoFocusInput)!=null?rt:!1,k=E,U=v,M=(Et=(at=r.layout)==null?void 0:at.header)==null?void 0:Et.layout,O=!1,S=v?E:!0,N=!1,Z=null,K=()=>{N=!0,Z&&clearTimeout(Z),Z=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},re=_l(r,C,K),z=(Rt=(it=r.features)==null?void 0:it.showReasoning)!=null?Rt:!0,pe=(rn=(Jt=r.features)==null?void 0:Jt.showToolCalls)!=null?rn:!0,Le=(Ro=(Wo=r.features)==null?void 0:Wo.showEventStreamToggle)!=null?Ro:!1,fe=`${(Bo=typeof r.persistState=="object"?(Ho=r.persistState)==null?void 0:Ho.keyPrefix:void 0)!=null?Bo:"persona-"}event-stream`,Q=Le?new Zr(fe):null,Y=(No=(Fo=($o=r.features)==null?void 0:$o.eventStream)==null?void 0:Fo.maxEvents)!=null?No:2e3,V=Le?new Gr(Y,Q):null,j=null,ce=!1,he=null,gt=0;Q==null||Q.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let lt={onCopy:l=>{var u,h;s.emit("message:copy",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.id,"copy").catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.messageId,l.type).catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},mt=(Oo=r.statusIndicator)!=null?Oo:{},Pt=l=>{var u,h,A,L;return l==="idle"?(u=mt.idleText)!=null?u:_t.idle:l==="connecting"?(h=mt.connectingText)!=null?h:_t.connecting:l==="connected"?(A=mt.connectedText)!=null?A:_t.connected:l==="error"?(L=mt.errorText)!=null?L:_t.error:_t[l]},{wrapper:le,panel:se}=bl(r),q=xl(r,v),{container:ne,body:oe,messagesWrapper:Ee,suggestions:Ke,textarea:ee,sendButton:X,sendButtonWrapper:He,composerForm:Ve,statusText:et,introTitle:jt,introSubtitle:Dt,closeButton:ie,iconHolder:Ue,headerTitle:Te,headerSubtitle:tt,header:_e,footer:Xe,actionsRow:$t,leftActions:Ft,rightActions:It}=q,H=q.micButton,te=q.micButtonWrapper,J=q.attachmentButton,We=q.attachmentButtonWrapper,Ce=q.attachmentInput,Pe=q.attachmentPreviewsContainer,Be=null,ut=null,ye=o.find(l=>l.renderHeader);if(ye!=null&&ye.renderHeader){let l=ye.renderHeader({config:r,defaultRenderer:()=>{let u=$n({config:r,showClose:v});return ur(ne,u,r),u.header},onClose:()=>ft(!1,"user")});if(l){let u=ne.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),_e=l)}}let be=()=>{var u,h,A,L;if(!V)return;if(ce=!0,!j&&V&&(j=Tl({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>$e(),config:r,plugins:o})),j&&(oe.style.display="none",(u=Xe.parentNode)==null||u.insertBefore(j.element,Xe),j.update()),de){de.classList.remove("persona-text-persona-muted"),de.classList.add("persona-text-persona-accent"),de.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let $=(L=(A=(h=r.features)==null?void 0:h.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;$&&$.split(/\s+/).forEach(R=>R&&de.classList.add(R))}let l=()=>{if(!ce)return;let $=Date.now();$-gt>=200&&(j==null||j.update(),gt=$),he=requestAnimationFrame(l)};gt=0,he=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},$e=()=>{var l,u,h;if(ce){if(ce=!1,j&&j.element.remove(),oe.style.display="",de){de.classList.remove("persona-text-persona-accent"),de.classList.add("persona-text-persona-muted"),de.style.boxShadow="";let A=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&de.classList.remove(L))}he!==null&&(cancelAnimationFrame(he),he=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},de=null;if(Le){let l=(_o=(Do=r.features)==null?void 0:Do.eventStream)==null?void 0:_o.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");de=f("button",u),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let h=ue("activity","18px","currentColor",1.5);h&&de.appendChild(h);let A=q.clearChatButtonWrapper,L=q.closeButtonWrapper,$=A||L;$&&$.parentNode===_e?_e.insertBefore(de,$):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}let bt=l=>{var A,L,$;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=l.querySelector(".persona-attachment-previews");if(!h){h=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let R=l.querySelector("[data-persona-composer-form]");R!=null&&R.parentNode?R.parentNode.insertBefore(h,R):l.insertBefore(h,l.firstChild)}if(!l.querySelector('input[type="file"]')){let R=f("input");R.type="file",R.accept=((A=u.allowedTypes)!=null?A:Mn).join(","),R.multiple=((L=u.maxFiles)!=null?L:4)>1,R.style.display="none",R.setAttribute("aria-label",($=u.buttonTooltipText)!=null?$:"Attach files"),l.appendChild(R)}},Gt=o.find(l=>l.renderComposer);if(Gt!=null&&Gt.renderComposer){let l=r.composer,u=Gt.renderComposer({config:r,defaultRenderer:()=>Yr({config:r}).footer,onSubmit:h=>{W&&!W.isStreaming()&&W.sendMessage(h)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h}},onVoiceToggle:((jo=r.voiceRecognition)==null?void 0:jo.enabled)===!0?()=>{ut==null||ut()}:void 0});u&&(Xe.replaceWith(u),Xe=u)}let pn=l=>{let u=l.querySelector("[data-persona-composer-form]"),h=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");u&&(Ve=u),h&&(ee=h),A&&(X=A),L&&(H=L,te=L.parentElement),$&&(et=$);let R=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");R&&(Ke=R);let D=l.querySelector(".persona-attachment-button");D&&(J=D,We=D.parentElement),Ce=l.querySelector('input[type="file"]'),Pe=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&($t=B)};bt(Xe),pn(Xe);let un=(Vo=r.layout)==null?void 0:Vo.contentMaxWidth;un&&Ve&&(Ve.style.maxWidth=un,Ve.style.marginLeft="auto",Ve.style.marginRight="auto"),(qo=r.attachments)!=null&&qo.enabled&&Ce&&Pe&&(Be=pr.fromConfig(r.attachments),Be.setPreviewsContainer(Pe),Ce.addEventListener("change",l=>{let u=l.target;Be==null||Be.handleFileSelect(u.files),u.value=""})),(()=>{var A,L;let l=(L=(A=r.layout)==null?void 0:A.slots)!=null?L:{},u=$=>{switch($){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ee;case"footer-top":return Ke;case"composer":return Ve;case"footer-bottom":return et;default:return null}},h=($,R)=>{var D;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")_e.insertBefore(R,_e.firstChild);else if($==="header-right")_e.appendChild(R);else{let B=_e.querySelector(".persona-flex-col");B?(D=B.parentNode)==null||D.insertBefore(R,B.nextSibling):_e.appendChild(R)}break;case"body-top":{let B=oe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(R):oe.insertBefore(R,oe.firstChild);break}case"body-bottom":oe.appendChild(R);break;case"footer-top":Ke.replaceWith(R);break;case"footer-bottom":et.replaceWith(R);break;default:break}};for(let[$,R]of Object.entries(l))if(R)try{let D=R({config:r,defaultContent:()=>u($)});D&&h($,D)}catch(D){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,D)}})();let Ln=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let A=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-bubble-type");$==="reasoning"?(mr.has(L)?mr.delete(L):mr.add(L),Sl(L,A)):$==="tool"&&(fr.has(L)?fr.delete(L):fr.add(L),Al(L,A,r))};Ee.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))}),Ee.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))});let Xn=new Map;Ee.addEventListener("click",l=>{var R;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let $=h.getAttribute("data-action");if($==="copy"){let B=W.getMessages().find(me=>me.id===L);if(B&<.onCopy){let me=B.content||"";navigator.clipboard.writeText(me).then(()=>{h.classList.add("persona-message-action-success");let ge=ue("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Me=ue("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),lt.onCopy(B)}}else if($==="upvote"||$==="downvote")if(((R=Xn.get(L))!=null?R:null)===$)Xn.delete(L),h.classList.remove("persona-message-action-active");else{let me=$==="upvote"?"downvote":"upvote",ge=A.querySelector(`[data-action="${me}"]`);ge&&ge.classList.remove("persona-message-action-active"),Xn.set(L,$),h.classList.add("persona-message-action-active");let je=W.getMessages().find(xe=>xe.id===L);je&<.onFeedback&<.onFeedback({type:$,messageId:je.id,message:je})}}),Ee.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest(".vanilla-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-approval-action");if(!$)return;let R=$==="approve"?"approved":"denied",B=W.getMessages().find(ge=>ge.id===L);if(!(B!=null&&B.approval))return;let me=A.querySelector("[data-approval-buttons]");me&&me.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),W.resolveApproval(B.approval,R)});let Ge=null,gn=null,Pn={artifacts:[],selectedId:null},an=!1,vr={current:null};Ee.addEventListener("click",l=>{var ge,Me;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.getAttribute("data-download-artifact");if(!A)return;let L=W.getArtifactById(A),$=L==null?void 0:L.markdown,R=(L==null?void 0:L.title)||"artifact";if(!$){let je=h.closest("[data-open-artifact]"),xe=je==null?void 0:je.closest("[data-message-id]"),P=xe==null?void 0:xe.getAttribute("data-message-id");if(P){let Ae=W.getMessages().find(F=>F.id===P);if(Ae!=null&&Ae.rawContent)try{let F=JSON.parse(Ae.rawContent);$=(ge=F==null?void 0:F.props)==null?void 0:ge.markdown,R=((Me=F==null?void 0:F.props)==null?void 0:Me.title)||R}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),B=URL.createObjectURL(D),me=document.createElement("a");me.href=B,me.download=`${R}.md`,me.click(),URL.revokeObjectURL(B)}),Ee.addEventListener("click",l=>{let h=l.target.closest("[data-open-artifact]");if(!h)return;let A=h.getAttribute("data-open-artifact");A&&(l.preventDefault(),l.stopPropagation(),W.selectArtifact(A),fn())}),Ee.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let mn=null,dt=null,tn=null,vn=null,Cr=()=>{};function Gn(){vn==null||vn(),vn=null}let wr=()=>{var R;if(!mn||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((R=e.ownerDocument.defaultView)!=null?R:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){dt.style.removeProperty("position"),dt.style.removeProperty("left"),dt.style.removeProperty("top"),dt.style.removeProperty("bottom"),dt.style.removeProperty("width"),dt.style.removeProperty("z-index");return}let A=mn.firstElementChild;if(!A||A===dt)return;let L=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${L}px`,dt.style.zIndex="5";let $=A.offsetWidth-L/2;dt.style.left=`${Math.max(0,$)}px`},Nn=()=>{},fn=()=>{var h,A,L,$,R;if(!Ge||!on(r))return;Ls(e,r),Ps(e,r),Nn();let l=($=(L=(A=(h=r.features)==null?void 0:h.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?$:520,u=se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ge.update(Pn),an?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),(R=Ge.backdrop)==null||R.classList.add("persona-hidden")):Pn.artifacts.length>0&&(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)),Cr()};if(on(r)){se.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ne),Ge=Ll(r,{onSelect:h=>{var A;return(A=vr.current)==null?void 0:A.selectArtifact(h)},onDismiss:()=>{an=!0,fn()}}),Ge.element.classList.add("persona-hidden"),mn=u,u.appendChild(l),u.appendChild(Ge.element),Ge.backdrop&&se.appendChild(Ge.backdrop),se.appendChild(u),Cr=()=>{var A,L,$,R;if(!mn||!Ge)return;if(!((($=(L=(A=r.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:$.resizable)===!0)){tn==null||tn(),tn=null,Gn(),dt&&(dt.remove(),dt=null),Ge.element.style.removeProperty("width"),Ge.element.style.removeProperty("maxWidth");return}if(!dt){let D=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");D.setAttribute("role","separator"),D.setAttribute("aria-orientation","vertical"),D.setAttribute("aria-label","Resize artifacts panel"),D.tabIndex=0;let B=e.ownerDocument,me=(R=B.defaultView)!=null?R:window,ge=Me=>{var F,Ie;if(!Ge||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||me.innerWidth<=640)return;Me.preventDefault(),Gn();let je=Me.clientX,xe=Ge.element.getBoundingClientRect().width,P=(Ie=(F=r.features)==null?void 0:F.artifacts)==null?void 0:Ie.layout,ke=st=>{let Ze=mn.getBoundingClientRect().width,St=e.classList.contains("persona-artifact-appearance-seamless"),ct=St?0:Rl(mn,me),ot=St?0:D.getBoundingClientRect().width||6,Kt=xe-(st.clientX-je),ve=Hl(Kt,Ze,ct,ot,P==null?void 0:P.resizableMinWidth,P==null?void 0:P.resizableMaxWidth);Ge.element.style.width=`${ve}px`,Ge.element.style.maxWidth="none",wr()},Ae=()=>{B.removeEventListener("pointermove",ke),B.removeEventListener("pointerup",Ae),B.removeEventListener("pointercancel",Ae),vn=null;try{D.releasePointerCapture(Me.pointerId)}catch{}};vn=Ae,B.addEventListener("pointermove",ke),B.addEventListener("pointerup",Ae),B.addEventListener("pointercancel",Ae);try{D.setPointerCapture(Me.pointerId)}catch{}};D.addEventListener("pointerdown",ge),dt=D,mn.insertBefore(D,Ge.element),tn=()=>{D.removeEventListener("pointerdown",ge)}}if(dt){let D=Pn.artifacts.length>0&&!an;dt.classList.toggle("persona-hidden",!D),wr()}},Nn=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,Ie,st,Ze,St,ct;if(!v||!Ge||((ge=(me=r.launcher)==null?void 0:me.sidebarMode)!=null?ge:!1))return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,L=(xe=(je=r.launcher)==null?void 0:je.mobileFullscreen)!=null?xe:!0,$=(ke=(P=r.launcher)==null?void 0:P.mobileBreakpoint)!=null?ke:640;if(L&&A.innerWidth<=$||!Wl(r,v))return;let R=(Ie=(F=(Ae=r.launcher)==null?void 0:Ae.width)!=null?F:r.launcherWidth)!=null?Ie:"min(400px, calc(100vw - 24px))",D=(ct=(St=(Ze=(st=r.features)==null?void 0:st.artifacts)==null?void 0:Ze.layout)==null?void 0:St.expandedPanelWidth)!=null?ct:"min(720px, calc(100vw - 24px))";Pn.artifacts.length>0&&!an?(se.style.width=D,se.style.maxWidth=D):(se.style.width=R,se.style.maxWidth=R)},typeof ResizeObserver!="undefined"&&(gn=new ResizeObserver(()=>{fn()}),gn.observe(se))}else se.appendChild(ne);e.appendChild(le);let On=()=>{var Ze,St,ct,ot,Kt,ve,pt,Ht,sn,ms,fs,hs,Vs,qs,Tt,ys,Hr,Br,ar,bs,Bn;let l=Ut(r),u=(St=(Ze=r.launcher)==null?void 0:Ze.sidebarMode)!=null?St:!1,h=l||u||((ot=(ct=r.launcher)==null?void 0:ct.fullHeight)!=null?ot:!1),A=((Kt=r.launcher)==null?void 0:Kt.enabled)===!1,L=(ve=r.theme)!=null?ve:{},$=(pt=e.ownerDocument.defaultView)!=null?pt:window,R=(sn=(Ht=r.launcher)==null?void 0:Ht.mobileFullscreen)!=null?sn:!0,D=(fs=(ms=r.launcher)==null?void 0:ms.mobileBreakpoint)!=null?fs:640,B=$.innerWidth<=D,me=R&&B&&v,ge=(Vs=(hs=r.launcher)==null?void 0:hs.position)!=null?Vs:"bottom-left",Me=ge==="bottom-left"||ge==="top-left",je=u||me?"none":"1px solid var(--persona-persona-border)",xe=me?"none":u?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",P=u||me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=(qs=L.panelBorder)!=null?qs:je,Ae=(Tt=L.panelShadow)!=null?Tt:xe,F=(ys=L.panelBorderRadius)!=null?ys:P;if(e.style.cssText="",le.style.cssText="",se.style.cssText="",ne.style.cssText="",oe.style.cssText="",Xe.style.cssText="",me){le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),le.style.cssText=`
|
|
20
|
+
`,N.addEventListener("click",()=>{p=S,x.forEach((Q,K)=>{let re=K<S;Q.classList.toggle("selected",re),Q.setAttribute("aria-checked",K===S-1?"true":"false")})}),x.push(N),E.appendChild(N)}y.appendChild(E);let k=null;if(d){let S=document.createElement("div");S.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=s,k.rows=3,k.setAttribute("aria-label","Additional comments"),S.appendChild(k),y.appendChild(S)}let U=document.createElement("div");U.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),g.remove()});let O=document.createElement("button");return O.type="button",O.className="persona-feedback-btn persona-feedback-btn-submit",O.textContent=a,O.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}O.disabled=!0,O.textContent="Submitting...";try{let S=(k==null?void 0:k.value.trim())||void 0;await n(p,S),g.remove()}catch(S){O.disabled=!1,O.textContent=a,console.error("[CSAT Feedback] Failed to submit:",S)}}),U.appendChild(M),U.appendChild(O),y.appendChild(U),g.appendChild(y),g}function So(e){let{onSubmit:n,onDismiss:t,title:r="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:a="Submit",skipText:i="Skip",showComment:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let y=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=o,C.appendChild(E),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let U=document.createElement("span");U.className="persona-feedback-label-low",U.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(U),k.appendChild(M);let O=document.createElement("div");O.className="persona-feedback-numbers";let S=[];for(let J=0;J<=10;J++){let pe=document.createElement("button");pe.type="button",pe.className="persona-feedback-rating-btn persona-feedback-number-btn",pe.setAttribute("role","radio"),pe.setAttribute("aria-checked","false"),pe.setAttribute("aria-label",`Rating ${J} out of 10`),pe.textContent=String(J),pe.dataset.rating=String(J),J<=6?pe.classList.add("persona-feedback-detractor"):J<=8?pe.classList.add("persona-feedback-passive"):pe.classList.add("persona-feedback-promoter"),pe.addEventListener("click",()=>{y=J,S.forEach((Le,Ye)=>{Le.classList.toggle("selected",Ye===J),Le.setAttribute("aria-checked",Ye===J?"true":"false")})}),S.push(pe),O.appendChild(pe)}x.appendChild(k),x.appendChild(O),m.appendChild(x);let N=null;if(d){let J=document.createElement("div");J.className="persona-feedback-comment-container",N=document.createElement("textarea"),N.className="persona-feedback-comment",N.placeholder=s,N.rows=3,N.setAttribute("aria-label","Additional comments"),J.appendChild(N),m.appendChild(J)}let Q=document.createElement("div");Q.className="persona-feedback-actions";let K=document.createElement("button");K.type="button",K.className="persona-feedback-btn persona-feedback-btn-skip",K.textContent=i,K.addEventListener("click",()=>{t==null||t(),p.remove()});let re=document.createElement("button");return re.type="button",re.className="persona-feedback-btn persona-feedback-btn-submit",re.textContent=a,re.addEventListener("click",async()=>{if(y===null){O.classList.add("persona-feedback-shake"),setTimeout(()=>O.classList.remove("persona-feedback-shake"),500);return}re.disabled=!0,re.textContent="Submitting...";try{let J=(N==null?void 0:N.value.trim())||void 0;await n(y,J),p.remove()}catch(J){re.disabled=!1,re.textContent=a,console.error("[NPS Feedback] Failed to submit:",J)}}),Q.appendChild(K),Q.appendChild(re),m.appendChild(Q),p.appendChild(m),p}var br="persona-chat-history",Wd=30*1e3,Rd={"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 Hd(e){var r,o,s;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let d=(o=Rd[i.type])!=null?o:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((s=e.files)!=null?s:[]))a.type.startsWith("image/")&&n.push(a);return n}function Bd(e){var n,t,r,o,s,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(o=(r=e.persist)==null?void 0:r.openState)!=null?o:!0,voiceState:(a=(s=e.persist)==null?void 0:s.voiceState)!=null?a:!0,focusInput:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function $d(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var Ao=e=>!e||typeof e!="object"?{}:{...e},Dl=e=>e.map(n=>({...n,streaming:!1})),_l=(e,n,t)=>{let r=e!=null&&e.markdown?ir(e.markdown):null;return o=>{var i,d,c;let s=(i=o.text)!=null?i:"",a=(d=o.message.rawContent)!=null?d:null;if(n){let g=n.process({text:s,raw:a!=null?a:s,message:o.message,streaming:o.streaming});g!==null&&(s=g.text,g.persist||(o.message.__skipPersist=!0),g.resubmit&&!o.streaming&&t&&t())}return e!=null&&e.postprocessMessage?e.postprocessMessage({...o,text:s,raw:(c=a!=null?a:o.text)!=null?c:""}):r?r(s):Dr(s)}},Eo=(e,n,t)=>{var ae,Se,nt,kt,wt,Ht,Lt,rt,at,Et,it,Bt,Jt,rn,Wo,Ro,Ho,Bo,$o,Fo,No,Oo,Do,_o,jo,Vo,qo,Uo,zo,Jo,Ko,Yo,Xo,Go,Zo,Qo,ea,ta;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=fo(n),o=Is.getForInstance(r.plugins);r.components&&Fn.registerAll(r.components);let s=Nl(),a=(ae=r.storageAdapter)!=null?ae:yo(),i={},d=null,c=l=>{if(r.onStateLoaded)try{return r.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(u=>{let h=u!=null?u:{messages:[],metadata:{}};return c(h)});else{let u=l!=null?l:{messages:[],metadata:{}},h=c(u);h.metadata&&(i=Ao(h.metadata)),(Se=h.messages)!=null&&Se.length&&(r={...r,initialMessages:h.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=c({messages:[],metadata:{}});(nt=l.messages)!=null&&nt.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>i,p=l=>{var h;i=(h=l({...i}))!=null?h:{},kr()},y=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick],C=Rs({parsers:y,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(kt=r.launcher)==null?void 0:kt.enabled)!=null?wt:!0,E=(Lt=(Ht=r.launcher)==null?void 0:Ht.autoExpand)!=null?Lt:!1,x=(rt=r.autoFocusInput)!=null?rt:!1,k=E,U=v,M=(Et=(at=r.layout)==null?void 0:at.header)==null?void 0:Et.layout,O=!1,S=v?E:!0,N=!1,Q=null,K=()=>{N=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{N&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),N=!1)},1e4)},re=_l(r,C,K),J=(Bt=(it=r.features)==null?void 0:it.showReasoning)!=null?Bt:!0,pe=(rn=(Jt=r.features)==null?void 0:Jt.showToolCalls)!=null?rn:!0,Le=(Ro=(Wo=r.features)==null?void 0:Wo.showEventStreamToggle)!=null?Ro:!1,fe=`${(Bo=typeof r.persistState=="object"?(Ho=r.persistState)==null?void 0:Ho.keyPrefix:void 0)!=null?Bo:"persona-"}event-stream`,ee=Le?new Zr(fe):null,Y=(No=(Fo=($o=r.features)==null?void 0:$o.eventStream)==null?void 0:Fo.maxEvents)!=null?No:2e3,V=Le?new Gr(Y,ee):null,j=null,ce=!1,he=null,gt=0;ee==null||ee.open().then(()=>V==null?void 0:V.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let lt={onCopy:l=>{var u,h;s.emit("message:copy",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.id,"copy").catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onCopy)==null||h.call(u,l)},onFeedback:l=>{var u,h;s.emit("message:feedback",l),W!=null&&W.isClientTokenMode()&&W.submitMessageFeedback(l.messageId,l.type).catch(A=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(h=(u=r.messageActions)==null?void 0:u.onFeedback)==null||h.call(u,l)}},mt=(Oo=r.statusIndicator)!=null?Oo:{},It=l=>{var u,h,A,L;return l==="idle"?(u=mt.idleText)!=null?u:_t.idle:l==="connecting"?(h=mt.connectingText)!=null?h:_t.connecting:l==="connected"?(A=mt.connectedText)!=null?A:_t.connected:l==="error"?(L=mt.errorText)!=null?L:_t.error:_t[l]},{wrapper:le,panel:se}=bl(r),q=xl(r,v),{container:ne,body:oe,messagesWrapper:Ee,suggestions:Ke,textarea:te,sendButton:X,sendButtonWrapper:He,composerForm:Ve,statusText:et,introTitle:jt,introSubtitle:Dt,closeButton:ie,iconHolder:Ue,headerTitle:Te,headerSubtitle:tt,header:_e,footer:Xe,actionsRow:Wt,leftActions:Rt,rightActions:Mt}=q,H=q.micButton,Z=q.micButtonWrapper,z=q.attachmentButton,Pe=q.attachmentButtonWrapper,Ce=q.attachmentInput,Ie=q.attachmentPreviewsContainer,Be=null,ut=null,ye=o.find(l=>l.renderHeader);if(ye!=null&&ye.renderHeader){let l=ye.renderHeader({config:r,defaultRenderer:()=>{let u=$n({config:r,showClose:v});return ur(ne,u,r),u.header},onClose:()=>ft(!1,"user")});if(l){let u=ne.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),_e=l)}}let be=()=>{var u,h,A,L;if(!V)return;if(ce=!0,!j&&V&&(j=Tl({buffer:V,getFullHistory:()=>V.getAllFromStore(),onClose:()=>$e(),config:r,plugins:o})),j&&(oe.style.display="none",(u=Xe.parentNode)==null||u.insertBefore(j.element,Xe),j.update()),de){de.classList.remove("persona-text-persona-muted"),de.classList.add("persona-text-persona-accent"),de.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let $=(L=(A=(h=r.features)==null?void 0:h.eventStream)==null?void 0:A.classNames)==null?void 0:L.toggleButtonActive;$&&$.split(/\s+/).forEach(R=>R&&de.classList.add(R))}let l=()=>{if(!ce)return;let $=Date.now();$-gt>=200&&(j==null||j.update(),gt=$),he=requestAnimationFrame(l)};gt=0,he=requestAnimationFrame(l),s.emit("eventStream:opened",{timestamp:Date.now()})},$e=()=>{var l,u,h;if(ce){if(ce=!1,j&&j.element.remove(),oe.style.display="",de){de.classList.remove("persona-text-persona-accent"),de.classList.add("persona-text-persona-muted"),de.style.boxShadow="";let A=(h=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:h.toggleButtonActive;A&&A.split(/\s+/).forEach(L=>L&&de.classList.remove(L))}he!==null&&(cancelAnimationFrame(he),he=null),s.emit("eventStream:closed",{timestamp:Date.now()})}},de=null;if(Le){let l=(_o=(Do=r.features)==null?void 0:Do.eventStream)==null?void 0:_o.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");de=f("button",u),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let h=ue("activity","18px","currentColor",1.5);h&&de.appendChild(h);let A=q.clearChatButtonWrapper,L=q.closeButtonWrapper,$=A||L;$&&$.parentNode===_e?_e.insertBefore(de,$):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}let bt=l=>{var A,L,$;let u=r.attachments;if(!(u!=null&&u.enabled))return;let h=l.querySelector(".persona-attachment-previews");if(!h){h=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),h.style.display="none";let R=l.querySelector("[data-persona-composer-form]");R!=null&&R.parentNode?R.parentNode.insertBefore(h,R):l.insertBefore(h,l.firstChild)}if(!l.querySelector('input[type="file"]')){let R=f("input");R.type="file",R.accept=((A=u.allowedTypes)!=null?A:Mn).join(","),R.multiple=((L=u.maxFiles)!=null?L:4)>1,R.style.display="none",R.setAttribute("aria-label",($=u.buttonTooltipText)!=null?$:"Attach files"),l.appendChild(R)}},Gt=o.find(l=>l.renderComposer);if(Gt!=null&&Gt.renderComposer){let l=r.composer,u=Gt.renderComposer({config:r,defaultRenderer:()=>Yr({config:r}).footer,onSubmit:h=>{W&&!W.isStreaming()&&W.sendMessage(h)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:h=>{r.composer={...r.composer,selectedModelId:h}},onVoiceToggle:((jo=r.voiceRecognition)==null?void 0:jo.enabled)===!0?()=>{ut==null||ut()}:void 0});u&&(Xe.replaceWith(u),Xe=u)}let pn=l=>{let u=l.querySelector("[data-persona-composer-form]"),h=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),$=l.querySelector("[data-persona-composer-status]");u&&(Ve=u),h&&(te=h),A&&(X=A),L&&(H=L,Z=L.parentElement),$&&(et=$);let R=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");R&&(Ke=R);let D=l.querySelector(".persona-attachment-button");D&&(z=D,Pe=D.parentElement),Ce=l.querySelector('input[type="file"]'),Ie=l.querySelector(".persona-attachment-previews");let B=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");B&&(Wt=B)};bt(Xe),pn(Xe);let un=(Vo=r.layout)==null?void 0:Vo.contentMaxWidth;un&&Ve&&(Ve.style.maxWidth=un,Ve.style.marginLeft="auto",Ve.style.marginRight="auto"),(qo=r.attachments)!=null&&qo.enabled&&Ce&&Ie&&(Be=pr.fromConfig(r.attachments),Be.setPreviewsContainer(Ie),Ce.addEventListener("change",l=>{let u=l.target;Be==null||Be.handleFileSelect(u.files),u.value=""})),(()=>{var A,L;let l=(L=(A=r.layout)==null?void 0:A.slots)!=null?L:{},u=$=>{switch($){case"body-top":return ne.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return Ee;case"footer-top":return Ke;case"composer":return Ve;case"footer-bottom":return et;default:return null}},h=($,R)=>{var D;switch($){case"header-left":case"header-center":case"header-right":if($==="header-left")_e.insertBefore(R,_e.firstChild);else if($==="header-right")_e.appendChild(R);else{let B=_e.querySelector(".persona-flex-col");B?(D=B.parentNode)==null||D.insertBefore(R,B.nextSibling):_e.appendChild(R)}break;case"body-top":{let B=oe.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");B?B.replaceWith(R):oe.insertBefore(R,oe.firstChild);break}case"body-bottom":oe.appendChild(R);break;case"footer-top":Ke.replaceWith(R);break;case"footer-bottom":et.replaceWith(R);break;default:break}};for(let[$,R]of Object.entries(l))if(R)try{let D=R({config:r,defaultContent:()=>u($)});D&&h($,D)}catch(D){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${$}":`,D)}})();let Ln=l=>{let h=l.target.closest('button[data-expand-header="true"]');if(!h)return;let A=h.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-bubble-type");$==="reasoning"?(mr.has(L)?mr.delete(L):mr.add(L),Sl(L,A)):$==="tool"&&(fr.has(L)?fr.delete(L):fr.add(L),Al(L,A,r))};Ee.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))}),Ee.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Ln(l))});let Xn=new Map;Ee.addEventListener("click",l=>{var R;let h=l.target.closest(".persona-message-action-btn[data-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest("[data-actions-for]");if(!A)return;let L=A.getAttribute("data-actions-for");if(!L)return;let $=h.getAttribute("data-action");if($==="copy"){let B=W.getMessages().find(me=>me.id===L);if(B&<.onCopy){let me=B.content||"";navigator.clipboard.writeText(me).then(()=>{h.classList.add("persona-message-action-success");let ge=ue("check",14,"currentColor",2);ge&&(h.innerHTML="",h.appendChild(ge)),setTimeout(()=>{h.classList.remove("persona-message-action-success");let Me=ue("copy",14,"currentColor",2);Me&&(h.innerHTML="",h.appendChild(Me))},2e3)}).catch(ge=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ge)}),lt.onCopy(B)}}else if($==="upvote"||$==="downvote")if(((R=Xn.get(L))!=null?R:null)===$)Xn.delete(L),h.classList.remove("persona-message-action-active");else{let me=$==="upvote"?"downvote":"upvote",ge=A.querySelector(`[data-action="${me}"]`);ge&&ge.classList.remove("persona-message-action-active"),Xn.set(L,$),h.classList.add("persona-message-action-active");let je=W.getMessages().find(xe=>xe.id===L);je&<.onFeedback&<.onFeedback({type:$,messageId:je.id,message:je})}}),Ee.addEventListener("click",l=>{let h=l.target.closest("button[data-approval-action]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.closest(".vanilla-approval-bubble");if(!A)return;let L=A.getAttribute("data-message-id");if(!L)return;let $=h.getAttribute("data-approval-action");if(!$)return;let R=$==="approve"?"approved":"denied",B=W.getMessages().find(ge=>ge.id===L);if(!(B!=null&&B.approval))return;let me=A.querySelector("[data-approval-buttons]");me&&me.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),W.resolveApproval(B.approval,R)});let Ge=null,gn=null,Pn={artifacts:[],selectedId:null},an=!1,vr={current:null};Ee.addEventListener("click",l=>{var ge,Me;let h=l.target.closest("[data-download-artifact]");if(!h)return;l.preventDefault(),l.stopPropagation();let A=h.getAttribute("data-download-artifact");if(!A)return;let L=W.getArtifactById(A),$=L==null?void 0:L.markdown,R=(L==null?void 0:L.title)||"artifact";if(!$){let je=h.closest("[data-open-artifact]"),xe=je==null?void 0:je.closest("[data-message-id]"),P=xe==null?void 0:xe.getAttribute("data-message-id");if(P){let Ae=W.getMessages().find(F=>F.id===P);if(Ae!=null&&Ae.rawContent)try{let F=JSON.parse(Ae.rawContent);$=(ge=F==null?void 0:F.props)==null?void 0:ge.markdown,R=((Me=F==null?void 0:F.props)==null?void 0:Me.title)||R}catch{}}}if(!$)return;let D=new Blob([$],{type:"text/markdown"}),B=URL.createObjectURL(D),me=document.createElement("a");me.href=B,me.download=`${R}.md`,me.click(),URL.revokeObjectURL(B)}),Ee.addEventListener("click",l=>{let h=l.target.closest("[data-open-artifact]");if(!h)return;let A=h.getAttribute("data-open-artifact");A&&(l.preventDefault(),l.stopPropagation(),W.selectArtifact(A),fn())}),Ee.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let mn=null,dt=null,tn=null,vn=null,Cr=()=>{};function Gn(){vn==null||vn(),vn=null}let wr=()=>{var R;if(!mn||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),h=((R=e.ownerDocument.defaultView)!=null?R:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||h){dt.style.removeProperty("position"),dt.style.removeProperty("left"),dt.style.removeProperty("top"),dt.style.removeProperty("bottom"),dt.style.removeProperty("width"),dt.style.removeProperty("z-index");return}let A=mn.firstElementChild;if(!A||A===dt)return;let L=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${L}px`,dt.style.zIndex="5";let $=A.offsetWidth-L/2;dt.style.left=`${Math.max(0,$)}px`},Nn=()=>{},fn=()=>{var h,A,L,$,R;if(!Ge||!on(r))return;Ls(e,r),Ps(e,r),Nn();let l=($=(L=(A=(h=r.features)==null?void 0:h.artifacts)==null?void 0:A.layout)==null?void 0:L.narrowHostMaxWidth)!=null?$:520,u=se.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Ge.update(Pn),an?(Ge.setMobileOpen(!1),Ge.element.classList.add("persona-hidden"),(R=Ge.backdrop)==null||R.classList.add("persona-hidden")):Pn.artifacts.length>0&&(Ge.element.classList.remove("persona-hidden"),Ge.setMobileOpen(!0)),Cr()};if(on(r)){se.style.position="relative";let l=f("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=f("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(ne),Ge=Ll(r,{onSelect:h=>{var A;return(A=vr.current)==null?void 0:A.selectArtifact(h)},onDismiss:()=>{an=!0,fn()}}),Ge.element.classList.add("persona-hidden"),mn=u,u.appendChild(l),u.appendChild(Ge.element),Ge.backdrop&&se.appendChild(Ge.backdrop),se.appendChild(u),Cr=()=>{var A,L,$,R;if(!mn||!Ge)return;if(!((($=(L=(A=r.features)==null?void 0:A.artifacts)==null?void 0:L.layout)==null?void 0:$.resizable)===!0)){tn==null||tn(),tn=null,Gn(),dt&&(dt.remove(),dt=null),Ge.element.style.removeProperty("width"),Ge.element.style.removeProperty("maxWidth");return}if(!dt){let D=f("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");D.setAttribute("role","separator"),D.setAttribute("aria-orientation","vertical"),D.setAttribute("aria-label","Resize artifacts panel"),D.tabIndex=0;let B=e.ownerDocument,me=(R=B.defaultView)!=null?R:window,ge=Me=>{var F,We;if(!Ge||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||me.innerWidth<=640)return;Me.preventDefault(),Gn();let je=Me.clientX,xe=Ge.element.getBoundingClientRect().width,P=(We=(F=r.features)==null?void 0:F.artifacts)==null?void 0:We.layout,ke=st=>{let Ze=mn.getBoundingClientRect().width,St=e.classList.contains("persona-artifact-appearance-seamless"),ct=St?0:Rl(mn,me),ot=St?0:D.getBoundingClientRect().width||6,Kt=xe-(st.clientX-je),ve=Hl(Kt,Ze,ct,ot,P==null?void 0:P.resizableMinWidth,P==null?void 0:P.resizableMaxWidth);Ge.element.style.width=`${ve}px`,Ge.element.style.maxWidth="none",wr()},Ae=()=>{B.removeEventListener("pointermove",ke),B.removeEventListener("pointerup",Ae),B.removeEventListener("pointercancel",Ae),vn=null;try{D.releasePointerCapture(Me.pointerId)}catch{}};vn=Ae,B.addEventListener("pointermove",ke),B.addEventListener("pointerup",Ae),B.addEventListener("pointercancel",Ae);try{D.setPointerCapture(Me.pointerId)}catch{}};D.addEventListener("pointerdown",ge),dt=D,mn.insertBefore(D,Ge.element),tn=()=>{D.removeEventListener("pointerdown",ge)}}if(dt){let D=Pn.artifacts.length>0&&!an;dt.classList.toggle("persona-hidden",!D),wr()}},Nn=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze,St,ct;if(!v||!Ge||((ge=(me=r.launcher)==null?void 0:me.sidebarMode)!=null?ge:!1))return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,L=(xe=(je=r.launcher)==null?void 0:je.mobileFullscreen)!=null?xe:!0,$=(ke=(P=r.launcher)==null?void 0:P.mobileBreakpoint)!=null?ke:640;if(L&&A.innerWidth<=$||!Wl(r,v))return;let R=(We=(F=(Ae=r.launcher)==null?void 0:Ae.width)!=null?F:r.launcherWidth)!=null?We:"min(400px, calc(100vw - 24px))",D=(ct=(St=(Ze=(st=r.features)==null?void 0:st.artifacts)==null?void 0:Ze.layout)==null?void 0:St.expandedPanelWidth)!=null?ct:"min(720px, calc(100vw - 24px))";Pn.artifacts.length>0&&!an?(se.style.width=D,se.style.maxWidth=D):(se.style.width=R,se.style.maxWidth=R)},typeof ResizeObserver!="undefined"&&(gn=new ResizeObserver(()=>{fn()}),gn.observe(se))}else se.appendChild(ne);e.appendChild(le);let On=()=>{var Ze,St,ct,ot,Kt,ve,pt,$t,sn,ms,fs,hs,Vs,qs,Tt,ys,Hr,Br,ar,bs,Bn;let l=Ut(r),u=(St=(Ze=r.launcher)==null?void 0:Ze.sidebarMode)!=null?St:!1,h=l||u||((ot=(ct=r.launcher)==null?void 0:ct.fullHeight)!=null?ot:!1),A=((Kt=r.launcher)==null?void 0:Kt.enabled)===!1,L=(ve=r.theme)!=null?ve:{},$=(pt=e.ownerDocument.defaultView)!=null?pt:window,R=(sn=($t=r.launcher)==null?void 0:$t.mobileFullscreen)!=null?sn:!0,D=(fs=(ms=r.launcher)==null?void 0:ms.mobileBreakpoint)!=null?fs:640,B=$.innerWidth<=D,me=R&&B&&v,ge=(Vs=(hs=r.launcher)==null?void 0:hs.position)!=null?Vs:"bottom-left",Me=ge==="bottom-left"||ge==="top-left",je=u||me?"none":"1px solid var(--persona-persona-border)",xe=me?"none":u?Me?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))",P=u||me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ke=(qs=L.panelBorder)!=null?qs:je,Ae=(Tt=L.panelShadow)!=null?Tt:xe,F=(ys=L.panelBorderRadius)!=null?ys:P;if(e.style.cssText="",le.style.cssText="",se.style.cssText="",ne.style.cssText="",oe.style.cssText="",Xe.style.cssText="",me){le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),le.style.cssText=`
|
|
21
21
|
position: fixed !important;
|
|
22
22
|
inset: 0 !important;
|
|
23
23
|
width: 100% !important;
|
|
@@ -52,7 +52,7 @@ import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let t=
|
|
|
52
52
|
overflow: hidden !important;
|
|
53
53
|
border-radius: 0 !important;
|
|
54
54
|
border: none !important;
|
|
55
|
-
`,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Xe.style.flexShrink="0",O=!0;return}let
|
|
55
|
+
`,oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Xe.style.flexShrink="0",O=!0;return}let We=(Br=(Hr=r==null?void 0:r.launcher)==null?void 0:Hr.width)!=null?Br:r==null?void 0:r.launcherWidth,st=We!=null?We:"min(400px, calc(100vw - 24px))";if(!u&&!l?A&&h?(se.style.width="100%",se.style.maxWidth="100%"):(se.style.width=st,se.style.maxWidth=st):l&&(se.style.width="100%",se.style.maxWidth="100%"),Nn(),se.style.boxShadow=Ae,se.style.borderRadius=F,ne.style.border=ke,ne.style.borderRadius=F,h&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),le.style.display="flex",le.style.flexDirection="column",le.style.flex="1 1 0%",le.style.minHeight="0",le.style.maxHeight="100%",le.style.height="100%",A&&(le.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",ne.style.display="flex",ne.style.flexDirection="column",ne.style.flex="1 1 0%",ne.style.minHeight="0",ne.style.maxHeight="100%",ne.style.overflow="hidden",oe.style.flex="1 1 0%",oe.style.minHeight="0",oe.style.overflowY="auto",Xe.style.flexShrink="0"),le.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!A&&!l&&((ar=dn[ge])!=null?ar:dn["bottom-right"]).split(" ").forEach(Yt=>le.classList.add(Yt)),u){let Tn=(Bn=(bs=r.launcher)==null?void 0:bs.sidebarWidth)!=null?Bn:"420px";le.style.cssText=`
|
|
56
56
|
position: fixed !important;
|
|
57
57
|
top: 0 !important;
|
|
58
58
|
bottom: 0 !important;
|
|
@@ -92,13 +92,13 @@ import{Marked as pc}from"marked";var uc=e=>{if(e)return e},xs=e=>{var o,s;let t=
|
|
|
92
92
|
flex-shrink: 0 !important;
|
|
93
93
|
border-top: none !important;
|
|
94
94
|
padding: 8px 16px 12px 16px !important;
|
|
95
|
-
`}if(!A&&!l){let Tn="max-height: -moz-available !important; max-height: stretch !important;",Yt=u?"":"padding-top: 1.25em !important;";le.style.cssText+=Tn+Yt}};On(),Yn(e,r),Ls(e,r),Ps(e,r);let xt=[];gn&&xt.push(()=>{gn==null||gn.disconnect(),gn=null}),xt.push(()=>{tn==null||tn(),tn=null,Gn(),dt&&(dt.remove(),dt=null),Ge==null||Ge.element.style.removeProperty("width"),Ge==null||Ge.element.style.removeProperty("maxWidth")}),Le&&xt.push(()=>{he!==null&&(cancelAnimationFrame(he),he=null),j==null||j.destroy(),j=null,V==null||V.destroy(),V=null,Q=null});let hn=null,Sr=()=>{hn&&(hn(),hn=null),r.colorScheme==="auto"&&(hn=oo(()=>{Yn(e,r)}))};Sr(),xt.push(()=>{hn&&(hn(),hn=null)});let In=El(Ke),yn=null,W,Wn=!1,Rn=pl(),Ar=0,Cn=!0,Dn=0,Er=0,wn=null,Sn=!1,Zn=0,Qn=!1,ns=125,rs=2e3,ss=5,Tr=50,er=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Mr=(zo=(Uo=r.voiceRecognition)==null?void 0:Uo.autoResume)!=null?zo:!1,nn=l=>{s.emit("voice:state",{active:qe.active,source:l,timestamp:Date.now()})},zt=()=>{p(l=>({...l,voiceState:{active:qe.active,timestamp:Date.now(),manuallyDeactivated:qe.manuallyDeactivated}}))},os=()=>{var A,L;if(((A=r.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ao(i.voiceState),u=!!l.active,h=Number((L=l.timestamp)!=null?L:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wd&&setTimeout(()=>{var $,R;qe.active||(qe.manuallyDeactivated=!1,((R=($=r.voiceRecognition)==null?void 0:$.provider)==null?void 0:R.type)==="runtype"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("restore"),W.isVoiceActive()&&Hn()}):Vn("restore"))},1e3)},as=()=>W?Dl(W.getMessages()).filter(l=>!l.__skipPersist):[];function kr(l){if(!(a!=null&&a.save))return;let h={messages:l?Dl(l):W?as():[],metadata:i};try{let A=a.save(h);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let _n=(l=!1)=>{if(!Cn)return;let u=Date.now();Sn&&u<Zn&&!l||(Sn&&u>=Zn&&(Sn=!1),!(!l&&!Wn)&&(u-Er<ns||(Er=u,wn&&cancelAnimationFrame(wn),wn=requestAnimationFrame(()=>{Sn||!Cn||(Qn=!0,oe.scrollTop=oe.scrollHeight,Dn=oe.scrollTop,requestAnimationFrame(()=>{Qn=!1}),wn=null)}))))},An=null,is=()=>le.querySelector("#persona-scroll-container")||oe,ls=(l,u=500)=>{let h=l.scrollTop,A=l.clientHeight,L=l.scrollHeight,$=L-h;if(h+A>=L-2||Math.abs($)<5)return;An!==null&&(cancelAnimationFrame(An),An=null);let D=performance.now(),B=ge=>1-Math.pow(1-ge,3),me=ge=>{let Me=l.scrollHeight;Me!==L&&(L=Me,$=L-h);let je=ge-D,xe=Math.min(je/u,1),P=B(xe),ke=h+$*P;l.scrollTop=ke,xe<1?An=requestAnimationFrame(me):(l.scrollTop=l.scrollHeight,An=null)};An=requestAnimationFrame(me)},cs=l=>{let u=new Map;l.forEach(h=>{let A=er.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!A&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(A!=null&&A.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(A?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),er.clear(),u.forEach((h,A)=>{er.set(A,h)})},jn=(l,u,h)=>{var ge,Me,je,xe;let A=document.createElement("div"),$=(()=>{var ke;let P=o.find(Ae=>Ae.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((ke=r.loadingIndicator)!=null&&ke.render)return r.loadingIndicator.render})(),R=new Set;u.forEach(P=>{var St,ct;R.add(P.id);let ke=dl(P,Ar),Ae=ul(Rn,P.id,ke);if(Ae){A.appendChild(Ae.cloneNode(!0));return}let F=null,Ie=o.find(ot=>!!(P.variant==="reasoning"&&ot.renderReasoning||P.variant==="tool"&&ot.renderToolCall||P.variant==="approval"&&ot.renderApproval||!P.variant&&ot.renderMessage)),st=(St=r.layout)==null?void 0:St.messages;if(Ie)if(P.variant==="reasoning"&&P.reasoning&&Ie.renderReasoning){if(!z)return;F=Ie.renderReasoning({message:P,defaultRenderer:()=>io(P),config:r})}else if(P.variant==="tool"&&P.toolCall&&Ie.renderToolCall){if(!pe)return;F=Ie.renderToolCall({message:P,defaultRenderer:()=>lo(P,r),config:r})}else if(P.variant==="approval"&&P.approval&&Ie.renderApproval){if(r.approval===!1)return;F=Ie.renderApproval({message:P,defaultRenderer:()=>co(P,r),config:r})}else Ie.renderMessage&&(F=Ie.renderMessage({message:P,defaultRenderer:()=>{let ot=Xr(P,h,st,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r});return P.role!=="user"&&go(ot,P,r,W),ot},config:r}));if(!F&&P.role==="assistant"&&!P.variant&&r.enableComponentStreaming!==!1&&vo(P)){let Kt=Co(P);if(Kt){let ve=xo(Kt,{config:r,message:P,transform:h});if(ve)if(r.wrapComponentDirectiveInBubble!==!1){let Ht=document.createElement("div");if(Ht.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Ht.id=`bubble-${P.id}`,Ht.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),Ht.appendChild(sn)}Ht.appendChild(ve),F=Ht}else{let Ht=document.createElement("div");if(Ht.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Ht.id=`bubble-${P.id}`,Ht.setAttribute("data-message-id",P.id),Ht.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let sn=document.createElement("div");sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),Ht.appendChild(sn)}Ht.appendChild(ve),F=Ht}}}if(!F)if(P.variant==="reasoning"&&P.reasoning){if(!z)return;F=io(P)}else if(P.variant==="tool"&&P.toolCall){if(!pe)return;F=lo(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;F=co(P,r)}else{let ot=(ct=r.layout)==null?void 0:ct.messages;ot!=null&&ot.renderUserMessage&&P.role==="user"?F=ot.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):ot!=null&&ot.renderAssistantMessage&&P.role==="assistant"?F=ot.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):F=Xr(P,h,ot,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r}),P.role!=="user"&&F&&go(F,P,r,W)}let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id=`wrapper-${P.id}`,Ze.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Ze.classList.add("persona-justify-end"),(F==null?void 0:F.getAttribute("data-persona-component-directive"))==="true"&&Ze.classList.add("persona-w-full"),Ze.appendChild(F),gl(Rn,P.id,ke,Ze),A.appendChild(Ze)}),ml(Rn,R);let D=u.some(P=>P.role==="assistant"&&P.streaming),B=u[u.length-1],me=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Wn&&u.some(P=>P.role==="user")&&!D&&!me){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:gr},ke=o.find(F=>F.renderLoadingIndicator),Ae=null;if(ke!=null&&ke.renderLoadingIndicator&&(Ae=ke.renderLoadingIndicator(P)),Ae===null&&((ge=r.loadingIndicator)!=null&&ge.render)&&(Ae=r.loadingIndicator.render(P)),Ae===null&&(Ae=gr()),Ae){let F=document.createElement("div"),Ie=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;F.className=Ie?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),F.setAttribute("data-typing-indicator","true"),F.appendChild(Ae);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-typing-indicator",st.setAttribute("data-wrapper-id","typing-indicator"),st.appendChild(F),A.appendChild(st)}}if(!Wn&&u.length>0){let P=u[u.length-1],ke={config:r,lastMessage:P,messageCount:u.length},Ae=o.find(Ie=>Ie.renderIdleIndicator),F=null;if(Ae!=null&&Ae.renderIdleIndicator&&(F=Ae.renderIdleIndicator(ke)),F===null&&((je=r.loadingIndicator)!=null&&je.renderIdle)&&(F=r.loadingIndicator.renderIdle(ke)),F){let Ie=document.createElement("div"),st=((xe=r.loadingIndicator)==null?void 0:xe.showBubble)!==!1;Ie.className=st?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ie.setAttribute("data-idle-indicator","true"),Ie.appendChild(F);let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id="wrapper-idle-indicator",Ze.setAttribute("data-wrapper-id","idle-indicator"),Ze.appendChild(Ie),A.appendChild(Ze)}}cl(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let P=is();ls(P)})})},tr=()=>{if(!v)return;let l=Ut(r);S?(le.style.display=l?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-95","persona-opacity-0"),se.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":Ne&&(Ne.style.display="none")):(l?(le.style.display="none",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100"),se.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":Ne&&(Ne.style.display=""))},ft=(l,u="user")=>{if(!v||S===l)return;let h=S;S=l,tr(),S&&(vt(),_n(!0));let A={open:S,source:u,timestamp:Date.now()};S&&!h?s.emit("widget:opened",A):!S&&h&&s.emit("widget:closed",A),s.emit("widget:state",{open:S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()})},nr=l=>{X.disabled=l,H&&(H.disabled=l),In.buttons.forEach(u=>{u.disabled=l}),Xe.dataset.personaComposerStreaming=l?"true":"false",Xe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},rr=()=>{qe.active||ee&&ee.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>rr(),200)});let Lr=()=>{var L,$,R,D,B,me,ge,Me,je,xe,P,ke,Ae,F;jt.textContent=($=(L=r.copy)==null?void 0:L.welcomeTitle)!=null?$:"Hello \u{1F44B}",Dt.textContent=(D=(R=r.copy)==null?void 0:R.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ee.placeholder=(me=(B=r.copy)==null?void 0:B.inputPlaceholder)!=null?me:"How can I help...",(Me=(ge=r.sendButton)==null?void 0:ge.useIcon)!=null&&Me||(X.textContent=(xe=(je=r.copy)==null?void 0:je.sendButtonLabel)!=null?xe:"Send");let u=(ke=(P=r.theme)==null?void 0:P.inputFontFamily)!=null?ke:"sans-serif",h=(F=(Ae=r.theme)==null?void 0:Ae.inputFontWeight)!=null?F:"400",A=Ie=>{switch(Ie){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};ee.style.fontFamily=A(u),ee.style.fontWeight=h};if(r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),W=new qr(r,{onMessagesChanged(l){jn(Ee,l,re),W&&(l.some(L=>L.role==="user")?In.render([],W,ee,l):In.render(r.suggestionChips,W,ee,l,r.suggestionChipsConfig)),_n(!Wn),cs(l);let u=[...l].reverse().find(A=>A.role==="user"),h=qe.lastUserMessageId;u&&u.id!==h&&(qe.lastUserMessageId=u.id,s.emit("user:message",u)),qe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),kr(l)},onStatusChanged(l){var A;let u=(A=r.statusIndicator)!=null?A:{},h=L=>{var $,R,D,B;return L==="idle"?($=u.idleText)!=null?$:_t.idle:L==="connecting"?(R=u.connectingText)!=null?R:_t.connecting:L==="connected"?(D=u.connectedText)!=null?D:_t.connected:L==="error"?(B=u.errorText)!=null?B:_t.error:_t[L]};et.textContent=h(l)},onStreamingChanged(l){Wn=l,nr(l),W&&jn(Ee,W.getMessages(),re),l||_n(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":cn(),ps();break;case"speaking":cn(),us();break;default:l==="idle"&&W.isBargeInActive()?(cn(),Hn(),H==null||H.setAttribute("aria-label","End voice session")):(qe.active=!1,cn(),nn("system"),zt());break}},onArtifactsState(l){Pn=l,fn()}}),vr.current=W,((Ko=(Jo=r.voiceRecognition)==null?void 0:Jo.provider)==null?void 0:Ko.type)==="runtype")try{W.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&W.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),V&&W.setSSEEventCallback((l,u)=>{V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(i=Ao(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&W.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Pr=l=>{var L;l.preventDefault();let u=ee.value.trim(),h=(L=Be==null?void 0:Be.hasAttachments())!=null?L:!1;if(!u&&!h)return;let A;h&&(A=[],A.push(...Be.getContentParts()),u&&A.push(Gs(u))),ee.value="",ee.style.height="auto",W.sendMessage(u,{contentParts:A}),h&&Be.clearAttachments()},Ir=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},Wr=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Be)return;let u=Hd(l.clipboardData);u.length!==0&&(l.preventDefault(),await Be.handleFiles(u))},Vt=null,Zt=!1,En=null,Re=null,Rr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vn=(l="user")=>{var $,R,D,B,me,ge,Me,je;if(Zt||W.isStreaming())return;let u=Rr();if(!u)return;Vt=new u;let A=(R=(($=r.voiceRecognition)!=null?$:{}).pauseDuration)!=null?R:2e3;Vt.continuous=!0,Vt.interimResults=!0,Vt.lang="en-US";let L=ee.value;Vt.onresult=xe=>{let P="",ke="";for(let F=0;F<xe.results.length;F++){let Ie=xe.results[F],st=Ie[0].transcript;Ie.isFinal?P+=st+" ":ke=st}let Ae=L+P+ke;ee.value=Ae,En&&clearTimeout(En),(P||ke)&&(En=window.setTimeout(()=>{let F=ee.value.trim();F&&Vt&&Zt&&(ln(),ee.value="",ee.style.height="auto",W.sendMessage(F,{viaVoice:!0}))},A))},Vt.onerror=xe=>{xe.error!=="no-speech"&&ln()},Vt.onend=()=>{if(Zt){let xe=ee.value.trim();xe&&xe!==L.trim()&&(ee.value="",ee.style.height="auto",W.sendMessage(xe,{viaVoice:!0})),ln()}};try{if(Vt.start(),Zt=!0,qe.active=!0,l!=="system"&&(qe.manuallyDeactivated=!1),nn(l),zt(),H){let xe=(D=r.voiceRecognition)!=null?D:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(B=xe.iconName)!=null?B:"mic",iconSize:parseFloat((Me=(ge=xe.iconSize)!=null?ge:(me=r.sendButton)==null?void 0:me.size)!=null?Me:"40")||24};let P=(je=xe.recordingBackgroundColor)!=null?je:"#ef4444",ke=xe.recordingIconColor,Ae=xe.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=P,ke){H.style.color=ke;let F=H.querySelector("svg");F&&F.setAttribute("stroke",ke)}Ae&&(H.style.borderColor=Ae),H.setAttribute("aria-label","Stop voice recognition")}}catch{ln("system")}},ln=(l="user")=>{if(Zt){if(Zt=!1,En&&(clearTimeout(En),En=null),Vt){try{Vt.stop()}catch{}Vt=null}if(qe.active=!1,nn(l),zt(),H){if(H.classList.remove("persona-voice-recording"),Re){H.style.backgroundColor=Re.backgroundColor,H.style.color=Re.color,H.style.borderColor=Re.borderColor;let u=H.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}H.setAttribute("aria-label","Start voice recognition")}}},ds=(l,u)=>{var F,Ie,st,Ze,St,ct,ot,Kt;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((F=l==null?void 0:l.provider)==null?void 0:F.type)==="runtype";if(!(h||A))return null;let $=f("div","persona-send-button-wrapper"),R=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let D=(Ie=l==null?void 0:l.iconName)!=null?Ie:"mic",B=(st=u==null?void 0:u.size)!=null?st:"40px",me=(Ze=l==null?void 0:l.iconSize)!=null?Ze:B,ge=parseFloat(me)||24,Me=(St=l==null?void 0:l.backgroundColor)!=null?St:u==null?void 0:u.backgroundColor,je=(ct=l==null?void 0:l.iconColor)!=null?ct:u==null?void 0:u.textColor;R.style.width=me,R.style.height=me,R.style.minWidth=me,R.style.minHeight=me,R.style.fontSize="18px",R.style.lineHeight="1";let xe=je||"currentColor",P=ue(D,ge,xe,1.5);P?(R.appendChild(P),R.style.color=xe):(R.textContent="\u{1F3A4}",R.style.color=xe),Me?R.style.backgroundColor=Me:R.classList.add("persona-bg-persona-primary"),je?R.style.color=je:!je&&!(u!=null&&u.textColor)&&R.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(R.style.borderWidth=l.borderWidth,R.style.borderStyle="solid"),l!=null&&l.borderColor&&(R.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(R.style.paddingLeft=l.paddingX,R.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(R.style.paddingTop=l.paddingY,R.style.paddingBottom=l.paddingY),$.appendChild(R);let ke=(ot=l==null?void 0:l.tooltipText)!=null?ot:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&ke){let ve=f("div","persona-send-button-tooltip");ve.textContent=ke,$.appendChild(ve)}return{micButton:R,micButtonWrapper:$}},sr=()=>{var u,h,A,L,$;if(!H||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat(($=(L=l.iconSize)!=null?L:(A=r.sendButton)==null?void 0:A.size)!=null?$:"40")||24}},or=(l,u)=>{var $,R,D,B,me;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let A=(me=Re==null?void 0:Re.iconSize)!=null?me:parseFloat((B=(D=($=r.voiceRecognition)==null?void 0:$.iconSize)!=null?D:(R=r.sendButton)==null?void 0:R.size)!=null?B:"40")||24,L=ue(l,A,u,1.5);L&&H.appendChild(L)},qn=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Hn=()=>{var L,$;if(!H)return;sr();let l=(L=r.voiceRecognition)!=null?L:{},u=($=l.recordingBackgroundColor)!=null?$:"#ef4444",h=l.recordingIconColor,A=l.recordingBorderColor;if(qn(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=u,h){H.style.color=h;let R=H.querySelector("svg");R&&R.setAttribute("stroke",h)}A&&(H.style.borderColor=A),H.setAttribute("aria-label","Stop voice recognition")},ps=()=>{var D,B,me,ge,Me,je,xe,P;if(!H)return;sr();let l=(D=r.voiceRecognition)!=null?D:{},u=W.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",A=(ge=(me=l.processingIconColor)!=null?me:Re==null?void 0:Re.color)!=null?ge:"",L=(je=(Me=l.processingBackgroundColor)!=null?Me:Re==null?void 0:Re.backgroundColor)!=null?je:"",$=(P=(xe=l.processingBorderColor)!=null?xe:Re==null?void 0:Re.borderColor)!=null?P:"";qn(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=L,H.style.borderColor=$;let R=A||"currentColor";H.style.color=R,or(h,R),H.setAttribute("aria-label","Processing voice input"),u==="none"&&(H.style.cursor="default")},us=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,Ie,st,Ze;if(!H)return;sr();let l=(me=r.voiceRecognition)!=null?me:{},u=W.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",A=(ge=l.speakingIconName)!=null?ge:h,L=(P=l.speakingIconColor)!=null?P:u==="barge-in"?(je=(Me=l.recordingIconColor)!=null?Me:Re==null?void 0:Re.color)!=null?je:"":(xe=Re==null?void 0:Re.color)!=null?xe:"",$=(F=l.speakingBackgroundColor)!=null?F:u==="barge-in"?(ke=l.recordingBackgroundColor)!=null?ke:"#ef4444":(Ae=Re==null?void 0:Re.backgroundColor)!=null?Ae:"",R=(Ze=l.speakingBorderColor)!=null?Ze:u==="barge-in"?(Ie=l.recordingBorderColor)!=null?Ie:"":(st=Re==null?void 0:Re.borderColor)!=null?st:"";qn(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=$,H.style.borderColor=R;let D=L||"currentColor";H.style.color=D,or(A,D);let B=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",B),u==="none"&&(H.style.cursor="default"),u==="barge-in"&&H.classList.add("persona-voice-recording")},cn=()=>{var l,u,h;H&&(qn(),Re&&(H.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",H.style.color=(u=Re.color)!=null?u:"",H.style.borderColor=(h=Re.borderColor)!=null?h:"",or(Re.iconName,Re.color||"currentColor"),Re=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Un=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=W.getVoiceStatus(),A=W.getVoiceInterruptionMode();if(A==="none"&&(h==="processing"||h==="speaking"))return;if(A==="cancel"&&(h==="processing"||h==="speaking")){W.stopVoicePlayback();return}if(W.isBargeInActive()){W.stopVoicePlayback(),W.deactivateBargeIn().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()});return}W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),qe.manuallyDeactivated=!W.isVoiceActive(),zt(),nn("user"),W.isVoiceActive()?Hn():cn()});return}if(Zt){let h=ee.value.trim();qe.manuallyDeactivated=!0,zt(),ln("user"),h&&(ee.value="",ee.style.height="auto",W.sendMessage(h))}else qe.manuallyDeactivated=!1,zt(),Vn("user")};ut=Un,H&&(H.addEventListener("click",Un),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(W.isVoiceActive()&&W.toggleVoice(),cn()):ln("system"),H&&H.removeEventListener("click",Un)}));let gs=s.on("assistant:complete",()=>{Mr&&(qe.active||qe.manuallyDeactivated||Mr==="assistant"&&!qe.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!qe.active&&!qe.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("auto"),W.isVoiceActive()&&Hn()}):Vn("auto"))},600))});xt.push(gs);let G=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});xt.push(G);let Fe=()=>{ft(!S,"user")},we=null,Ne=null;if(v){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>Jr(r,Fe).element,onToggle:Fe});u&&(Ne=u)}Ne||(we=Jr(r,Fe))}we?e.appendChild(we.element):Ne&&e.appendChild(Ne),tr(),In.render(r.suggestionChips,W,ee,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming()),_n(!0),os(),x&&(v?S&&setTimeout(()=>rr(),200):setTimeout(()=>rr(),0));let vt=()=>{var B,me,ge,Me,je,xe,P,ke,Ae,F,Ie,st,Ze;let l=Ut(r),u=(me=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?me:!1,h=l||u||((Me=(ge=r.launcher)==null?void 0:ge.fullHeight)!=null?Me:!1),A=(je=e.ownerDocument.defaultView)!=null?je:window,L=(P=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?P:!0,$=(Ae=(ke=r.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ae:640,R=A.innerWidth<=$;if(L&&R&&v){On(),Yn(e,r);return}if(O&&(O=!1,On(),Yn(e,r)),!v&&!l){se.style.height="",se.style.width="";return}if(!u&&!l){let St=(Ie=(F=r==null?void 0:r.launcher)==null?void 0:F.width)!=null?Ie:r==null?void 0:r.launcherWidth,ct=St!=null?St:"min(400px, calc(100vw - 24px))";se.style.width=ct,se.style.maxWidth=ct}if(Nn(),!h){let St=A.innerHeight,ct=64,ot=(Ze=(st=r.launcher)==null?void 0:st.heightOffset)!=null?Ze:0,Kt=Math.max(200,St-ct),ve=Math.min(640,Kt),pt=Math.max(200,ve-ot);se.style.height=`${pt}px`}};vt();let Nt=(Yo=e.ownerDocument.defaultView)!=null?Yo:window;Nt.addEventListener("resize",vt),xt.push(()=>Nt.removeEventListener("resize",vt)),Dn=oe.scrollTop;let Ct=()=>{let l=oe.scrollTop,u=oe.scrollHeight,h=oe.clientHeight,A=u-l-h,L=Math.abs(l-Dn);if(Dn=l,!Qn&&!(L<=ss)){if(!Cn&&A<Tr){Sn=!1,Cn=!0;return}Cn&&A>Tr&&(Sn=!0,Zn=Date.now()+rs,Cn=!1)}};oe.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>oe.removeEventListener("scroll",Ct)),xt.push(()=>{wn&&cancelAnimationFrame(wn)});let b=()=>{ie&&(yn&&(ie.removeEventListener("click",yn),yn=null),v?(ie.style.display="",yn=()=>{ft(!1,"user")},ie.addEventListener("click",yn)):ie.style.display="none")};b(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let h=a.clear();h instanceof Promise&&h.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}i={},C.syncFromMetadata(),V==null||V.clear(),j==null||j.update()})})(),Ve&&Ve.addEventListener("submit",Pr),ee==null||ee.addEventListener("keydown",Ir),ee==null||ee.addEventListener("paste",Wr),xt.push(()=>{Ve&&Ve.removeEventListener("submit",Pr),ee==null||ee.removeEventListener("keydown",Ir),ee==null||ee.removeEventListener("paste",Wr)}),xt.push(()=>{W.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):Ne&&xt.push(()=>{Ne==null||Ne.remove()});let T={update(l){var na,ra,sa,oa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,$a,Fa,Na,Oa,Da,_a,ja,Va,qa,Ua,za,Ja,Ka,Ya,Xa,Ga,Za,Qa,ei,ti,ni,ri,si,oi,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,$i,Fi,Ni,Oi;let u=r.toolCall,h=r.messageActions,A=(na=r.layout)==null?void 0:na.messages,L=r.colorScheme;r={...r,...l},On(),Yn(e,r),Ls(e,r),Ps(e,r),fn(),r.colorScheme!==L&&Sr();let $=Is.getForInstance(r.plugins);o.length=0,o.push(...$),v=(sa=(ra=r.launcher)==null?void 0:ra.enabled)!=null?sa:!0,E=(aa=(oa=r.launcher)==null?void 0:oa.autoExpand)!=null?aa:!1,z=(la=(ia=r.features)==null?void 0:ia.showReasoning)!=null?la:!0,pe=(da=(ca=r.features)==null?void 0:ca.showToolCalls)!=null?da:!0;let R=Le;if(Le=(ua=(pa=r.features)==null?void 0:pa.showEventStreamToggle)!=null?ua:!1,Le&&!R){if(V||(Q=new Zr(fe),V=new Gr(Y,Q),Q.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),W.setSSEEventCallback((_,ze)=>{V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:_,timestamp:Date.now(),payload:JSON.stringify(ze)})})),!de&&_e){let _=(ma=(ga=r.features)==null?void 0:ga.eventStream)==null?void 0:ma.classNames,ze="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(_!=null&&_.toggleButton?" "+_.toggleButton:"");de=f("button",ze),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let ht=ue("activity","18px","currentColor",1.5);ht&&de.appendChild(ht);let Oe=q.clearChatButtonWrapper,Qe=q.closeButtonWrapper,Lt=Oe||Qe;Lt&&Lt.parentNode===_e?_e.insertBefore(de,Lt):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}}else!Le&&R&&($e(),de&&(de.remove(),de=null),V==null||V.clear(),Q==null||Q.destroy(),V=null,Q=null);if(((fa=r.launcher)==null?void 0:fa.enabled)===!1&&we&&(we.destroy(),we=null),((ha=r.launcher)==null?void 0:ha.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((ya=r.launcher)==null?void 0:ya.enabled)!==!1&&!we&&!Ne){let _=o.find(ze=>ze.renderLauncher);if(_!=null&&_.renderLauncher){let ze=_.renderLauncher({config:r,defaultRenderer:()=>Jr(r,Fe).element,onToggle:Fe});ze&&(Ne=ze,e.appendChild(Ne))}Ne||(we=Jr(r,Fe),e.appendChild(we.element))}we&&we.update(r),Te&&((ba=r.launcher)==null?void 0:ba.title)!==void 0&&(Te.textContent=r.launcher.title),tt&&((xa=r.launcher)==null?void 0:xa.subtitle)!==void 0&&(tt.textContent=r.launcher.subtitle);let D=(va=r.layout)==null?void 0:va.header;if((D==null?void 0:D.layout)!==M&&_e){let _=D?Kr(r,D,{showClose:v,onClose:()=>ft(!1,"user")}):$n({config:r,showClose:v,onClose:()=>ft(!1,"user")});_e.replaceWith(_.header),_e=_.header,Ue=_.iconHolder,Te=_.headerTitle,tt=_.headerSubtitle,ie=_.closeButton,M=D==null?void 0:D.layout}else if(D&&(Ue&&(Ue.style.display=D.showIcon===!1?"none":""),Te&&(Te.style.display=D.showTitle===!1?"none":""),tt&&(tt.style.display=D.showSubtitle===!1?"none":""),ie&&(ie.style.display=D.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let _=D.showClearChat;if(_!==void 0){q.clearChatButtonWrapper.style.display=_?"":"none";let{closeButtonWrapper:ze}=q;ze&&!ze.classList.contains("persona-absolute")&&(_?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}let me=((Ca=r.layout)==null?void 0:Ca.showHeader)!==!1;_e&&(_e.style.display=me?"":"none");let ge=((wa=r.layout)==null?void 0:wa.showFooter)!==!1;Xe&&(Xe.style.display=ge?"":"none"),v!==U?v?ft(E,"auto"):(S=!0,tr()):E!==k&&ft(E,"auto"),k=E,U=v,vt(),b();let xe=JSON.stringify(l.toolCall)!==JSON.stringify(u),P=JSON.stringify(r.messageActions)!==JSON.stringify(h),ke=JSON.stringify((Sa=r.layout)==null?void 0:Sa.messages)!==JSON.stringify(A);(xe||P||ke)&&W&&(Ar++,jn(Ee,W.getMessages(),re));let F=(Aa=r.launcher)!=null?Aa:{},Ie=(Ea=F.headerIconHidden)!=null?Ea:!1,st=(Ma=(Ta=r.layout)==null?void 0:Ta.header)==null?void 0:Ma.showIcon,Ze=Ie||st===!1,St=F.headerIconName,ct=(ka=F.headerIconSize)!=null?ka:"48px";if(Ue){let _=ne.querySelector(".persona-border-b-persona-divider"),ze=_==null?void 0:_.querySelector(".persona-flex-col");if(Ze)Ue.style.display="none",_&&ze&&!_.contains(ze)&&_.insertBefore(ze,_.firstChild);else{if(Ue.style.display="",Ue.style.height=ct,Ue.style.width=ct,_&&ze&&(_.contains(Ue)?Ue.nextSibling!==ze&&(Ue.remove(),_.insertBefore(Ue,ze)):_.insertBefore(Ue,ze)),St){let Oe=parseFloat(ct)||24,Qe=ue(St,Oe*.6,"#ffffff",2);Qe?Ue.replaceChildren(Qe):Ue.textContent=(La=F.agentIconText)!=null?La:"\u{1F4AC}"}else if(F.iconUrl){let Oe=Ue.querySelector("img");if(Oe)Oe.src=F.iconUrl,Oe.style.height=ct,Oe.style.width=ct;else{let Qe=document.createElement("img");Qe.src=F.iconUrl,Qe.alt="",Qe.className="persona-rounded-xl persona-object-cover",Qe.style.height=ct,Qe.style.width=ct,Ue.replaceChildren(Qe)}}else{let Oe=Ue.querySelector("svg"),Qe=Ue.querySelector("img");(Oe||Qe)&&Ue.replaceChildren(),Ue.textContent=(Pa=F.agentIconText)!=null?Pa:"\u{1F4AC}"}let ht=Ue.querySelector("img");ht&&(ht.style.height=ct,ht.style.width=ct)}}let ot=(Wa=(Ia=r.layout)==null?void 0:Ia.header)==null?void 0:Wa.showTitle,Kt=(Ha=(Ra=r.layout)==null?void 0:Ra.header)==null?void 0:Ha.showSubtitle;if(Te&&(Te.style.display=ot===!1?"none":""),tt&&(tt.style.display=Kt===!1?"none":""),ie){(($a=(Ba=r.layout)==null?void 0:Ba.header)==null?void 0:$a.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let ze=(Fa=F.closeButtonSize)!=null?Fa:"32px",ht=(Na=F.closeButtonPlacement)!=null?Na:"inline";ie.style.height=ze,ie.style.width=ze;let{closeButtonWrapper:Oe}=q,Qe=ht==="top-right",Lt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&Qe!==Lt)if(Oe.remove(),Qe)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(Oe);else{let Je=(Da=(Oa=F.clearChat)==null?void 0:Oa.placement)!=null?Da:"inline",Bt=(ja=(_a=F.clearChat)==null?void 0:_a.enabled)!=null?ja:!0;Oe.className=Bt&&Je==="inline"?"":"persona-ml-auto";let Xt=ne.querySelector(".persona-border-b-persona-divider");Xt&&Xt.appendChild(Oe)}if(F.closeButtonColor?(ie.style.color=F.closeButtonColor,ie.classList.remove("persona-text-persona-muted")):(ie.style.color="",ie.classList.add("persona-text-persona-muted")),F.closeButtonBackgroundColor?(ie.style.backgroundColor=F.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),F.closeButtonBorderWidth||F.closeButtonBorderColor){let Je=F.closeButtonBorderWidth||"0px",Bt=F.closeButtonBorderColor||"transparent";ie.style.border=`${Je} solid ${Bt}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");F.closeButtonBorderRadius?(ie.style.borderRadius=F.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),F.closeButtonPaddingX?(ie.style.paddingLeft=F.closeButtonPaddingX,ie.style.paddingRight=F.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),F.closeButtonPaddingY?(ie.style.paddingTop=F.closeButtonPaddingY,ie.style.paddingBottom=F.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let Ot=(Va=F.closeButtonIconName)!=null?Va:"x",Qt=(qa=F.closeButtonIconText)!=null?qa:"\xD7";ie.innerHTML="";let qt=ue(Ot,"20px",F.closeButtonColor||"",2);qt?ie.appendChild(qt):ie.textContent=Qt;let At=(Ua=F.closeButtonTooltipText)!=null?Ua:"Close chat",en=(za=F.closeButtonShowTooltip)!=null?za:!0;if(ie.setAttribute("aria-label",At),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),en&&At)){let Je=null,Bt=()=>{if(Je||!ie)return;let zn=ie.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ie.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};Oe.addEventListener("mouseenter",Bt),Oe.addEventListener("mouseleave",Xt),ie.addEventListener("focus",Bt),ie.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Bt),Oe.removeEventListener("mouseleave",Xt)),ie&&(ie.removeEventListener("focus",Bt),ie.removeEventListener("blur",Xt))}}}let{clearChatButton:ve,clearChatButtonWrapper:pt}=q;if(ve){let _=(Ja=F.clearChat)!=null?Ja:{},ze=(Ka=_.enabled)!=null?Ka:!0,ht=(Xa=(Ya=r.layout)==null?void 0:Ya.header)==null?void 0:Xa.showClearChat,Oe=ht!==void 0?ht:ze,Qe=(Ga=_.placement)!=null?Ga:"inline";if(pt){pt.style.display=Oe?"":"none";let{closeButtonWrapper:Lt}=q;Lt&&!Lt.classList.contains("persona-absolute")&&(Oe?Lt.classList.remove("persona-ml-auto"):Lt.classList.add("persona-ml-auto"));let Ot=Qe==="top-right",Qt=pt.classList.contains("persona-absolute");if(Ot!==Qt&&Oe){if(pt.remove(),Ot)pt.className="persona-absolute persona-top-4 persona-z-50",pt.style.right="48px",ne.style.position="relative",ne.appendChild(pt);else{pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pt.style.right="";let At=ne.querySelector(".persona-border-b-persona-divider"),en=q.closeButtonWrapper;At&&en&&en.parentElement===At?At.insertBefore(pt,en):At&&At.appendChild(pt)}let qt=q.closeButtonWrapper;qt&&!qt.classList.contains("persona-absolute")&&(Ot?qt.classList.add("persona-ml-auto"):qt.classList.remove("persona-ml-auto"))}}if(Oe){let Lt=(Za=_.size)!=null?Za:"32px";ve.style.height=Lt,ve.style.width=Lt;let Ot=(Qa=_.iconName)!=null?Qa:"refresh-cw",Qt=(ei=_.iconColor)!=null?ei:"";ve.innerHTML="";let qt=ue(Ot,"20px",Qt||"",2);if(qt&&ve.appendChild(qt),Qt?(ve.style.color=Qt,ve.classList.remove("persona-text-persona-muted")):(ve.style.color="",ve.classList.add("persona-text-persona-muted")),_.backgroundColor?(ve.style.backgroundColor=_.backgroundColor,ve.classList.remove("hover:persona-bg-gray-100")):(ve.style.backgroundColor="",ve.classList.add("hover:persona-bg-gray-100")),_.borderWidth||_.borderColor){let Je=_.borderWidth||"0px",Bt=_.borderColor||"transparent";ve.style.border=`${Je} solid ${Bt}`,ve.classList.remove("persona-border-none")}else ve.style.border="",ve.classList.add("persona-border-none");_.borderRadius?(ve.style.borderRadius=_.borderRadius,ve.classList.remove("persona-rounded-full")):(ve.style.borderRadius="",ve.classList.add("persona-rounded-full")),_.paddingX?(ve.style.paddingLeft=_.paddingX,ve.style.paddingRight=_.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),_.paddingY?(ve.style.paddingTop=_.paddingY,ve.style.paddingBottom=_.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom="");let At=(ti=_.tooltipText)!=null?ti:"Clear chat",en=(ni=_.showTooltip)!=null?ni:!0;if(ve.setAttribute("aria-label",At),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),en&&At)){let Je=null,Bt=()=>{if(Je||!ve)return;let zn=ve.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ve.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};pt.addEventListener("mouseenter",Bt),pt.addEventListener("mouseleave",Xt),ve.addEventListener("focus",Bt),ve.addEventListener("blur",Xt),pt._cleanupTooltip=()=>{Xt(),pt&&(pt.removeEventListener("mouseenter",Bt),pt.removeEventListener("mouseleave",Xt)),ve&&(ve.removeEventListener("focus",Bt),ve.removeEventListener("blur",Xt))}}}}let Ht=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick];C=Rs({parsers:Ht,handlers:sn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),re=_l(r,C,K),W.updateConfig(r),jn(Ee,W.getMessages(),re),In.render(r.suggestionChips,W,ee,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming());let ms=((ri=r.voiceRecognition)==null?void 0:ri.enabled)===!0,fs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),hs=((oi=(si=r.voiceRecognition)==null?void 0:si.provider)==null?void 0:oi.type)==="runtype";if(ms&&(fs||hs))if(!H||!te){let _=ds(r.voiceRecognition,r.sendButton);_&&(H=_.micButton,te=_.micButtonWrapper,It.insertBefore(te,He),H.addEventListener("click",Un),H.disabled=W.isStreaming())}else{let _=(ai=r.voiceRecognition)!=null?ai:{},ze=(ii=r.sendButton)!=null?ii:{},ht=(li=_.iconName)!=null?li:"mic",Oe=(ci=ze.size)!=null?ci:"40px",Qe=(di=_.iconSize)!=null?di:Oe,Lt=parseFloat(Qe)||24;H.style.width=Qe,H.style.height=Qe,H.style.minWidth=Qe,H.style.minHeight=Qe;let Ot=(ui=(pi=_.iconColor)!=null?pi:ze.textColor)!=null?ui:"currentColor";H.innerHTML="";let Qt=ue(ht,Lt,Ot,2);Qt?H.appendChild(Qt):H.textContent="\u{1F3A4}";let qt=(gi=_.backgroundColor)!=null?gi:ze.backgroundColor;qt?(H.style.backgroundColor=qt,H.classList.remove("persona-bg-persona-primary")):(H.style.backgroundColor="",H.classList.add("persona-bg-persona-primary")),Ot?(H.style.color=Ot,H.classList.remove("persona-text-white")):!Ot&&!ze.textColor&&(H.style.color="",H.classList.add("persona-text-white")),_.borderWidth?(H.style.borderWidth=_.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),_.borderColor?H.style.borderColor=_.borderColor:H.style.borderColor="",_.paddingX?(H.style.paddingLeft=_.paddingX,H.style.paddingRight=_.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),_.paddingY?(H.style.paddingTop=_.paddingY,H.style.paddingBottom=_.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let At=te==null?void 0:te.querySelector(".persona-send-button-tooltip"),en=(mi=_.tooltipText)!=null?mi:"Start voice recognition";if(((fi=_.showTooltip)!=null?fi:!1)&&en)if(At)At.textContent=en,At.style.display="";else{let Bt=document.createElement("div");Bt.className="persona-send-button-tooltip",Bt.textContent=en,te==null||te.insertBefore(Bt,H)}else At&&(At.style.display="none");te.style.display="",H.disabled=W.isStreaming()}else H&&te&&(te.style.display="none",((yi=(hi=r.voiceRecognition)==null?void 0:hi.provider)==null?void 0:yi.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():Zt&&ln());if(((bi=r.attachments)==null?void 0:bi.enabled)===!0)if(!We||!J){let _=(xi=r.attachments)!=null?xi:{},ht=(Ci=((vi=r.sendButton)!=null?vi:{}).size)!=null?Ci:"40px";Pe||(Pe=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Pe.style.display="none",Ve.insertBefore(Pe,ee)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((wi=_.allowedTypes)!=null?wi:Mn).join(","),Ce.multiple=((Si=_.maxFiles)!=null?Si:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ve.insertBefore(Ce,ee)),We=f("div","persona-send-button-wrapper"),J=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),J.type="button",J.setAttribute("aria-label",(Ai=_.buttonTooltipText)!=null?Ai:"Attach file");let Oe=(Ei=_.buttonIconName)!=null?Ei:"paperclip",Qe=ht,Lt=parseFloat(Qe)||40,Ot=Math.round(Lt*.6);J.style.width=Qe,J.style.height=Qe,J.style.minWidth=Qe,J.style.minHeight=Qe,J.style.fontSize="18px",J.style.lineHeight="1",J.style.backgroundColor="transparent",J.style.color="var(--persona-primary, #111827)",J.style.border="none",J.style.borderRadius="6px",J.style.transition="background-color 0.15s ease",J.addEventListener("mouseenter",()=>{J.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),J.addEventListener("mouseleave",()=>{J.style.backgroundColor="transparent"});let Qt=ue(Oe,Ot,"currentColor",1.5);Qt?J.appendChild(Qt):J.textContent="\u{1F4CE}",J.addEventListener("click",en=>{en.preventDefault(),Ce==null||Ce.click()}),We.appendChild(J);let qt=(Ti=_.buttonTooltipText)!=null?Ti:"Attach file",At=f("div","persona-send-button-tooltip");At.textContent=qt,We.appendChild(At),Ft.append(We),!Be&&Ce&&Pe&&(Be=pr.fromConfig(_),Be.setPreviewsContainer(Pe),Ce.addEventListener("change",async()=>{Be&&(Ce!=null&&Ce.files)&&(await Be.handleFileSelect(Ce.files),Ce.value="")}))}else{We.style.display="";let _=(Mi=r.attachments)!=null?Mi:{};Ce&&(Ce.accept=((ki=_.allowedTypes)!=null?ki:Mn).join(","),Ce.multiple=((Li=_.maxFiles)!=null?Li:4)>1),Be&&Be.updateConfig({allowedTypes:_.allowedTypes,maxFileSize:_.maxFileSize,maxFiles:_.maxFiles})}else We&&(We.style.display="none"),Be&&Be.clearAttachments();let Tt=(Pi=r.sendButton)!=null?Pi:{},ys=(Ii=Tt.useIcon)!=null?Ii:!1,Hr=(Wi=Tt.iconText)!=null?Wi:"\u2191",Br=Tt.iconName,ar=(Ri=Tt.tooltipText)!=null?Ri:"Send message",bs=(Hi=Tt.showTooltip)!=null?Hi:!1,Bn=(Bi=Tt.size)!=null?Bi:"40px",Tn=Tt.backgroundColor,Yt=Tt.textColor;if(ys){if(X.style.width=Bn,X.style.height=Bn,X.style.minWidth=Bn,X.style.minHeight=Bn,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Br){let _=parseFloat(Bn)||24,ze=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",ht=ue(Br,_,ze,2);ht?(X.appendChild(ht),X.style.color=ze):(X.textContent=Hr,Yt?X.style.color=Yt:X.classList.add("persona-text-white"))}else X.textContent=Hr,Yt?X.style.color=Yt:X.classList.add("persona-text-white");X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-primary")):X.classList.add("persona-bg-persona-primary")}else X.textContent=(Fi=($i=r.copy)==null?void 0:$i.sendButtonLabel)!=null?Fi:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Yt?X.style.color=Yt:X.classList.add("persona-text-white");Tt.borderWidth?(X.style.borderWidth=Tt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Tt.borderColor?X.style.borderColor=Tt.borderColor:X.style.borderColor="",Tt.paddingX?(X.style.paddingLeft=Tt.paddingX,X.style.paddingRight=Tt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Tt.paddingY?(X.style.paddingTop=Tt.paddingY,X.style.paddingBottom=Tt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let $r=He==null?void 0:He.querySelector(".persona-send-button-tooltip");if(bs&&ar)if($r)$r.textContent=ar,$r.style.display="";else{let _=document.createElement("div");_.className="persona-send-button-tooltip",_.textContent=ar,He==null||He.insertBefore(_,X)}else $r&&($r.style.display="none");let Fr=(Ni=r.statusIndicator)!=null?Ni:{},dc=(Oi=Fr.visible)!=null?Oi:!0;if(et.style.display=dc?"":"none",W){let _=W.getStatus(),ze=ht=>{var Oe,Qe,Lt,Ot;return ht==="idle"?(Oe=Fr.idleText)!=null?Oe:_t.idle:ht==="connecting"?(Qe=Fr.connectingText)!=null?Qe:_t.connecting:ht==="connected"?(Lt=Fr.connectedText)!=null?Lt:_t.connected:ht==="error"?(Ot=Fr.errorText)!=null?Ot:_t.error:_t[ht]};et.textContent=ze(_)}},open(){v&&ft(!0,"api")},close(){v&&ft(!1,"api")},toggle(){v&&ft(!S,"api")},clearChat(){an=!1,W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}i={},C.syncFromMetadata(),V==null||V.clear(),j==null||j.update()},setMessage(l){return!ee||W.isStreaming()?!1:(!S&&v&&ft(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(W.isStreaming())return!1;let u=(l==null?void 0:l.trim())||ee.value.trim();return u?(!S&&v&&ft(!0,"system"),ee.value="",ee.style.height="auto",W.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return W.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(W.isVoiceActive()||(!S&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("user"),W.isVoiceActive()&&Hn()})),!0):Zt?!0:Rr()?(!S&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),Vn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?W.isVoiceActive()?(W.toggleVoice().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()}),!0):!1:Zt?(qe.manuallyDeactivated=!0,zt(),ln("user"),!0):!1},injectMessage(l){return!S&&v&&ft(!0,"system"),W.injectMessage(l)},injectAssistantMessage(l){!S&&v&&ft(!0,"system");let u=W.injectAssistantMessage(l);return N&&(N=!1,Z&&(clearTimeout(Z),Z=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),u},injectUserMessage(l){return!S&&v&&ft(!0,"system"),W.injectUserMessage(l)},injectSystemMessage(l){return!S&&v&&ft(!0,"system"),W.injectSystemMessage(l)},injectMessageBatch(l){return!S&&v&&ft(!0,"system"),W.injectMessageBatch(l)},injectTestMessage(l){!S&&v&&ft(!0,"system"),W.injectTestEvent(l)},async connectStream(l,u){return W.connectStream(l,u)},__pushEventStreamEvent(l){V&&V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Le||!V||be()},hideEventStream(){ce&&$e()},isEventStreamVisible(){return ce},showArtifacts(){on(r)&&(an=!1,fn(),Ge==null||Ge.setMobileOpen(!0))},hideArtifacts(){on(r)&&(an=!0,fn())},upsertArtifact(l){return on(r)?(an=!1,W.upsertArtifact(l)):null},selectArtifact(l){on(r)&&W.selectArtifact(l)},clearArtifacts(){on(r)&&W.clearArtifacts()},focusInput(){return v&&!S||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,u){let A=W.getMessages().find(L=>{var $;return L.variant==="approval"&&(($=L.approval)==null?void 0:$.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return W.resolveApproval(A.approval,u)},getMessages(){return W.getMessages()},getStatus(){return W.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return v&&S},isVoiceActive(){return qe.active},getState(){return{open:v&&S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()}},showCSATFeedback(l){!S&&v&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=wo({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitCSATFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!S&&v&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=So({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitNPSFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return W.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return W.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),le.remove(),we==null||we.destroy(),Ne==null||Ne.remove(),yn&&ie.removeEventListener("click",yn)}};if((((Xo=n==null?void 0:n.debugTools)!=null?Xo:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:T,getMessages:T.getMessages,getStatus:T.getStatus,getMetadata:T.getPersistentMetadata,updateMetadata:T.updatePersistentMetadata,clearHistory:()=>T.clearChat(),setVoiceActive:h=>h?T.startVoiceRecognition():T.stopVoiceRecognition()};window.AgentWidgetBrowser=u,xt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Le){let D=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.showEventStream()},B=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",D),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",D),window.removeEventListener("persona:hideEventStream",B)})}let h=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.showArtifacts()},A=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.hideArtifacts()},L=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&T.upsertArtifact(B.artifact)},$=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&T.selectArtifact(B.id)},R=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",R),xt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",R)})}let I=Bd(r.persistState);if(I&&v){let l=$d(I.storage),u=`${I.keyPrefix}widget-open`,h=`${I.keyPrefix}widget-voice`,A=`${I.keyPrefix}widget-voice-mode`;if(l){let L=((Go=I.persist)==null?void 0:Go.openState)&&l.getItem(u)==="true",$=((Zo=I.persist)==null?void 0:Zo.voiceState)&&l.getItem(h)==="true",R=((Qo=I.persist)==null?void 0:Qo.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{T.open(),setTimeout(()=>{var D;if($||R)T.startVoiceRecognition();else if((D=I.persist)!=null&&D.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(ea=I.persist)!=null&&ea.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(ta=I.persist)!=null&&ta.voiceState&&(s.on("voice:state",D=>{l.setItem(h,D.active?"true":"false")}),s.on("user:message",D=>{l.setItem(A,D.viaVoice?"true":"false")})),I.clearOnChatClear){let D=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(A)},B=()=>D();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return T};var jl=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},To=(e,t,n,r,o,s)=>{let a=zr(o),i=s?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=s?"true":"false",e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.flex="1 1 auto",t.style.minWidth="0",t.style.minHeight="0",t.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${i}`,n.style.width=i,n.style.maxWidth=i,n.style.minWidth=i,n.style.minHeight="0",n.style.position="relative",n.style.overflow="visible",n.style.transition="width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto",a.side==="left"?e.firstElementChild!==n&&e.replaceChildren(n,t):e.lastElementChild!==n&&e.replaceChildren(t,n)},Fd=(e,t)=>{let n=e.ownerDocument.createElement("div");return jl(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){jl(n,r)},destroy(){n.remove()}}},Nd=(e,t)=>{var p,y,m,C;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("aside"),c=n.createElement("div"),g=(y=(p=t==null?void 0:t.launcher)==null?void 0:p.enabled)==null||y?(C=(m=t==null?void 0:t.launcher)==null?void 0:m.autoExpand)!=null?C:!1:!0;return i.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(a,e),i.appendChild(e),a.appendChild(i),a.appendChild(d),To(a,i,d,c,t,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,To(a,i,d,c,t,g))},updateConfig(v){var E,x;t=v,((x=(E=t==null?void 0:t.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),To(a,i,d,c,t,g)},destroy(){r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Hs=(e,t)=>Ut(t)?Nd(e,t):Fd(e,t);var Mo={},Od=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},Dd=()=>{try{if(typeof Mo!="undefined"&&Mo.url)return new URL("../widget.css",Mo.url).href}catch{}return null},Vl=(e,t)=>{let n=Dd(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},ql=e=>{var E;let t=Od(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Hs(t,o),a,i=[],d=(x,k)=>{var S,N;let M=!((N=(S=k==null?void 0:k.launcher)==null?void 0:S.enabled)!=null?N:!0)||Ut(k),O=r.createElement("div");if(O.id="persona-root",M&&(O.style.height="100%",O.style.display="flex",O.style.flexDirection="column",O.style.flex="1",O.style.minHeight="0"),n){let Z=x.attachShadow({mode:"open"});Z.appendChild(O),Vl(Z,r)}else x.appendChild(O),Vl(x,r);return t.id&&O.setAttribute("data-persona-instance",t.id),O},c=()=>{s.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(s.host,o);a=Eo(x,o,{debugTools:e.debugTools}),g()},y=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{y(),s.destroy(),s=Hs(t,x),o=x,p()},C={update(x){var O,S,N,Z,K,re;let k={...o,...x,launcher:{...(O=o==null?void 0:o.launcher)!=null?O:{},...(S=x==null?void 0:x.launcher)!=null?S:{},dock:{...(Z=(N=o==null?void 0:o.launcher)==null?void 0:N.dock)!=null?Z:{},...(re=(K=x==null?void 0:x.launcher)==null?void 0:K.dock)!=null?re:{}}}},U=Ut(o),M=Ut(k);if(U!==M){m(k);return}o=k,s.updateConfig(o),a.update(x),c()},destroy(){y(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,U){if(k==="host")return s.host;if(k in x)return Reflect.get(x,k,U);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Yl=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_d=new Set(["button","a","input","select","textarea","details","summary"]),jd=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ko=/\b(product|card|item|listing|result)\b/i,Po=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vd=3e3,qd=100;function Xl(e){let t=typeof e.className=="string"?e.className:"";if(ko.test(t)||e.id&&ko.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&ko.test(r.value))return!0}return!1}function Gl(e){var t;return Po.test(((t=e.textContent)!=null?t:"").trim())}function Zl(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ud(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ul(e){let t=e.match(Po);return t?t[0]:null}function zl(e){var r,o,s;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((o=t.textContent)!=null&&o.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function zd(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var Jd="commerce-card",Kd="result-card";function Jl(e){return!Xl(e)||!Gl(e)||!Zl(e)&&!Ud(e)?0:5200}function Kl(e){var r;return!Xl(e)||Gl(e)||!Zl(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ql=[{id:Jd,scoreElement(e){return Jl(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||Po.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,c,g;if(Jl(e)===0)return null;let{title:n,href:r}=zl(e),o=(g=(c=Ul(((d=e.textContent)!=null?d:"").trim()))!=null?c:Ul(t.text))!=null?g:"",s=zd(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
96
|
-
`)}},{id:Kd,scoreElement(e){return Kl(e)},formatSummary(e,
|
|
97
|
-
`)}}];function Yd(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Xd(e){var g,p,y,m,C,v,E,x,k,U,M,O,S;let
|
|
95
|
+
`}if(!A&&!l){let Tn="max-height: -moz-available !important; max-height: stretch !important;",Yt=u?"":"padding-top: 1.25em !important;";le.style.cssText+=Tn+Yt}};On(),Yn(e,r),Ls(e,r),Ps(e,r);let xt=[];gn&&xt.push(()=>{gn==null||gn.disconnect(),gn=null}),xt.push(()=>{tn==null||tn(),tn=null,Gn(),dt&&(dt.remove(),dt=null),Ge==null||Ge.element.style.removeProperty("width"),Ge==null||Ge.element.style.removeProperty("maxWidth")}),Le&&xt.push(()=>{he!==null&&(cancelAnimationFrame(he),he=null),j==null||j.destroy(),j=null,V==null||V.destroy(),V=null,ee=null});let hn=null,Sr=()=>{hn&&(hn(),hn=null),r.colorScheme==="auto"&&(hn=oo(()=>{Yn(e,r)}))};Sr(),xt.push(()=>{hn&&(hn(),hn=null)});let In=El(Ke),yn=null,W,Wn=!1,Rn=pl(),Ar=0,Cn=!0,Dn=0,Er=0,wn=null,Sn=!1,Zn=0,Qn=!1,ns=125,rs=2e3,ss=5,Tr=50,er=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Mr=(zo=(Uo=r.voiceRecognition)==null?void 0:Uo.autoResume)!=null?zo:!1,nn=l=>{s.emit("voice:state",{active:qe.active,source:l,timestamp:Date.now()})},zt=()=>{p(l=>({...l,voiceState:{active:qe.active,timestamp:Date.now(),manuallyDeactivated:qe.manuallyDeactivated}}))},os=()=>{var A,L;if(((A=r.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Ao(i.voiceState),u=!!l.active,h=Number((L=l.timestamp)!=null?L:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-h<Wd&&setTimeout(()=>{var $,R;qe.active||(qe.manuallyDeactivated=!1,((R=($=r.voiceRecognition)==null?void 0:$.provider)==null?void 0:R.type)==="runtype"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("restore"),W.isVoiceActive()&&Hn()}):Vn("restore"))},1e3)},as=()=>W?Dl(W.getMessages()).filter(l=>!l.__skipPersist):[];function kr(l){if(!(a!=null&&a.save))return;let h={messages:l?Dl(l):W?as():[],metadata:i};try{let A=a.save(h);A instanceof Promise&&A.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let _n=(l=!1)=>{if(!Cn)return;let u=Date.now();Sn&&u<Zn&&!l||(Sn&&u>=Zn&&(Sn=!1),!(!l&&!Wn)&&(u-Er<ns||(Er=u,wn&&cancelAnimationFrame(wn),wn=requestAnimationFrame(()=>{Sn||!Cn||(Qn=!0,oe.scrollTop=oe.scrollHeight,Dn=oe.scrollTop,requestAnimationFrame(()=>{Qn=!1}),wn=null)}))))},An=null,is=()=>le.querySelector("#persona-scroll-container")||oe,ls=(l,u=500)=>{let h=l.scrollTop,A=l.clientHeight,L=l.scrollHeight,$=L-h;if(h+A>=L-2||Math.abs($)<5)return;An!==null&&(cancelAnimationFrame(An),An=null);let D=performance.now(),B=ge=>1-Math.pow(1-ge,3),me=ge=>{let Me=l.scrollHeight;Me!==L&&(L=Me,$=L-h);let je=ge-D,xe=Math.min(je/u,1),P=B(xe),ke=h+$*P;l.scrollTop=ke,xe<1?An=requestAnimationFrame(me):(l.scrollTop=l.scrollHeight,An=null)};An=requestAnimationFrame(me)},cs=l=>{let u=new Map;l.forEach(h=>{let A=er.get(h.id);u.set(h.id,{streaming:h.streaming,role:h.role}),!A&&h.role==="assistant"&&s.emit("assistant:message",h),h.role==="assistant"&&(A!=null&&A.streaming)&&h.streaming===!1&&s.emit("assistant:complete",h),h.variant==="approval"&&h.approval&&(A?h.approval.status!=="pending"&&s.emit("approval:resolved",{approval:h.approval,decision:h.approval.status}):s.emit("approval:requested",{approval:h.approval,message:h}))}),er.clear(),u.forEach((h,A)=>{er.set(A,h)})},jn=(l,u,h)=>{var ge,Me,je,xe;let A=document.createElement("div"),$=(()=>{var ke;let P=o.find(Ae=>Ae.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((ke=r.loadingIndicator)!=null&&ke.render)return r.loadingIndicator.render})(),R=new Set;u.forEach(P=>{var St,ct;R.add(P.id);let ke=dl(P,Ar),Ae=ul(Rn,P.id,ke);if(Ae){A.appendChild(Ae.cloneNode(!0));return}let F=null,We=o.find(ot=>!!(P.variant==="reasoning"&&ot.renderReasoning||P.variant==="tool"&&ot.renderToolCall||P.variant==="approval"&&ot.renderApproval||!P.variant&&ot.renderMessage)),st=(St=r.layout)==null?void 0:St.messages;if(We)if(P.variant==="reasoning"&&P.reasoning&&We.renderReasoning){if(!J)return;F=We.renderReasoning({message:P,defaultRenderer:()=>io(P),config:r})}else if(P.variant==="tool"&&P.toolCall&&We.renderToolCall){if(!pe)return;F=We.renderToolCall({message:P,defaultRenderer:()=>lo(P,r),config:r})}else if(P.variant==="approval"&&P.approval&&We.renderApproval){if(r.approval===!1)return;F=We.renderApproval({message:P,defaultRenderer:()=>co(P,r),config:r})}else We.renderMessage&&(F=We.renderMessage({message:P,defaultRenderer:()=>{let ot=Xr(P,h,st,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r});return P.role!=="user"&&go(ot,P,r,W),ot},config:r}));if(!F&&P.role==="assistant"&&!P.variant&&r.enableComponentStreaming!==!1&&vo(P)){let Kt=Co(P);if(Kt){let ve=xo(Kt,{config:r,message:P,transform:h});if(ve)if(r.wrapComponentDirectiveInBubble!==!1){let $t=document.createElement("div");if($t.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${P.id}`,$t.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),$t.appendChild(sn)}$t.appendChild(ve),F=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${P.id}`,$t.setAttribute("data-message-id",P.id),$t.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let sn=document.createElement("div");sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",sn.innerHTML=h({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),$t.appendChild(sn)}$t.appendChild(ve),F=$t}}}if(!F)if(P.variant==="reasoning"&&P.reasoning){if(!J)return;F=io(P)}else if(P.variant==="tool"&&P.toolCall){if(!pe)return;F=lo(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;F=co(P,r)}else{let ot=(ct=r.layout)==null?void 0:ct.messages;ot!=null&&ot.renderUserMessage&&P.role==="user"?F=ot.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):ot!=null&&ot.renderAssistantMessage&&P.role==="assistant"?F=ot.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):F=Xr(P,h,ot,r.messageActions,lt,{loadingIndicatorRenderer:$,widgetConfig:r}),P.role!=="user"&&F&&go(F,P,r,W)}let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id=`wrapper-${P.id}`,Ze.setAttribute("data-wrapper-id",P.id),P.role==="user"&&Ze.classList.add("persona-justify-end"),(F==null?void 0:F.getAttribute("data-persona-component-directive"))==="true"&&Ze.classList.add("persona-w-full"),Ze.appendChild(F),gl(Rn,P.id,ke,Ze),A.appendChild(Ze)}),ml(Rn,R);let D=u.some(P=>P.role==="assistant"&&P.streaming),B=u[u.length-1],me=(B==null?void 0:B.role)==="assistant"&&!B.streaming&&B.variant!=="approval";if(Wn&&u.some(P=>P.role==="user")&&!D&&!me){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:gr},ke=o.find(F=>F.renderLoadingIndicator),Ae=null;if(ke!=null&&ke.renderLoadingIndicator&&(Ae=ke.renderLoadingIndicator(P)),Ae===null&&((ge=r.loadingIndicator)!=null&&ge.render)&&(Ae=r.loadingIndicator.render(P)),Ae===null&&(Ae=gr()),Ae){let F=document.createElement("div"),We=((Me=r.loadingIndicator)==null?void 0:Me.showBubble)!==!1;F.className=We?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),F.setAttribute("data-typing-indicator","true"),F.appendChild(Ae);let st=document.createElement("div");st.className="persona-flex",st.id="wrapper-typing-indicator",st.setAttribute("data-wrapper-id","typing-indicator"),st.appendChild(F),A.appendChild(st)}}if(!Wn&&u.length>0){let P=u[u.length-1],ke={config:r,lastMessage:P,messageCount:u.length},Ae=o.find(We=>We.renderIdleIndicator),F=null;if(Ae!=null&&Ae.renderIdleIndicator&&(F=Ae.renderIdleIndicator(ke)),F===null&&((je=r.loadingIndicator)!=null&&je.renderIdle)&&(F=r.loadingIndicator.renderIdle(ke)),F){let We=document.createElement("div"),st=((xe=r.loadingIndicator)==null?void 0:xe.showBubble)!==!1;We.className=st?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),We.setAttribute("data-idle-indicator","true"),We.appendChild(F);let Ze=document.createElement("div");Ze.className="persona-flex",Ze.id="wrapper-idle-indicator",Ze.setAttribute("data-wrapper-id","idle-indicator"),Ze.appendChild(We),A.appendChild(Ze)}}cl(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let P=is();ls(P)})})},tr=()=>{if(!v)return;let l=Ut(r);S?(le.style.display=l?"flex":"",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-95","persona-opacity-0"),se.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":Ne&&(Ne.style.display="none")):(l?(le.style.display="none",le.classList.remove("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(le.style.display="",le.classList.add("persona-pointer-events-none","persona-opacity-0"),se.classList.remove("persona-scale-100","persona-opacity-100"),se.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":Ne&&(Ne.style.display=""))},ft=(l,u="user")=>{if(!v||S===l)return;let h=S;S=l,tr(),S&&(vt(),_n(!0));let A={open:S,source:u,timestamp:Date.now()};S&&!h?s.emit("widget:opened",A):!S&&h&&s.emit("widget:closed",A),s.emit("widget:state",{open:S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()})},nr=l=>{X.disabled=l,H&&(H.disabled=l),In.buttons.forEach(u=>{u.disabled=l}),Xe.dataset.personaComposerStreaming=l?"true":"false",Xe.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},rr=()=>{qe.active||te&&te.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>rr(),200)});let Lr=()=>{var L,$,R,D,B,me,ge,Me,je,xe,P,ke,Ae,F;jt.textContent=($=(L=r.copy)==null?void 0:L.welcomeTitle)!=null?$:"Hello \u{1F44B}",Dt.textContent=(D=(R=r.copy)==null?void 0:R.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",te.placeholder=(me=(B=r.copy)==null?void 0:B.inputPlaceholder)!=null?me:"How can I help...",(Me=(ge=r.sendButton)==null?void 0:ge.useIcon)!=null&&Me||(X.textContent=(xe=(je=r.copy)==null?void 0:je.sendButtonLabel)!=null?xe:"Send");let u=(ke=(P=r.theme)==null?void 0:P.inputFontFamily)!=null?ke:"sans-serif",h=(F=(Ae=r.theme)==null?void 0:Ae.inputFontWeight)!=null?F:"400",A=We=>{switch(We){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};te.style.fontFamily=A(u),te.style.fontWeight=h};if(r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),W=new qr(r,{onMessagesChanged(l){jn(Ee,l,re),W&&(l.some(L=>L.role==="user")?In.render([],W,te,l):In.render(r.suggestionChips,W,te,l,r.suggestionChipsConfig)),_n(!Wn),cs(l);let u=[...l].reverse().find(A=>A.role==="user"),h=qe.lastUserMessageId;u&&u.id!==h&&(qe.lastUserMessageId=u.id,s.emit("user:message",u)),qe.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),kr(l)},onStatusChanged(l){var A;let u=(A=r.statusIndicator)!=null?A:{},h=L=>{var $,R,D,B;return L==="idle"?($=u.idleText)!=null?$:_t.idle:L==="connecting"?(R=u.connectingText)!=null?R:_t.connecting:L==="connected"?(D=u.connectedText)!=null?D:_t.connected:L==="error"?(B=u.errorText)!=null?B:_t.error:_t[L]};et.textContent=h(l)},onStreamingChanged(l){Wn=l,nr(l),W&&jn(Ee,W.getMessages(),re),l||_n(!0)},onVoiceStatusChanged(l){var u,h;if(((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype")switch(l){case"listening":break;case"processing":cn(),ps();break;case"speaking":cn(),us();break;default:l==="idle"&&W.isBargeInActive()?(cn(),Hn(),H==null||H.setAttribute("aria-label","End voice session")):(qe.active=!1,cn(),nn("system"),zt());break}},onArtifactsState(l){Pn=l,fn()}}),vr.current=W,((Ko=(Jo=r.voiceRecognition)==null?void 0:Jo.provider)==null?void 0:Ko.type)==="runtype")try{W.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&W.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),V&&W.setSSEEventCallback((l,u)=>{V==null||V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(i=Ao(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&W.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Pr=l=>{var L;l.preventDefault();let u=te.value.trim(),h=(L=Be==null?void 0:Be.hasAttachments())!=null?L:!1;if(!u&&!h)return;let A;h&&(A=[],A.push(...Be.getContentParts()),u&&A.push(Gs(u))),te.value="",te.style.height="auto",W.sendMessage(u,{contentParts:A}),h&&Be.clearAttachments()},Ir=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),X.click())},Wr=async l=>{var h;if(((h=r.attachments)==null?void 0:h.enabled)!==!0||!Be)return;let u=Hd(l.clipboardData);u.length!==0&&(l.preventDefault(),await Be.handleFiles(u))},Vt=null,Zt=!1,En=null,Re=null,Rr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vn=(l="user")=>{var $,R,D,B,me,ge,Me,je;if(Zt||W.isStreaming())return;let u=Rr();if(!u)return;Vt=new u;let A=(R=(($=r.voiceRecognition)!=null?$:{}).pauseDuration)!=null?R:2e3;Vt.continuous=!0,Vt.interimResults=!0,Vt.lang="en-US";let L=te.value;Vt.onresult=xe=>{let P="",ke="";for(let F=0;F<xe.results.length;F++){let We=xe.results[F],st=We[0].transcript;We.isFinal?P+=st+" ":ke=st}let Ae=L+P+ke;te.value=Ae,En&&clearTimeout(En),(P||ke)&&(En=window.setTimeout(()=>{let F=te.value.trim();F&&Vt&&Zt&&(ln(),te.value="",te.style.height="auto",W.sendMessage(F,{viaVoice:!0}))},A))},Vt.onerror=xe=>{xe.error!=="no-speech"&&ln()},Vt.onend=()=>{if(Zt){let xe=te.value.trim();xe&&xe!==L.trim()&&(te.value="",te.style.height="auto",W.sendMessage(xe,{viaVoice:!0})),ln()}};try{if(Vt.start(),Zt=!0,qe.active=!0,l!=="system"&&(qe.manuallyDeactivated=!1),nn(l),zt(),H){let xe=(D=r.voiceRecognition)!=null?D:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(B=xe.iconName)!=null?B:"mic",iconSize:parseFloat((Me=(ge=xe.iconSize)!=null?ge:(me=r.sendButton)==null?void 0:me.size)!=null?Me:"40")||24};let P=(je=xe.recordingBackgroundColor)!=null?je:"#ef4444",ke=xe.recordingIconColor,Ae=xe.recordingBorderColor;if(H.classList.add("persona-voice-recording"),H.style.backgroundColor=P,ke){H.style.color=ke;let F=H.querySelector("svg");F&&F.setAttribute("stroke",ke)}Ae&&(H.style.borderColor=Ae),H.setAttribute("aria-label","Stop voice recognition")}}catch{ln("system")}},ln=(l="user")=>{if(Zt){if(Zt=!1,En&&(clearTimeout(En),En=null),Vt){try{Vt.stop()}catch{}Vt=null}if(qe.active=!1,nn(l),zt(),H){if(H.classList.remove("persona-voice-recording"),Re){H.style.backgroundColor=Re.backgroundColor,H.style.color=Re.color,H.style.borderColor=Re.borderColor;let u=H.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}H.setAttribute("aria-label","Start voice recognition")}}},ds=(l,u)=>{var F,We,st,Ze,St,ct,ot,Kt;let h=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((F=l==null?void 0:l.provider)==null?void 0:F.type)==="runtype";if(!(h||A))return null;let $=f("div","persona-send-button-wrapper"),R=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");R.type="button",R.setAttribute("aria-label","Start voice recognition");let D=(We=l==null?void 0:l.iconName)!=null?We:"mic",B=(st=u==null?void 0:u.size)!=null?st:"40px",me=(Ze=l==null?void 0:l.iconSize)!=null?Ze:B,ge=parseFloat(me)||24,Me=(St=l==null?void 0:l.backgroundColor)!=null?St:u==null?void 0:u.backgroundColor,je=(ct=l==null?void 0:l.iconColor)!=null?ct:u==null?void 0:u.textColor;R.style.width=me,R.style.height=me,R.style.minWidth=me,R.style.minHeight=me,R.style.fontSize="18px",R.style.lineHeight="1";let xe=je||"currentColor",P=ue(D,ge,xe,1.5);P?(R.appendChild(P),R.style.color=xe):(R.textContent="\u{1F3A4}",R.style.color=xe),Me?R.style.backgroundColor=Me:R.classList.add("persona-bg-persona-primary"),je?R.style.color=je:!je&&!(u!=null&&u.textColor)&&R.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(R.style.borderWidth=l.borderWidth,R.style.borderStyle="solid"),l!=null&&l.borderColor&&(R.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(R.style.paddingLeft=l.paddingX,R.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(R.style.paddingTop=l.paddingY,R.style.paddingBottom=l.paddingY),$.appendChild(R);let ke=(ot=l==null?void 0:l.tooltipText)!=null?ot:"Start voice recognition";if(((Kt=l==null?void 0:l.showTooltip)!=null?Kt:!1)&&ke){let ve=f("div","persona-send-button-tooltip");ve.textContent=ke,$.appendChild(ve)}return{micButton:R,micButtonWrapper:$}},sr=()=>{var u,h,A,L,$;if(!H||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:H.style.backgroundColor,color:H.style.color,borderColor:H.style.borderColor,iconName:(h=l.iconName)!=null?h:"mic",iconSize:parseFloat(($=(L=l.iconSize)!=null?L:(A=r.sendButton)==null?void 0:A.size)!=null?$:"40")||24}},or=(l,u)=>{var $,R,D,B,me;if(!H)return;let h=H.querySelector("svg");h&&h.remove();let A=(me=Re==null?void 0:Re.iconSize)!=null?me:parseFloat((B=(D=($=r.voiceRecognition)==null?void 0:$.iconSize)!=null?D:(R=r.sendButton)==null?void 0:R.size)!=null?B:"40")||24,L=ue(l,A,u,1.5);L&&H.appendChild(L)},qn=()=>{H&&H.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Hn=()=>{var L,$;if(!H)return;sr();let l=(L=r.voiceRecognition)!=null?L:{},u=($=l.recordingBackgroundColor)!=null?$:"#ef4444",h=l.recordingIconColor,A=l.recordingBorderColor;if(qn(),H.classList.add("persona-voice-recording"),H.style.backgroundColor=u,h){H.style.color=h;let R=H.querySelector("svg");R&&R.setAttribute("stroke",h)}A&&(H.style.borderColor=A),H.setAttribute("aria-label","Stop voice recognition")},ps=()=>{var D,B,me,ge,Me,je,xe,P;if(!H)return;sr();let l=(D=r.voiceRecognition)!=null?D:{},u=W.getVoiceInterruptionMode(),h=(B=l.processingIconName)!=null?B:"loader",A=(ge=(me=l.processingIconColor)!=null?me:Re==null?void 0:Re.color)!=null?ge:"",L=(je=(Me=l.processingBackgroundColor)!=null?Me:Re==null?void 0:Re.backgroundColor)!=null?je:"",$=(P=(xe=l.processingBorderColor)!=null?xe:Re==null?void 0:Re.borderColor)!=null?P:"";qn(),H.classList.add("persona-voice-processing"),H.style.backgroundColor=L,H.style.borderColor=$;let R=A||"currentColor";H.style.color=R,or(h,R),H.setAttribute("aria-label","Processing voice input"),u==="none"&&(H.style.cursor="default")},us=()=>{var me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze;if(!H)return;sr();let l=(me=r.voiceRecognition)!=null?me:{},u=W.getVoiceInterruptionMode(),h=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",A=(ge=l.speakingIconName)!=null?ge:h,L=(P=l.speakingIconColor)!=null?P:u==="barge-in"?(je=(Me=l.recordingIconColor)!=null?Me:Re==null?void 0:Re.color)!=null?je:"":(xe=Re==null?void 0:Re.color)!=null?xe:"",$=(F=l.speakingBackgroundColor)!=null?F:u==="barge-in"?(ke=l.recordingBackgroundColor)!=null?ke:"#ef4444":(Ae=Re==null?void 0:Re.backgroundColor)!=null?Ae:"",R=(Ze=l.speakingBorderColor)!=null?Ze:u==="barge-in"?(We=l.recordingBorderColor)!=null?We:"":(st=Re==null?void 0:Re.borderColor)!=null?st:"";qn(),H.classList.add("persona-voice-speaking"),H.style.backgroundColor=$,H.style.borderColor=R;let D=L||"currentColor";H.style.color=D,or(A,D);let B=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";H.setAttribute("aria-label",B),u==="none"&&(H.style.cursor="default"),u==="barge-in"&&H.classList.add("persona-voice-recording")},cn=()=>{var l,u,h;H&&(qn(),Re&&(H.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",H.style.color=(u=Re.color)!=null?u:"",H.style.borderColor=(h=Re.borderColor)!=null?h:"",or(Re.iconName,Re.color||"currentColor"),Re=null),H.style.cursor="",H.setAttribute("aria-label","Start voice recognition"))},Un=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let h=W.getVoiceStatus(),A=W.getVoiceInterruptionMode();if(A==="none"&&(h==="processing"||h==="speaking"))return;if(A==="cancel"&&(h==="processing"||h==="speaking")){W.stopVoicePlayback();return}if(W.isBargeInActive()){W.stopVoicePlayback(),W.deactivateBargeIn().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()});return}W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),qe.manuallyDeactivated=!W.isVoiceActive(),zt(),nn("user"),W.isVoiceActive()?Hn():cn()});return}if(Zt){let h=te.value.trim();qe.manuallyDeactivated=!0,zt(),ln("user"),h&&(te.value="",te.style.height="auto",W.sendMessage(h))}else qe.manuallyDeactivated=!1,zt(),Vn("user")};ut=Un,H&&(H.addEventListener("click",Un),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(W.isVoiceActive()&&W.toggleVoice(),cn()):ln("system"),H&&H.removeEventListener("click",Un)}));let gs=s.on("assistant:complete",()=>{Mr&&(qe.active||qe.manuallyDeactivated||Mr==="assistant"&&!qe.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!qe.active&&!qe.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("auto"),W.isVoiceActive()&&Hn()}):Vn("auto"))},600))});xt.push(gs);let G=s.on("action:resubmit",()=>{setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)});xt.push(G);let Fe=()=>{ft(!S,"user")},we=null,Ne=null;if(v){let l=o.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>Jr(r,Fe).element,onToggle:Fe});u&&(Ne=u)}Ne||(we=Jr(r,Fe))}we?e.appendChild(we.element):Ne&&e.appendChild(Ne),tr(),In.render(r.suggestionChips,W,te,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming()),_n(!0),os(),x&&(v?S&&setTimeout(()=>rr(),200):setTimeout(()=>rr(),0));let vt=()=>{var B,me,ge,Me,je,xe,P,ke,Ae,F,We,st,Ze;let l=Ut(r),u=(me=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?me:!1,h=l||u||((Me=(ge=r.launcher)==null?void 0:ge.fullHeight)!=null?Me:!1),A=(je=e.ownerDocument.defaultView)!=null?je:window,L=(P=(xe=r.launcher)==null?void 0:xe.mobileFullscreen)!=null?P:!0,$=(Ae=(ke=r.launcher)==null?void 0:ke.mobileBreakpoint)!=null?Ae:640,R=A.innerWidth<=$;if(L&&R&&v){On(),Yn(e,r);return}if(O&&(O=!1,On(),Yn(e,r)),!v&&!l){se.style.height="",se.style.width="";return}if(!u&&!l){let St=(We=(F=r==null?void 0:r.launcher)==null?void 0:F.width)!=null?We:r==null?void 0:r.launcherWidth,ct=St!=null?St:"min(400px, calc(100vw - 24px))";se.style.width=ct,se.style.maxWidth=ct}if(Nn(),!h){let St=A.innerHeight,ct=64,ot=(Ze=(st=r.launcher)==null?void 0:st.heightOffset)!=null?Ze:0,Kt=Math.max(200,St-ct),ve=Math.min(640,Kt),pt=Math.max(200,ve-ot);se.style.height=`${pt}px`}};vt();let Nt=(Yo=e.ownerDocument.defaultView)!=null?Yo:window;Nt.addEventListener("resize",vt),xt.push(()=>Nt.removeEventListener("resize",vt)),Dn=oe.scrollTop;let Ct=()=>{let l=oe.scrollTop,u=oe.scrollHeight,h=oe.clientHeight,A=u-l-h,L=Math.abs(l-Dn);if(Dn=l,!Qn&&!(L<=ss)){if(!Cn&&A<Tr){Sn=!1,Cn=!0;return}Cn&&A>Tr&&(Sn=!0,Zn=Date.now()+rs,Cn=!1)}};oe.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>oe.removeEventListener("scroll",Ct)),xt.push(()=>{wn&&cancelAnimationFrame(wn)});let b=()=>{ie&&(yn&&(ie.removeEventListener("click",yn),yn=null),v?(ie.style.display="",yn=()=>{ft(!1,"user")},ie.addEventListener("click",yn)):ie.style.display="none")};b(),(()=>{let{clearChatButton:l}=q;l&&l.addEventListener("click",()=>{W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(h){console.error("[AgentWidget] Failed to clear default localStorage:",h)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(h){console.error("[AgentWidget] Failed to clear custom localStorage:",h)}let u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),a!=null&&a.clear)try{let h=a.clear();h instanceof Promise&&h.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(h){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)}i={},C.syncFromMetadata(),V==null||V.clear(),j==null||j.update()})})(),Ve&&Ve.addEventListener("submit",Pr),te==null||te.addEventListener("keydown",Ir),te==null||te.addEventListener("paste",Wr),xt.push(()=>{Ve&&Ve.removeEventListener("submit",Pr),te==null||te.removeEventListener("keydown",Ir),te==null||te.removeEventListener("paste",Wr)}),xt.push(()=>{W.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):Ne&&xt.push(()=>{Ne==null||Ne.remove()});let T={update(l){var na,ra,sa,oa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,$a,Fa,Na,Oa,Da,_a,ja,Va,qa,Ua,za,Ja,Ka,Ya,Xa,Ga,Za,Qa,ei,ti,ni,ri,si,oi,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,$i,Fi,Ni,Oi;let u=r.toolCall,h=r.messageActions,A=(na=r.layout)==null?void 0:na.messages,L=r.colorScheme;r={...r,...l},On(),Yn(e,r),Ls(e,r),Ps(e,r),fn(),r.colorScheme!==L&&Sr();let $=Is.getForInstance(r.plugins);o.length=0,o.push(...$),v=(sa=(ra=r.launcher)==null?void 0:ra.enabled)!=null?sa:!0,E=(aa=(oa=r.launcher)==null?void 0:oa.autoExpand)!=null?aa:!1,J=(la=(ia=r.features)==null?void 0:ia.showReasoning)!=null?la:!0,pe=(da=(ca=r.features)==null?void 0:ca.showToolCalls)!=null?da:!0;let R=Le;if(Le=(ua=(pa=r.features)==null?void 0:pa.showEventStreamToggle)!=null?ua:!1,Le&&!R){if(V||(ee=new Zr(fe),V=new Gr(Y,ee),ee.open().then(()=>V==null?void 0:V.restore()).catch(()=>{}),W.setSSEEventCallback((_,ze)=>{V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:_,timestamp:Date.now(),payload:JSON.stringify(ze)})})),!de&&_e){let _=(ma=(ga=r.features)==null?void 0:ga.eventStream)==null?void 0:ma.classNames,ze="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(_!=null&&_.toggleButton?" "+_.toggleButton:"");de=f("button",ze),de.style.width="28px",de.style.height="28px",de.type="button",de.setAttribute("aria-label","Event Stream"),de.title="Event Stream";let ht=ue("activity","18px","currentColor",1.5);ht&&de.appendChild(ht);let Oe=q.clearChatButtonWrapper,Qe=q.closeButtonWrapper,Pt=Oe||Qe;Pt&&Pt.parentNode===_e?_e.insertBefore(de,Pt):_e.appendChild(de),de.addEventListener("click",()=>{ce?$e():be()})}}else!Le&&R&&($e(),de&&(de.remove(),de=null),V==null||V.clear(),ee==null||ee.destroy(),V=null,ee=null);if(((fa=r.launcher)==null?void 0:fa.enabled)===!1&&we&&(we.destroy(),we=null),((ha=r.launcher)==null?void 0:ha.enabled)===!1&&Ne&&(Ne.remove(),Ne=null),((ya=r.launcher)==null?void 0:ya.enabled)!==!1&&!we&&!Ne){let _=o.find(ze=>ze.renderLauncher);if(_!=null&&_.renderLauncher){let ze=_.renderLauncher({config:r,defaultRenderer:()=>Jr(r,Fe).element,onToggle:Fe});ze&&(Ne=ze,e.appendChild(Ne))}Ne||(we=Jr(r,Fe),e.appendChild(we.element))}we&&we.update(r),Te&&((ba=r.launcher)==null?void 0:ba.title)!==void 0&&(Te.textContent=r.launcher.title),tt&&((xa=r.launcher)==null?void 0:xa.subtitle)!==void 0&&(tt.textContent=r.launcher.subtitle);let D=(va=r.layout)==null?void 0:va.header;if((D==null?void 0:D.layout)!==M&&_e){let _=D?Kr(r,D,{showClose:v,onClose:()=>ft(!1,"user")}):$n({config:r,showClose:v,onClose:()=>ft(!1,"user")});_e.replaceWith(_.header),_e=_.header,Ue=_.iconHolder,Te=_.headerTitle,tt=_.headerSubtitle,ie=_.closeButton,M=D==null?void 0:D.layout}else if(D&&(Ue&&(Ue.style.display=D.showIcon===!1?"none":""),Te&&(Te.style.display=D.showTitle===!1?"none":""),tt&&(tt.style.display=D.showSubtitle===!1?"none":""),ie&&(ie.style.display=D.showCloseButton===!1?"none":""),q.clearChatButtonWrapper)){let _=D.showClearChat;if(_!==void 0){q.clearChatButtonWrapper.style.display=_?"":"none";let{closeButtonWrapper:ze}=q;ze&&!ze.classList.contains("persona-absolute")&&(_?ze.classList.remove("persona-ml-auto"):ze.classList.add("persona-ml-auto"))}}let me=((Ca=r.layout)==null?void 0:Ca.showHeader)!==!1;_e&&(_e.style.display=me?"":"none");let ge=((wa=r.layout)==null?void 0:wa.showFooter)!==!1;Xe&&(Xe.style.display=ge?"":"none"),v!==U?v?ft(E,"auto"):(S=!0,tr()):E!==k&&ft(E,"auto"),k=E,U=v,vt(),b();let xe=JSON.stringify(l.toolCall)!==JSON.stringify(u),P=JSON.stringify(r.messageActions)!==JSON.stringify(h),ke=JSON.stringify((Sa=r.layout)==null?void 0:Sa.messages)!==JSON.stringify(A);(xe||P||ke)&&W&&(Ar++,jn(Ee,W.getMessages(),re));let F=(Aa=r.launcher)!=null?Aa:{},We=(Ea=F.headerIconHidden)!=null?Ea:!1,st=(Ma=(Ta=r.layout)==null?void 0:Ta.header)==null?void 0:Ma.showIcon,Ze=We||st===!1,St=F.headerIconName,ct=(ka=F.headerIconSize)!=null?ka:"48px";if(Ue){let _=ne.querySelector(".persona-border-b-persona-divider"),ze=_==null?void 0:_.querySelector(".persona-flex-col");if(Ze)Ue.style.display="none",_&&ze&&!_.contains(ze)&&_.insertBefore(ze,_.firstChild);else{if(Ue.style.display="",Ue.style.height=ct,Ue.style.width=ct,_&&ze&&(_.contains(Ue)?Ue.nextSibling!==ze&&(Ue.remove(),_.insertBefore(Ue,ze)):_.insertBefore(Ue,ze)),St){let Oe=parseFloat(ct)||24,Qe=ue(St,Oe*.6,"#ffffff",2);Qe?Ue.replaceChildren(Qe):Ue.textContent=(La=F.agentIconText)!=null?La:"\u{1F4AC}"}else if(F.iconUrl){let Oe=Ue.querySelector("img");if(Oe)Oe.src=F.iconUrl,Oe.style.height=ct,Oe.style.width=ct;else{let Qe=document.createElement("img");Qe.src=F.iconUrl,Qe.alt="",Qe.className="persona-rounded-xl persona-object-cover",Qe.style.height=ct,Qe.style.width=ct,Ue.replaceChildren(Qe)}}else{let Oe=Ue.querySelector("svg"),Qe=Ue.querySelector("img");(Oe||Qe)&&Ue.replaceChildren(),Ue.textContent=(Pa=F.agentIconText)!=null?Pa:"\u{1F4AC}"}let ht=Ue.querySelector("img");ht&&(ht.style.height=ct,ht.style.width=ct)}}let ot=(Wa=(Ia=r.layout)==null?void 0:Ia.header)==null?void 0:Wa.showTitle,Kt=(Ha=(Ra=r.layout)==null?void 0:Ra.header)==null?void 0:Ha.showSubtitle;if(Te&&(Te.style.display=ot===!1?"none":""),tt&&(tt.style.display=Kt===!1?"none":""),ie){(($a=(Ba=r.layout)==null?void 0:Ba.header)==null?void 0:$a.showCloseButton)===!1?ie.style.display="none":ie.style.display="";let ze=(Fa=F.closeButtonSize)!=null?Fa:"32px",ht=(Na=F.closeButtonPlacement)!=null?Na:"inline";ie.style.height=ze,ie.style.width=ze;let{closeButtonWrapper:Oe}=q,Qe=ht==="top-right",Pt=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&Qe!==Pt)if(Oe.remove(),Qe)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",ne.style.position="relative",ne.appendChild(Oe);else{let Je=(Da=(Oa=F.clearChat)==null?void 0:Oa.placement)!=null?Da:"inline",Ft=(ja=(_a=F.clearChat)==null?void 0:_a.enabled)!=null?ja:!0;Oe.className=Ft&&Je==="inline"?"":"persona-ml-auto";let Xt=ne.querySelector(".persona-border-b-persona-divider");Xt&&Xt.appendChild(Oe)}if(F.closeButtonColor?(ie.style.color=F.closeButtonColor,ie.classList.remove("persona-text-persona-muted")):(ie.style.color="",ie.classList.add("persona-text-persona-muted")),F.closeButtonBackgroundColor?(ie.style.backgroundColor=F.closeButtonBackgroundColor,ie.classList.remove("hover:persona-bg-gray-100")):(ie.style.backgroundColor="",ie.classList.add("hover:persona-bg-gray-100")),F.closeButtonBorderWidth||F.closeButtonBorderColor){let Je=F.closeButtonBorderWidth||"0px",Ft=F.closeButtonBorderColor||"transparent";ie.style.border=`${Je} solid ${Ft}`,ie.classList.remove("persona-border-none")}else ie.style.border="",ie.classList.add("persona-border-none");F.closeButtonBorderRadius?(ie.style.borderRadius=F.closeButtonBorderRadius,ie.classList.remove("persona-rounded-full")):(ie.style.borderRadius="",ie.classList.add("persona-rounded-full")),F.closeButtonPaddingX?(ie.style.paddingLeft=F.closeButtonPaddingX,ie.style.paddingRight=F.closeButtonPaddingX):(ie.style.paddingLeft="",ie.style.paddingRight=""),F.closeButtonPaddingY?(ie.style.paddingTop=F.closeButtonPaddingY,ie.style.paddingBottom=F.closeButtonPaddingY):(ie.style.paddingTop="",ie.style.paddingBottom="");let Ot=(Va=F.closeButtonIconName)!=null?Va:"x",Qt=(qa=F.closeButtonIconText)!=null?qa:"\xD7";ie.innerHTML="";let qt=ue(Ot,"20px",F.closeButtonColor||"",2);qt?ie.appendChild(qt):ie.textContent=Qt;let At=(Ua=F.closeButtonTooltipText)!=null?Ua:"Close chat",en=(za=F.closeButtonShowTooltip)!=null?za:!0;if(ie.setAttribute("aria-label",At),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),en&&At)){let Je=null,Ft=()=>{if(Je||!ie)return;let zn=ie.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ie.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};Oe.addEventListener("mouseenter",Ft),Oe.addEventListener("mouseleave",Xt),ie.addEventListener("focus",Ft),ie.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Ft),Oe.removeEventListener("mouseleave",Xt)),ie&&(ie.removeEventListener("focus",Ft),ie.removeEventListener("blur",Xt))}}}let{clearChatButton:ve,clearChatButtonWrapper:pt}=q;if(ve){let _=(Ja=F.clearChat)!=null?Ja:{},ze=(Ka=_.enabled)!=null?Ka:!0,ht=(Xa=(Ya=r.layout)==null?void 0:Ya.header)==null?void 0:Xa.showClearChat,Oe=ht!==void 0?ht:ze,Qe=(Ga=_.placement)!=null?Ga:"inline";if(pt){pt.style.display=Oe?"":"none";let{closeButtonWrapper:Pt}=q;Pt&&!Pt.classList.contains("persona-absolute")&&(Oe?Pt.classList.remove("persona-ml-auto"):Pt.classList.add("persona-ml-auto"));let Ot=Qe==="top-right",Qt=pt.classList.contains("persona-absolute");if(Ot!==Qt&&Oe){if(pt.remove(),Ot)pt.className="persona-absolute persona-top-4 persona-z-50",pt.style.right="48px",ne.style.position="relative",ne.appendChild(pt);else{pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",pt.style.right="";let At=ne.querySelector(".persona-border-b-persona-divider"),en=q.closeButtonWrapper;At&&en&&en.parentElement===At?At.insertBefore(pt,en):At&&At.appendChild(pt)}let qt=q.closeButtonWrapper;qt&&!qt.classList.contains("persona-absolute")&&(Ot?qt.classList.add("persona-ml-auto"):qt.classList.remove("persona-ml-auto"))}}if(Oe){let Pt=(Za=_.size)!=null?Za:"32px";ve.style.height=Pt,ve.style.width=Pt;let Ot=(Qa=_.iconName)!=null?Qa:"refresh-cw",Qt=(ei=_.iconColor)!=null?ei:"";ve.innerHTML="";let qt=ue(Ot,"20px",Qt||"",2);if(qt&&ve.appendChild(qt),Qt?(ve.style.color=Qt,ve.classList.remove("persona-text-persona-muted")):(ve.style.color="",ve.classList.add("persona-text-persona-muted")),_.backgroundColor?(ve.style.backgroundColor=_.backgroundColor,ve.classList.remove("hover:persona-bg-gray-100")):(ve.style.backgroundColor="",ve.classList.add("hover:persona-bg-gray-100")),_.borderWidth||_.borderColor){let Je=_.borderWidth||"0px",Ft=_.borderColor||"transparent";ve.style.border=`${Je} solid ${Ft}`,ve.classList.remove("persona-border-none")}else ve.style.border="",ve.classList.add("persona-border-none");_.borderRadius?(ve.style.borderRadius=_.borderRadius,ve.classList.remove("persona-rounded-full")):(ve.style.borderRadius="",ve.classList.add("persona-rounded-full")),_.paddingX?(ve.style.paddingLeft=_.paddingX,ve.style.paddingRight=_.paddingX):(ve.style.paddingLeft="",ve.style.paddingRight=""),_.paddingY?(ve.style.paddingTop=_.paddingY,ve.style.paddingBottom=_.paddingY):(ve.style.paddingTop="",ve.style.paddingBottom="");let At=(ti=_.tooltipText)!=null?ti:"Clear chat",en=(ni=_.showTooltip)!=null?ni:!0;if(ve.setAttribute("aria-label",At),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),en&&At)){let Je=null,Ft=()=>{if(Je||!ve)return;let zn=ve.ownerDocument,Nr=zn.body;if(!Nr)return;Je=bn(zn,"div","persona-clear-chat-tooltip"),Je.textContent=At;let Or=bn(zn,"div");Or.className="persona-clear-chat-tooltip-arrow",Je.appendChild(Or);let Jn=ve.getBoundingClientRect();Je.style.position="fixed",Je.style.left=`${Jn.left+Jn.width/2}px`,Je.style.top=`${Jn.top-8}px`,Je.style.transform="translate(-50%, -100%)",Nr.appendChild(Je)},Xt=()=>{Je&&Je.parentNode&&(Je.parentNode.removeChild(Je),Je=null)};pt.addEventListener("mouseenter",Ft),pt.addEventListener("mouseleave",Xt),ve.addEventListener("focus",Ft),ve.addEventListener("blur",Xt),pt._cleanupTooltip=()=>{Xt(),pt&&(pt.removeEventListener("mouseenter",Ft),pt.removeEventListener("mouseleave",Xt)),ve&&(ve.removeEventListener("focus",Ft),ve.removeEventListener("blur",Xt))}}}}let $t=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ws],sn=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[yr.message,yr.messageAndClick];C=Rs({parsers:$t,handlers:sn,getSessionMetadata:g,updateSessionMetadata:p,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),re=_l(r,C,K),W.updateConfig(r),jn(Ee,W.getMessages(),re),In.render(r.suggestionChips,W,te,void 0,r.suggestionChipsConfig),Lr(),nr(W.isStreaming());let ms=((ri=r.voiceRecognition)==null?void 0:ri.enabled)===!0,fs=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),hs=((oi=(si=r.voiceRecognition)==null?void 0:si.provider)==null?void 0:oi.type)==="runtype";if(ms&&(fs||hs))if(!H||!Z){let _=ds(r.voiceRecognition,r.sendButton);_&&(H=_.micButton,Z=_.micButtonWrapper,Mt.insertBefore(Z,He),H.addEventListener("click",Un),H.disabled=W.isStreaming())}else{let _=(ai=r.voiceRecognition)!=null?ai:{},ze=(ii=r.sendButton)!=null?ii:{},ht=(li=_.iconName)!=null?li:"mic",Oe=(ci=ze.size)!=null?ci:"40px",Qe=(di=_.iconSize)!=null?di:Oe,Pt=parseFloat(Qe)||24;H.style.width=Qe,H.style.height=Qe,H.style.minWidth=Qe,H.style.minHeight=Qe;let Ot=(ui=(pi=_.iconColor)!=null?pi:ze.textColor)!=null?ui:"currentColor";H.innerHTML="";let Qt=ue(ht,Pt,Ot,2);Qt?H.appendChild(Qt):H.textContent="\u{1F3A4}";let qt=(gi=_.backgroundColor)!=null?gi:ze.backgroundColor;qt?(H.style.backgroundColor=qt,H.classList.remove("persona-bg-persona-primary")):(H.style.backgroundColor="",H.classList.add("persona-bg-persona-primary")),Ot?(H.style.color=Ot,H.classList.remove("persona-text-white")):!Ot&&!ze.textColor&&(H.style.color="",H.classList.add("persona-text-white")),_.borderWidth?(H.style.borderWidth=_.borderWidth,H.style.borderStyle="solid"):(H.style.borderWidth="",H.style.borderStyle=""),_.borderColor?H.style.borderColor=_.borderColor:H.style.borderColor="",_.paddingX?(H.style.paddingLeft=_.paddingX,H.style.paddingRight=_.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),_.paddingY?(H.style.paddingTop=_.paddingY,H.style.paddingBottom=_.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let At=Z==null?void 0:Z.querySelector(".persona-send-button-tooltip"),en=(mi=_.tooltipText)!=null?mi:"Start voice recognition";if(((fi=_.showTooltip)!=null?fi:!1)&&en)if(At)At.textContent=en,At.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=en,Z==null||Z.insertBefore(Ft,H)}else At&&(At.style.display="none");Z.style.display="",H.disabled=W.isStreaming()}else H&&Z&&(Z.style.display="none",((yi=(hi=r.voiceRecognition)==null?void 0:hi.provider)==null?void 0:yi.type)==="runtype"?W.isVoiceActive()&&W.toggleVoice():Zt&&ln());if(((bi=r.attachments)==null?void 0:bi.enabled)===!0)if(!Pe||!z){let _=(xi=r.attachments)!=null?xi:{},ht=(Ci=((vi=r.sendButton)!=null?vi:{}).size)!=null?Ci:"40px";Ie||(Ie=f("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ie.style.display="none",Ve.insertBefore(Ie,te)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((wi=_.allowedTypes)!=null?wi:Mn).join(","),Ce.multiple=((Si=_.maxFiles)!=null?Si:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ve.insertBefore(Ce,te)),Pe=f("div","persona-send-button-wrapper"),z=f("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),z.type="button",z.setAttribute("aria-label",(Ai=_.buttonTooltipText)!=null?Ai:"Attach file");let Oe=(Ei=_.buttonIconName)!=null?Ei:"paperclip",Qe=ht,Pt=parseFloat(Qe)||40,Ot=Math.round(Pt*.6);z.style.width=Qe,z.style.height=Qe,z.style.minWidth=Qe,z.style.minHeight=Qe,z.style.fontSize="18px",z.style.lineHeight="1",z.style.backgroundColor="transparent",z.style.color="var(--persona-primary, #111827)",z.style.border="none",z.style.borderRadius="6px",z.style.transition="background-color 0.15s ease",z.addEventListener("mouseenter",()=>{z.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),z.addEventListener("mouseleave",()=>{z.style.backgroundColor="transparent"});let Qt=ue(Oe,Ot,"currentColor",1.5);Qt?z.appendChild(Qt):z.textContent="\u{1F4CE}",z.addEventListener("click",en=>{en.preventDefault(),Ce==null||Ce.click()}),Pe.appendChild(z);let qt=(Ti=_.buttonTooltipText)!=null?Ti:"Attach file",At=f("div","persona-send-button-tooltip");At.textContent=qt,Pe.appendChild(At),Rt.append(Pe),!Be&&Ce&&Ie&&(Be=pr.fromConfig(_),Be.setPreviewsContainer(Ie),Ce.addEventListener("change",async()=>{Be&&(Ce!=null&&Ce.files)&&(await Be.handleFileSelect(Ce.files),Ce.value="")}))}else{Pe.style.display="";let _=(Mi=r.attachments)!=null?Mi:{};Ce&&(Ce.accept=((ki=_.allowedTypes)!=null?ki:Mn).join(","),Ce.multiple=((Li=_.maxFiles)!=null?Li:4)>1),Be&&Be.updateConfig({allowedTypes:_.allowedTypes,maxFileSize:_.maxFileSize,maxFiles:_.maxFiles})}else Pe&&(Pe.style.display="none"),Be&&Be.clearAttachments();let Tt=(Pi=r.sendButton)!=null?Pi:{},ys=(Ii=Tt.useIcon)!=null?Ii:!1,Hr=(Wi=Tt.iconText)!=null?Wi:"\u2191",Br=Tt.iconName,ar=(Ri=Tt.tooltipText)!=null?Ri:"Send message",bs=(Hi=Tt.showTooltip)!=null?Hi:!1,Bn=(Bi=Tt.size)!=null?Bi:"40px",Tn=Tt.backgroundColor,Yt=Tt.textColor;if(ys){if(X.style.width=Bn,X.style.height=Bn,X.style.minWidth=Bn,X.style.minHeight=Bn,X.style.fontSize="18px",X.style.lineHeight="1",X.innerHTML="",Br){let _=parseFloat(Bn)||24,ze=Yt&&typeof Yt=="string"&&Yt.trim()?Yt.trim():"currentColor",ht=ue(Br,_,ze,2);ht?(X.appendChild(ht),X.style.color=ze):(X.textContent=Hr,Yt?X.style.color=Yt:X.classList.add("persona-text-white"))}else X.textContent=Hr,Yt?X.style.color=Yt:X.classList.add("persona-text-white");X.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-primary")):X.classList.add("persona-bg-persona-primary")}else X.textContent=(Fi=($i=r.copy)==null?void 0:$i.sendButtonLabel)!=null?Fi:"Send",X.style.width="",X.style.height="",X.style.minWidth="",X.style.minHeight="",X.style.fontSize="",X.style.lineHeight="",X.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",Tn?(X.style.backgroundColor=Tn,X.classList.remove("persona-bg-persona-accent")):X.classList.add("persona-bg-persona-accent"),Yt?X.style.color=Yt:X.classList.add("persona-text-white");Tt.borderWidth?(X.style.borderWidth=Tt.borderWidth,X.style.borderStyle="solid"):(X.style.borderWidth="",X.style.borderStyle=""),Tt.borderColor?X.style.borderColor=Tt.borderColor:X.style.borderColor="",Tt.paddingX?(X.style.paddingLeft=Tt.paddingX,X.style.paddingRight=Tt.paddingX):(X.style.paddingLeft="",X.style.paddingRight=""),Tt.paddingY?(X.style.paddingTop=Tt.paddingY,X.style.paddingBottom=Tt.paddingY):(X.style.paddingTop="",X.style.paddingBottom="");let $r=He==null?void 0:He.querySelector(".persona-send-button-tooltip");if(bs&&ar)if($r)$r.textContent=ar,$r.style.display="";else{let _=document.createElement("div");_.className="persona-send-button-tooltip",_.textContent=ar,He==null||He.insertBefore(_,X)}else $r&&($r.style.display="none");let Fr=(Ni=r.statusIndicator)!=null?Ni:{},dc=(Oi=Fr.visible)!=null?Oi:!0;if(et.style.display=dc?"":"none",W){let _=W.getStatus(),ze=ht=>{var Oe,Qe,Pt,Ot;return ht==="idle"?(Oe=Fr.idleText)!=null?Oe:_t.idle:ht==="connecting"?(Qe=Fr.connectingText)!=null?Qe:_t.connecting:ht==="connected"?(Pt=Fr.connectedText)!=null?Pt:_t.connected:ht==="error"?(Ot=Fr.errorText)!=null?Ot:_t.error:_t[ht]};et.textContent=ze(_)}},open(){v&&ft(!0,"api")},close(){v&&ft(!1,"api")},toggle(){v&&ft(!S,"api")},clearChat(){an=!1,W.clearMessages(),Rn.clear();try{localStorage.removeItem(br),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${br}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==br)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(h=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",h)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}i={},C.syncFromMetadata(),V==null||V.clear(),j==null||j.update()},setMessage(l){return!te||W.isStreaming()?!1:(!S&&v&&ft(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(W.isStreaming())return!1;let u=(l==null?void 0:l.trim())||te.value.trim();return u?(!S&&v&&ft(!0,"system"),te.value="",te.style.height="auto",W.sendMessage(u),!0):!1},startVoiceRecognition(){var u,h;return W.isStreaming()?!1:((h=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:h.type)==="runtype"?(W.isVoiceActive()||(!S&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),W.toggleVoice().then(()=>{qe.active=W.isVoiceActive(),nn("user"),W.isVoiceActive()&&Hn()})),!0):Zt?!0:Rr()?(!S&&v&&ft(!0,"system"),qe.manuallyDeactivated=!1,zt(),Vn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?W.isVoiceActive()?(W.toggleVoice().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,zt(),nn("user"),cn()}),!0):!1:Zt?(qe.manuallyDeactivated=!0,zt(),ln("user"),!0):!1},injectMessage(l){return!S&&v&&ft(!0,"system"),W.injectMessage(l)},injectAssistantMessage(l){!S&&v&&ft(!0,"system");let u=W.injectAssistantMessage(l);return N&&(N=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{W&&!W.isStreaming()&&W.continueConversation()},100)),u},injectUserMessage(l){return!S&&v&&ft(!0,"system"),W.injectUserMessage(l)},injectSystemMessage(l){return!S&&v&&ft(!0,"system"),W.injectSystemMessage(l)},injectMessageBatch(l){return!S&&v&&ft(!0,"system"),W.injectMessageBatch(l)},injectTestMessage(l){!S&&v&&ft(!0,"system"),W.injectTestEvent(l)},async connectStream(l,u){return W.connectStream(l,u)},__pushEventStreamEvent(l){V&&V.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Le||!V||be()},hideEventStream(){ce&&$e()},isEventStreamVisible(){return ce},showArtifacts(){on(r)&&(an=!1,fn(),Ge==null||Ge.setMobileOpen(!0))},hideArtifacts(){on(r)&&(an=!0,fn())},upsertArtifact(l){return on(r)?(an=!1,W.upsertArtifact(l)):null},selectArtifact(l){on(r)&&W.selectArtifact(l)},clearArtifacts(){on(r)&&W.clearArtifacts()},focusInput(){return v&&!S||!te?!1:(te.focus(),!0)},async resolveApproval(l,u){let A=W.getMessages().find(L=>{var $;return L.variant==="approval"&&(($=L.approval)==null?void 0:$.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return W.resolveApproval(A.approval,u)},getMessages(){return W.getMessages()},getStatus(){return W.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return s.on(l,u)},off(l,u){s.off(l,u)},isOpen(){return v&&S},isVoiceActive(){return qe.active},getState(){return{open:v&&S,launcherEnabled:v,voiceActive:qe.active,streaming:W.isStreaming()}},showCSATFeedback(l){!S&&v&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=wo({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitCSATFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!S&&v&&ft(!0,"system");let u=Ee.querySelector(".persona-feedback-container");u&&u.remove();let h=So({onSubmit:async(A,L)=>{var $;W.isClientTokenMode()&&await W.submitNPSFeedback(A,L),($=l==null?void 0:l.onSubmit)==null||$.call(l,A,L)},onDismiss:l==null?void 0:l.onDismiss,...l});Ee.appendChild(h),h.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return W.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return W.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),le.remove(),we==null||we.destroy(),Ne==null||Ne.remove(),yn&&ie.removeEventListener("click",yn)}};if((((Xo=t==null?void 0:t.debugTools)!=null?Xo:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:T,getMessages:T.getMessages,getStatus:T.getStatus,getMetadata:T.getPersistentMetadata,updateMetadata:T.updatePersistentMetadata,clearHistory:()=>T.clearChat(),setVoiceActive:h=>h?T.startVoiceRecognition():T.stopVoiceRecognition()};window.AgentWidgetBrowser=u,xt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Le){let D=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.showEventStream()},B=me=>{let ge=me.detail;(!(ge!=null&&ge.instanceId)||ge.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",D),window.addEventListener("persona:hideEventStream",B),xt.push(()=>{window.removeEventListener("persona:showEventStream",D),window.removeEventListener("persona:hideEventStream",B)})}let h=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.showArtifacts()},A=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.hideArtifacts()},L=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||B!=null&&B.artifact&&T.upsertArtifact(B.artifact)},$=D=>{let B=D.detail;B!=null&&B.instanceId&&B.instanceId!==l||typeof(B==null?void 0:B.id)=="string"&&T.selectArtifact(B.id)},R=D=>{let B=D.detail;(!(B!=null&&B.instanceId)||B.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",h),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",$),window.addEventListener("persona:clearArtifacts",R),xt.push(()=>{window.removeEventListener("persona:showArtifacts",h),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",$),window.removeEventListener("persona:clearArtifacts",R)})}let I=Bd(r.persistState);if(I&&v){let l=$d(I.storage),u=`${I.keyPrefix}widget-open`,h=`${I.keyPrefix}widget-voice`,A=`${I.keyPrefix}widget-voice-mode`;if(l){let L=((Go=I.persist)==null?void 0:Go.openState)&&l.getItem(u)==="true",$=((Zo=I.persist)==null?void 0:Zo.voiceState)&&l.getItem(h)==="true",R=((Qo=I.persist)==null?void 0:Qo.voiceState)&&l.getItem(A)==="true";if(L&&setTimeout(()=>{T.open(),setTimeout(()=>{var D;if($||R)T.startVoiceRecognition();else if((D=I.persist)!=null&&D.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(ea=I.persist)!=null&&ea.openState&&(s.on("widget:opened",()=>{l.setItem(u,"true")}),s.on("widget:closed",()=>{l.setItem(u,"false")})),(ta=I.persist)!=null&&ta.voiceState&&(s.on("voice:state",D=>{l.setItem(h,D.active?"true":"false")}),s.on("user:message",D=>{l.setItem(A,D.viaVoice?"true":"false")})),I.clearOnChatClear){let D=()=>{l.removeItem(u),l.removeItem(h),l.removeItem(A)},B=()=>D();window.addEventListener("persona:clear-chat",B),xt.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return T};var jl=(e,n)=>{var r,o;let t=(o=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?o:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},To=(e,n,t,r,o,s)=>{let a=zr(o),i=s?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=s?"true":"false",e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto",n.style.minWidth="0",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.flex=`0 0 ${i}`,t.style.width=i,t.style.maxWidth=i,t.style.minWidth=i,t.style.minHeight="0",t.style.position="relative",t.style.overflow="visible",t.style.transition="width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto",a.side==="left"?e.firstElementChild!==t&&e.replaceChildren(t,n):e.lastElementChild!==t&&e.replaceChildren(n,t)},Fd=(e,n)=>{let t=e.ownerDocument.createElement("div");return jl(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){jl(t,r)},destroy(){t.remove()}}},Nd=(e,n)=>{var p,y,m,C;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),d=t.createElement("aside"),c=t.createElement("div"),g=(y=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)==null||y?(C=(m=n==null?void 0:n.launcher)==null?void 0:m.autoExpand)!=null?C:!1:!0;return i.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(a,e),i.appendChild(e),a.appendChild(i),a.appendChild(d),To(a,i,d,c,n,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,To(a,i,d,c,n,g))},updateConfig(v){var E,x;n=v,((x=(E=n==null?void 0:n.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),To(a,i,d,c,n,g)},destroy(){r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Hs=(e,n)=>Ut(n)?Nd(e,n):Fd(e,n);var Mo={},Od=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},Dd=()=>{try{if(typeof Mo!="undefined"&&Mo.url)return new URL("../widget.css",Mo.url).href}catch{}return null},Vl=(e,n)=>{let t=Dd(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=n.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),n.head.appendChild(s)}},ql=e=>{var E;let n=Od(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,o=e.config,s=Hs(n,o),a,i=[],d=(x,k)=>{var S,N;let M=!((N=(S=k==null?void 0:k.launcher)==null?void 0:S.enabled)!=null?N:!0)||Ut(k),O=r.createElement("div");if(O.id="persona-root",M&&(O.style.height="100%",O.style.display="flex",O.style.flexDirection="column",O.style.flex="1",O.style.minHeight="0"),t){let Q=x.attachShadow({mode:"open"});Q.appendChild(O),Vl(Q,r)}else x.appendChild(O),Vl(x,r);return n.id&&O.setAttribute("data-persona-instance",n.id),O},c=()=>{s.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(s.host,o);a=Eo(x,o,{debugTools:e.debugTools}),g()},y=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{y(),s.destroy(),s=Hs(n,x),o=x,p()},C={update(x){var O,S,N,Q,K,re;let k={...o,...x,launcher:{...(O=o==null?void 0:o.launcher)!=null?O:{},...(S=x==null?void 0:x.launcher)!=null?S:{},dock:{...(Q=(N=o==null?void 0:o.launcher)==null?void 0:N.dock)!=null?Q:{},...(re=(K=x==null?void 0:x.launcher)==null?void 0:K.dock)!=null?re:{}}}},U=Ut(o),M=Ut(k);if(U!==M){m(k);return}o=k,s.updateConfig(o),a.update(x),c()},destroy(){y(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,U){if(k==="host")return s.host;if(k in x)return Reflect.get(x,k,U);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var Yl=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_d=new Set(["button","a","input","select","textarea","details","summary"]),jd=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),ko=/\b(product|card|item|listing|result)\b/i,Po=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Vd=3e3,qd=100;function Xl(e){let n=typeof e.className=="string"?e.className:"";if(ko.test(n)||e.id&&ko.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&ko.test(r.value))return!0}return!1}function Gl(e){var n;return Po.test(((n=e.textContent)!=null?n:"").trim())}function Zl(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let o=(t=n[r].getAttribute("href"))!=null?t:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function Ud(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ul(e){let n=e.match(Po);return n?n[0]:null}function zl(e){var r,o,s;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((o=n.textContent)!=null&&o.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(s=t==null?void 0:t.textContent)!=null&&s.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function zd(e){let n=[],t=r=>{let o=r.trim();o&&!n.includes(o)&&n.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return t((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;t((o=r.value)!=null?o:"")}),n.slice(0,6)}var Jd="commerce-card",Kd="result-card";function Jl(e){return!Xl(e)||!Gl(e)||!Zl(e)&&!Ud(e)?0:5200}function Kl(e){var r;return!Xl(e)||Gl(e)||!Zl(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ql=[{id:Jd,scoreElement(e){return Jl(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||Po.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,c,g;if(Jl(e)===0)return null;let{title:t,href:r}=zl(e),o=(g=(c=Ul(((d=e.textContent)!=null?d:"").trim()))!=null?c:Ul(n.text))!=null?g:"",s=zd(e);return[r&&t?`[${t}](${r})${o?` \u2014 ${o}`:""}`:t?`${t}${o?` \u2014 ${o}`:""}`:o||n.text.trim().slice(0,120),`selector: ${n.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
96
|
+
`)}},{id:Kd,scoreElement(e){return Kl(e)},formatSummary(e,n){if(Kl(e)===0)return null;let{title:t,href:r}=zl(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
|
|
97
|
+
`)}}];function Yd(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Xd(e){var g,p,y,m,C,v,E,x,k,U,M,O,S;let n=(g=e.options)!=null?g:{},t=(y=(p=n.maxElements)!=null?p:e.maxElements)!=null?y:80,r=(C=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",o=(E=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,s=(k=(x=n.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(U=n.root)!=null?U:e.root,i=(M=n.mode)!=null?M:"structured",d=(O=n.maxCandidates)!=null?O:Math.max(500,t*10),c=(S=e.rules)!=null?S:Ql;return i==="simple"&&e.rules&&e.rules.length>0?(Yd(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:c}}function Lo(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Gd=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Zd(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||_d.has(n)||t&&jd.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ec(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Qd(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let o=e.getAttribute("aria-label");o&&(n["aria-label"]=o);let s=e.getAttribute("type");s&&(n.type=s);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let d=e.getAttribute("role");d&&(n.role=d);for(let c=0;c<e.attributes.length;c++){let g=e.attributes[c];g.name.startsWith("data-")&&(n[g.name]=g.value)}return n}function tc(e){let n=e.tagName.toLowerCase();if(e.id){let o=`#${Lo(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of Gd){let s=e.getAttribute(o);if(s){let a=`${n}[${o}="${Lo(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(t.length>0){let o=`${n}.${t.map(a=>Lo(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(s>=0)return`${n}:nth-of-type(${s+1})`}return n}function ep(e){return e==="static"?qd:Vd}function nc(e,n){var o;let t=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,n);return{selector:tc(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Zd(e),attributes:Qd(e)}}function tp(e,n,t,r){let o=ep(n.interactivity),s=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function np(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function rp(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,g=c.tagName.toLowerCase();if(Yl.has(g)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ec(c)){i=a.nextNode();continue}let p=nc(c,e.maxTextLength),y=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!y&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:C,formattingRule:v}=tp(c,p,e.rules,t);o.push({el:c,domIndex:s,enriched:p,score:C,formattingRule:v}),s+=1}i=a.nextNode()}o.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,y=g.enriched.interactivity==="static"?1:0;return p!==y?p-y:g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex});let d=[];for(let c of o){if(d.length>=e.maxElements)break;np(d,c)||d.push(c)}return d.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,y=g.enriched.interactivity==="static"?1:0;return p!==y?p-y:p===1&&g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex}),d.map(c=>{var y;let g;if((y=c.formattingRule)!=null&&y.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(g=m)}let p={...c.enriched};return g&&(p.formattedSummary=g),p})}function sp(e,n){let t=[],r=new Set,o=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&t.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,c=d.tagName.toLowerCase();if(Yl.has(c)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!ec(d)){s=o.nextNode();continue}let g=nc(d,e.maxTextLength),p=g.text.length>0,y=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(m=>m==="role");if(!p&&!y){s=o.nextNode();continue}r.has(g.selector)||(r.add(g.selector),t.push(g))}s=o.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function op(e={}){var r;let n=Xd(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?sp(n,t):rp(n,t):[]}var Bs=100;function ap(e,n={}){var s;if(e.length===0)return"No page elements found.";let t=(s=n.mode)!=null?s:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
98
98
|
${a.map(i=>`- ${i.split(`
|
|
99
99
|
`).join(`
|
|
100
100
|
`)}`).join(`
|
|
101
|
-
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)
|
|
101
|
+
`)}`)}let o={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||o[a.interactivity].push(a);if(o.clickable.length>0){let a=o.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Bs)}" (clickable)`);r.push(`Interactive elements:
|
|
102
102
|
${a.join(`
|
|
103
103
|
`)}`)}if(o.navigable.length>0){let a=o.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Bs)}" (navigable)`);r.push(`Navigation links:
|
|
104
104
|
${a.join(`
|
|
@@ -108,7 +108,7 @@ ${a.join(`
|
|
|
108
108
|
${a.join(`
|
|
109
109
|
`)}`)}return r.join(`
|
|
110
110
|
|
|
111
|
-
`)}var rc={name:"@runtypelabs/persona",version:"2.
|
|
111
|
+
`)}var rc={name:"@runtypelabs/persona",version:"2.1.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 xr=rc.version;function kn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function lp(e){if(e)return{getHeaders:kn(e.getHeaders),onFeedback:kn(e.onFeedback),onCopy:kn(e.onCopy),requestMiddleware:kn(e.requestMiddleware),actionHandlers:kn(e.actionHandlers),actionParsers:kn(e.actionParsers),postprocessMessage:kn(e.postprocessMessage),contextProviders:kn(e.contextProviders),streamParser:kn(e.streamParser)}}var sc=`({ text, message }: any) => {
|
|
112
112
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
113
113
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
114
114
|
let cleanJson = jsonSource
|
|
@@ -180,12 +180,12 @@ ${a.join(`
|
|
|
180
180
|
if (parsed.action === 'message') return parsed.text || '';
|
|
181
181
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
182
182
|
return parsed.text || null;
|
|
183
|
-
}`;function pp(e){if(!e)return null;let
|
|
184
|
-
`)}function mp(e,
|
|
185
|
-
`)}function fp(e,t){let n=t==null?void 0:t.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&(r.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.launcher&&_s(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Fs(e," ")),r.push(...Ns(e," ",n)),r.push(...Os(e," ")),r.push(...Ds(e," ")),n!=null&&n.getHeaders&&r.push(` getHeaders: ${n.getHeaders},`),n!=null&&n.contextProviders&&r.push(` contextProviders: ${n.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),n!=null&&n.streamParser?r.push(` streamParser: ${n.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${cp}),`)),n!=null&&n.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${n.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${sc}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${sc}`),r.push(" ],")),n!=null&&n.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${n.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${ac}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${ac}`),r.push(" ],")),n!=null&&n.postprocessMessage?r.push(` postprocessMessage: ${n.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),n!=null&&n.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${n.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
186
|
-
`)}function cc(e){var o;let
|
|
187
|
-
`)}function bp(e,
|
|
183
|
+
}`;function pp(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function $s(e){var n,t;return(t=(n=e.parserType)!=null?n:pp(e.streamParser))!=null?t:"plain"}function Fs(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,o])=>{typeof o=="string"&&t.push(`${n} ${r}: "${o}",`)}),t.push(`${n}},`)),t}function Ns(e,n,t){let r=[],o=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),s=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(o||s)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function Os(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,o=e.markdown.disableDefaultStyles!==void 0;(r||o)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([s,a])=>{typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`)}),t.push(`${n} },`)),o&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function Ds(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(s=>s!=="render"),o=e.layout.messages&&Object.keys(e.layout.messages).some(s=>s!=="renderUserMessage"&&s!=="renderAssistantMessage");(r||o)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([s,a])=>{s!=="render"&&(typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),o&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([s,a])=>{s==="renderUserMessage"||s==="renderAssistantMessage"||(s==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):s==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${n} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${n} ${d}: ${c},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${s}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${s}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function Io(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function lc(e,n,t){Object.entries(n).forEach(([r,o])=>{if(!(o===void 0||typeof o=="function")){if(Array.isArray(o)){e.push(`${t}${r}: ${JSON.stringify(o)},`);return}if(o&&typeof o=="object"){e.push(`${t}${r}: {`),lc(e,o,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(o)},`)}})}function _s(e,n,t,r){t&&(e.push(`${r}${n}: {`),lc(e,t,`${r} `),e.push(`${r}},`))}function up(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let o=t?{...t,hooks:lp(t.hooks)}:void 0;return n==="esm"?gp(r,o):n==="script-installer"?hp(r):n==="script-advanced"?bp(r,o):n==="react-component"?mp(r,o):n==="react-advanced"?fp(r,o):yp(r,o)}function gp(e,n){let t=n==null?void 0:n.hooks,r=$s(e),o=r!=="plain",s=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&_s(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Fs(e," ")),s.push(...Ns(e," ",t)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),s.push(" }"),s.push("});"),s.join(`
|
|
184
|
+
`)}function mp(e,n){let t=n==null?void 0:n.hooks,r=$s(e),o=r!=="plain",s=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&_s(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Fs(e," ")),s.push(...Ns(e," ",t)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.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(`
|
|
185
|
+
`)}function fp(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&(r.push(" theme: {"),Object.entries(e.theme).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.launcher&&_s(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([o,s])=>{r.push(` ${o}: "${s}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"?r.push(` ${o}: ${s},`):typeof s=="number"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([o,s])=>{typeof s=="string"?r.push(` ${o}: "${s}",`):typeof s=="boolean"&&r.push(` ${o}: ${s},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([o,s])=>{r.push(` ${o}: ${s},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(o=>{r.push(` "${o}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Fs(e," ")),r.push(...Ns(e," ",t)),r.push(...Os(e," ")),r.push(...Ds(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${cp}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${sc}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${sc}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${ac}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${ac}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
186
|
+
`)}function cc(e){var o;let n=$s(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((o=e.suggestionChips)==null?void 0:o.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let s={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(s[a]=i)}),Object.keys(s).length>0&&(r.toolCall=s)}if(e.messageActions){let s={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(s[a]=i)}),Object.keys(s).length>0&&(r.messageActions=s)}if(e.markdown){let s={};e.markdown.options&&(s.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(s.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(s).length>0&&(r.markdown=s)}if(e.layout){let s={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([g,p])=>{g!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[g]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(s.messages=a)}Object.keys(s).length>0&&(r.layout=s)}return r}function hp(e){let n=cc(e),t=JSON.stringify(n,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/dist/install.global.js" data-config='${t}'></script>`}function yp(e,n){let t=n==null?void 0:n.hooks,r=$s(e),o=r!=="plain",s=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&s.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&s.push(` clientToken: "${e.clientToken}",`),e.flowId&&s.push(` flowId: "${e.flowId}",`),o&&s.push(` parserType: "${r}",`),e.theme&&(s.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.launcher&&_s(s,"launcher",e.launcher," "),e.copy&&(s.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{s.push(` ${a}: "${i}",`)}),s.push(" },")),e.sendButton&&(s.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.voiceRecognition&&(s.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"?s.push(` ${a}: ${i},`):typeof i=="number"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.statusIndicator&&(s.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?s.push(` ${a}: "${i}",`):typeof i=="boolean"&&s.push(` ${a}: ${i},`)}),s.push(" },")),e.features&&(s.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{s.push(` ${a}: ${i},`)}),s.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(s.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{s.push(` "${a}",`)}),s.push(" ],")),e.suggestionChipsConfig&&(s.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&s.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&s.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&s.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&s.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),s.push(" },")),s.push(...Fs(e," ")),s.push(...Ns(e," ",t)),s.push(...Os(e," ")),s.push(...Ds(e," ")),s.push(...Io(t," ")),e.debug&&s.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?s.push(` postprocessMessage: ${t.postprocessMessage}`):s.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),s.push(" }"),s.push(" });"),s.push("</script>"),s.join(`
|
|
187
|
+
`)}function bp(e,n){let t=n==null?void 0:n.hooks,r=cc(e),s=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
188
188
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
189
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/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
|
|
190
|
-
`)}function xp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #1d4ed8)"}}}function vp(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Cp(e){return{name:"@persona/brand",version:"1.0.0",transform(
|
|
189
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${xr}/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 t!=null&&t.getHeaders&&(s.push(` widgetConfig.getHeaders = ${t.getHeaders};`),s.push("")),t!=null&&t.contextProviders&&(s.push(` widgetConfig.contextProviders = ${t.contextProviders};`),s.push("")),t!=null&&t.streamParser?s.push(` widgetConfig.streamParser = ${t.streamParser};`):(s.push(" // Flexible JSON stream parser for handling structured actions"),s.push(" widgetConfig.streamParser = function() {"),s.push(` return agentWidget.createFlexibleJsonStreamParser(${dp});`),s.push(" };")),s.push(""),t!=null&&t.actionParsers?(s.push(" // Action parsers (custom merged with defaults)"),s.push(` var customParsers = ${t.actionParsers};`),s.push(" widgetConfig.actionParsers = customParsers.concat(["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${oc}`),s.push(" ]);")):(s.push(" // Action parsers to detect JSON actions in responses"),s.push(" widgetConfig.actionParsers = ["),s.push(" agentWidget.defaultJsonActionParser,"),s.push(` ${oc}`),s.push(" ];")),s.push(""),t!=null&&t.actionHandlers?(s.push(" // Action handlers (custom merged with defaults)"),s.push(` var customHandlers = ${t.actionHandlers};`),s.push(" widgetConfig.actionHandlers = customHandlers.concat(["),s.push(" agentWidget.defaultActionHandlers.message,"),s.push(" agentWidget.defaultActionHandlers.messageAndClick,"),s.push(` ${ic}`),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(` ${ic}`),s.push(" ];")),s.push(""),t!=null&&t.requestMiddleware?(s.push(" // Request middleware (custom merged with DOM context)"),s.push(" widgetConfig.requestMiddleware = function(ctx) {"),s.push(` var customResult = (${t.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(""),t!=null&&t.postprocessMessage?s.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(s.push(" // Markdown postprocessor"),s.push(" widgetConfig.postprocessMessage = function(ctx) {"),s.push(" return agentWidget.markdownPostprocessor(ctx.text);"),s.push(" };")),s.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(s.push(" // Message action callbacks"),s.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&s.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&s.push(` widgetConfig.messageActions.onCopy = ${t.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(`
|
|
190
|
+
`)}function xp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #1d4ed8)"}}}function vp(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Cp(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:xn(e.colors.primary,.95),100:xn(e.colors.primary,.9),200:xn(e.colors.primary,.8),300:xn(e.colors.primary,.7),400:xn(e.colors.primary,.6),500:e.colors.primary,600:xn(e.colors.primary,.8),700:xn(e.colors.primary,.7),800:xn(e.colors.primary,.6),900:xn(e.colors.primary,.5),950:xn(e.colors.primary,.45)}}),{...n,palette:t}}}}function wp(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Sp(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function xn(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(o+(255-o)*(1-n));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Ap(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Rm=ql;export{lr as AgentWidgetClient,qr as AgentWidgetSession,pr as AttachmentManager,tl as DEFAULT_COMPONENTS,Fl as DEFAULT_DARK_THEME,$l as DEFAULT_LIGHT_THEME,Qi as DEFAULT_PALETTE,el as DEFAULT_SEMANTIC,yt as DEFAULT_WIDGET_CONFIG,xr as VERSION,xp as accessibilityPlugin,vp as animationsPlugin,Yn as applyThemeVariables,ur as attachHeaderToContainer,Cp as brandPlugin,Yr as buildComposer,fl as buildDefaultHeader,$n as buildHeader,Kr as buildHeaderWithLayout,hl as buildMinimalHeader,op as collectEnrichedPageContext,Fn as componentRegistry,Rs as createActionManager,Eo as createAgentExperience,Zs as createBestAvailableVoiceProvider,td as createBubbleWithLayout,wo as createCSATFeedback,Pd as createComponentMiddleware,bo as createComponentStreamParser,mc as createDirectivePostprocessor,xc as createFlexibleJsonStreamParser,Mc as createImagePart,Js as createJsonStreamParser,yo as createLocalStorageAdapter,xs as createMarkdownProcessor,ir as createMarkdownProcessorFromConfig,wl as createMessageActions,So as createNPSFeedback,Us as createPlainTextParser,Ap as createPlugin,zs as createRegexJsonParser,Xr as createStandardBubble,Gs as createTextPart,Ur as createTheme,oo as createThemeObserver,gr as createTypingIndicator,dr as createVoiceProvider,Hs as createWidgetHostLayout,Ks as createXmlParser,Rm as default,yr as defaultActionHandlers,Ws as defaultJsonActionParser,Ql as defaultParseRules,ks as detectColorScheme,fc as directivePostprocessor,Dr as escapeHtml,Co as extractComponentDirectiveFromMessage,kc as fileToImagePart,ap as formatEnrichedContext,cr as generateAssistantMessageId,up as generateCodeSnippet,wc as generateMessageId,tc as generateStableSelector,jr as generateUserMessageId,ll as getActiveTheme,il as getColorScheme,Ac as getDisplayText,yl as getHeaderLayout,Tc as getImageParts,vo as hasComponentDirective,Ec as hasImages,ao as headerLayouts,Sp as highContrastPlugin,ql as initAgentWidget,Ld as isComponentDirectiveType,Ut as isDockedMountMode,Ts as isVoiceSupported,_i as markdownPostprocessor,fo as mergeWithDefaults,no as migrateV1Theme,Sc as normalizeContent,Is as pluginRegistry,wp as reducedMotionPlugin,xo as renderComponentDirective,Cl as renderLoadingIndicatorWithFallback,zr as resolveDockConfig,Qs as resolveTokens,eo as themeToCssVariables,Lc as validateImageFile,rl as validateTheme,Nc as validateV1Theme};
|
|
191
191
|
//# sourceMappingURL=index.js.map
|