@runtypelabs/persona 3.9.1 → 3.9.2
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 +3 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +3 -4
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +3 -4
- package/dist/index.js.map +1 -1
- package/dist/theme-editor.cjs +2 -2
- package/dist/theme-editor.js +2 -2
- package/package.json +1 -1
- package/src/components/tool-bubble.ts +1 -1
- package/src/defaults.ts +1 -1
package/dist/index.cjs
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async n=>{if(n.length<=r)return e!==null?{text:e,raw:n}:null;let s=n.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(n);return o!==null&&(e=o),r=n.length,e!==null?{text:e,raw:n}:null},close:async()=>{}}},rs=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},os=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ss=()=>{var r;let e=cp();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},as=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,sr.parse)(t,sr.STR|sr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?ns(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=ns(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},hc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?ns(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?ns(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>r,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return r!==null?{text:r,raw:o}:null;try{let i=(0,sr.parse)(o,sr.STR|sr.OBJ),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},is=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var dp="https://api.runtype.com/v1/dispatch",qs="https://api.runtype.com",Js=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 pp(e){switch(e){case"json":return as;case"regex-json":return ss;case"xml":return is;default:return os}}var Dr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:dp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:pp(r.parserType),this.contextProviders=(s=r.contextProviders)!=null?s:[],this.requestMiddleware=r.requestMiddleware,this.customFetch=r.customFetch,this.parseSSEEvent=r.parseSSEEvent,this.getHeaders=r.getHeaders}setSSEEventCallback(r){this.onSSEEvent=r}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(r){var n;let t=((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||qs;return r==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var r,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 n=await this.sessionInitPromise;return this.clientSession=n,(t=(r=this.config).onSessionInit)==null||t.call(r,n),n}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let r=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...r&&{sessionId:r}},n=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!n.ok){let i=await n.json().catch(()=>({error:"Session initialization failed"}));throw n.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):n.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await n.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.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$/,""))||qs}/v1/client/feedback`}async sendFeedback(r){var o,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(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,u={sessionId:d.sessionId,messages:r.messages.filter(Js).map(m=>{var v,M,b;return{id:m.id,role:m.role,content:(b=(M=(v=m.contentParts)!=null?v:m.llmContent)!=null?M:m.rawContent)!=null?b:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",u);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(u),signal:n.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}if(f.status===429){let M=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:M}),M}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.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(f.body,t,r.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}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:o,body:JSON.stringify(s),signal:n.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(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...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:o,body:JSON.stringify(s),signal:n.signal},s)}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:o,body:JSON.stringify(s),signal:n.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,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||qs}/v1/agents/${r.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:r.executionId,approvalId:r.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(r){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=r.slice().filter(Js).filter(s=>s.role==="user"||s.role==="assistant"||s.role==="system").filter(s=>!s.variant||s.variant==="assistant").sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),n={agent:this.config.agent,messages:t,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}return n}async buildPayload(r){let n={messages:r.slice().filter(Js).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return n.current=u,s(u),u},c=p=>n.current?n.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O,Le,ue,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Dn,Xe,Mr,Vn,kr,kn,Vr,dr,Kn,et,xn,Fn,an,pr,vn,ft,ln,Ln,ur,Zn,gr,qn,Cn,Jn,ht,Wt,Rt,wn,mr,Nn,Sn,D,On,In,fr,gn,An,te,$n,qr,fo,Jr,Je,ho,Pn,mn,Yo,Go,yo,Qn,Xo,Yr,Gr,er,bo,hr,yr,Ko,Zo,zs,Lr,Ir,Tt,Xr,Kr,xo,vo,Co,wo,cn,En,tr,je,So,Pr,_n;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,p=X=>{let Ye=X.reasoning?{...X.reasoning,chunks:[...X.reasoning.chunks]}:void 0,pt=X.toolCall?{...X.toolCall,chunks:X.toolCall.chunks?[...X.toolCall.chunks]:void 0}:void 0,It=X.tools?X.tools.map(Pt=>({...Pt,chunks:Pt.chunks?[...Pt.chunks]:void 0})):void 0;return{...X,reasoning:Ye,toolCall:pt,tools:It}},u=X=>{t({type:"message",message:p(X)})},f=null,m={current:null},v={current:null},M=!1,b=new Map,C=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},w=X=>{if(X==null)return null;try{return String(X)}catch{return null}},L=X=>{var Ye,pt,It,Pt,Qt;return w((Qt=(Pt=(It=(pt=(Ye=X.stepId)!=null?Ye:X.step_id)!=null?pt:X.step)!=null?It:X.parentId)!=null?Pt:X.flowStepId)!=null?Qt:X.flow_step_id)},B=X=>{var Ye,pt,It,Pt,Qt,Ht,x;return w((x=(Ht=(Qt=(Pt=(It=(pt=(Ye=X.callId)!=null?Ye:X.call_id)!=null?pt:X.requestId)!=null?It:X.request_id)!=null?Pt:X.toolCallId)!=null?Qt:X.tool_call_id)!=null?Ht:X.stepId)!=null?x:X.step_id)},T=n,Y=!1,ge=()=>{if(f)return f;let X;return!Y&&T?(X=T,Y=!0):T&&v.current?X=`${T}_${v.current}`:X=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:X,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},u(f),f},ce=(X,Ye)=>{S.lastId=Ye,X&&S.byStep.set(X,Ye)},$=(X,Ye)=>{var Qt;let pt=(Qt=X.reasoningId)!=null?Qt:X.id,It=L(X);if(pt){let Ht=String(pt);return ce(It,Ht),Ht}if(It){let Ht=S.byStep.get(It);if(Ht)return S.lastId=Ht,Ht}if(S.lastId&&!Ye)return S.lastId;if(!Ye)return null;let Pt=`reason-${c()}`;return ce(It,Pt),Pt},ne=X=>{let Ye=b.get(X);if(Ye)return Ye;let pt={id:`reason-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:X,status:"streaming",chunks:[]}};return b.set(X,pt),u(pt),pt},Te=(X,Ye)=>{R.lastId=Ye,X&&R.byCall.set(X,Ye)},re=new Set,Se=new Map,He=new Set,he=new Map,Me=X=>{if(!X)return!1;let Ye=X.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},ke=(X,Ye)=>{var Qt;let pt=(Qt=X.toolId)!=null?Qt:X.id,It=B(X);if(pt){let Ht=String(pt);return Te(It,Ht),Ht}if(It){let Ht=R.byCall.get(It);if(Ht)return R.lastId=Ht,Ht}if(R.lastId&&!Ye)return R.lastId;if(!Ye)return null;let Pt=`tool-${c()}`;return Te(It,Pt),Pt},oe=X=>{let Ye=C.get(X);if(Ye)return Ye;let pt={id:`tool-${X}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:X,status:"pending"}};return C.set(X,pt),u(pt),pt},be=X=>{if(typeof X=="number"&&Number.isFinite(X))return X;if(typeof X=="string"){let Ye=Number(X);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let pt=Date.parse(X);if(!Number.isNaN(pt))return pt}return Date.now()},$e=X=>{if(typeof X=="string")return X;if(X==null)return"";try{return JSON.stringify(X)}catch{return String(X)}},pe=new Map,de=new Map,se=null,De=new Map,ot=(St=this.config.iterationDisplay)!=null?St:"separate";for(;;){let{done:X,value:Ye}=await s.read();if(X)break;a+=o.decode(Ye,{stream:!0});let pt=a.split(`
|
|
5
5
|
|
|
6
6
|
`);a=(j=pt.pop())!=null?j:"";for(let It of pt){let Pt=It.split(`
|
|
7
|
-
`),Qt="message",Ht="";for(let I of Pt)I.startsWith("event:")?Qt=I.replace("event:","").trim():I.startsWith("data:")&&(Ht+=I.replace("data:","").trim());if(!Ht)continue;let x;try{x=JSON.parse(Ht)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let We=Qt!=="message"?Qt:(q=x.type)!=null?q:"message";if((ae=this.onSSEEvent)==null||ae.call(this,We,x),this.parseSSEEvent){m.current=f;let I=await this.handleCustomSSEEvent(x,t,m,u,c,v);if(m.current&&m.current!==f&&(f=m.current),I)continue}if(We==="reason_start"){let I=(_=$(x,!0))!=null?_:`reason-${c()}`,A=ne(I);A.reasoning=(z=A.reasoning)!=null?z:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Fe=A.reasoning.startedAt)!=null?Fe:be((ee=x.startedAt)!=null?ee:x.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(We==="reason_delta"||We==="reason_chunk"){let I=(K=(J=$(x,!1))!=null?J:$(x,!0))!=null?K:`reason-${c()}`,A=ne(I);A.reasoning=(vt=A.reasoning)!=null?vt:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Lt=A.reasoning.startedAt)!=null?Lt:be((tt=x.startedAt)!=null?tt:x.timestamp);let G=(le=(Ne=(Vt=x.reasoningText)!=null?Vt:x.text)!=null?Ne:x.delta)!=null?le:"";if(G&&x.hidden!==!0&&A.reasoning.chunks.push(String(G)),A.reasoning.status=x.done?"complete":"streaming",x.done){A.reasoning.completedAt=be((Ie=x.completedAt)!=null?Ie:x.timestamp);let N=(At=A.reasoning.startedAt)!=null?At:Date.now();A.reasoning.durationMs=Math.max(0,((Et=A.reasoning.completedAt)!=null?Et:Date.now())-N)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(We==="reason_complete"){let I=(Qe=(Ze=$(x,!1))!=null?Ze:$(x,!0))!=null?Qe:`reason-${c()}`,A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be((Kt=x.completedAt)!=null?Kt:x.timestamp);let N=(Gt=A.reasoning.startedAt)!=null?Gt:Date.now();A.reasoning.durationMs=Math.max(0,((Zt=A.reasoning.completedAt)!=null?Zt:Date.now())-N),A.streaming=!1,u(A)}let G=L(x);G&&S.byStep.delete(G)}else if(We==="tool_start"){let I=(O=ke(x,!0))!=null?O:`tool-${c()}`,A=(Le=x.toolName)!=null?Le:x.name;if(Me(A)){re.add(I);continue}let G=oe(I),N=(ue=G.toolCall)!=null?ue:{id:I,status:"pending"};N.name=A!=null?A:N.name,N.status="running",x.args!==void 0?N.args=x.args:x.parameters!==void 0&&(N.args=x.parameters),N.startedAt=(Be=N.startedAt)!=null?Be:be((at=x.startedAt)!=null?at:x.timestamp),N.completedAt=void 0,N.durationMs=void 0,G.toolCall=N,G.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(G.agentMetadata={executionId:(Z=Q==null?void 0:Q.executionId)!=null?Z:x.executionId,iteration:(ye=Q==null?void 0:Q.iteration)!=null?ye:x.iteration}),u(G)}else if(We==="tool_chunk"||We==="tool_delta"){let I=(dt=(Pe=ke(x,!1))!=null?Pe:ke(x,!0))!=null?dt:`tool-${c()}`;if(re.has(I))continue;let A=oe(I),G=(Ot=A.toolCall)!=null?Ot:{id:I,status:"running"};G.startedAt=($t=G.startedAt)!=null?$t:be((nt=x.startedAt)!=null?nt:x.timestamp);let N=(lt=(qe=(it=x.text)!=null?it:x.delta)!=null?qe:x.message)!=null?lt:"";N&&(G.chunks=(_e=G.chunks)!=null?_e:[],G.chunks.push(String(N))),G.status="running",A.toolCall=G,A.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(Xn=A.agentMetadata)!=null?Xn:{executionId:(_t=Q==null?void 0:Q.executionId)!=null?_t:x.executionId,iteration:(Un=Q==null?void 0:Q.iteration)!=null?Un:x.iteration}),u(A)}else if(We==="tool_complete"){let I=(Xe=(Dn=ke(x,!1))!=null?Dn:ke(x,!0))!=null?Xe:`tool-${c()}`;if(re.has(I)){re.delete(I);continue}let A=oe(I),G=(Mr=A.toolCall)!=null?Mr:{id:I,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=be((Vn=x.completedAt)!=null?Vn:x.timestamp);let N=(kr=x.duration)!=null?kr:x.executionTime;if(typeof N=="number")G.durationMs=N;else{let Mt=(kn=G.startedAt)!=null?kn:Date.now();G.durationMs=Math.max(0,((Vr=G.completedAt)!=null?Vr:Date.now())-Mt)}A.toolCall=G,A.streaming=!1;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(et=A.agentMetadata)!=null?et:{executionId:(dr=Q==null?void 0:Q.executionId)!=null?dr:x.executionId,iteration:(Kn=Q==null?void 0:Q.iteration)!=null?Kn:x.iteration}),u(A);let ut=B(x);ut&&R.byCall.delete(ut)}else if(We==="text_start"){let I=x.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let A=f;A&&(A.streaming=!1,u(A),f=null,M=!0)}I!==void 0&&(v.current=I)}else if(We==="text_end"){let I=f;I&&(I.streaming=!1,u(I),f=null,M=!0)}else if(We==="step_chunk"||We==="step_delta"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;let G=x.partId;if(G!==void 0&&v.current!==null&&G!==v.current){let ut=f;ut&&(ut.streaming=!1,u(ut),f=null,M=!0)}G!==void 0&&(v.current=G);let N=ge();G!==void 0&&!N.partId&&(N.partId=G);let Q=(pr=(an=(Fn=(xn=x.text)!=null?xn:x.delta)!=null?Fn:x.content)!=null?an:x.chunk)!=null?pr:"";if(Q){let Mt=((vn=de.get(N.id))!=null?vn:"")+Q;N.rawContent=Mt,pe.has(N.id)||pe.set(N.id,this.createStreamParser());let Bt=pe.get(N.id),en=Mt.trim().startsWith("{")||Mt.trim().startsWith("[");if(en&&de.set(N.id,Mt),Bt.__isPlainTextParser===!0){N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N);continue}let tn=Bt.processChunk(Mt);if(tn instanceof Promise)tn.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null&&Ct.trim()!==""){let bt=f;bt&&bt.id===N.id&&(bt.content=Ct,u(bt))}else if(!en&&!Mt.trim().startsWith("<")){let bt=f;bt&&bt.id===N.id&&(bt.content+=Q,de.delete(bt.id),pe.delete(bt.id),bt.rawContent=void 0,u(bt))}}).catch(()=>{N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N)});else{let Ae=typeof tn=="string"?tn:(ft=tn==null?void 0:tn.text)!=null?ft:null;Ae!==null&&Ae.trim()!==""?(N.content=Ae,u(N)):!en&&!Mt.trim().startsWith("<")&&(N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N))}}if(x.isComplete){let ut=(Ln=(ln=x.result)==null?void 0:ln.response)!=null?Ln:N.content;if(ut){let Mt=de.get(N.id),Bt=Mt!=null?Mt:$e(ut);N.rawContent=Bt;let en=pe.get(N.id),qt=null,tn=!1;if(en&&(qt=en.getExtractedText(),qt===null&&(qt=rs(Bt)),qt===null)){let Ae=en.processChunk(Bt);Ae instanceof Promise?(tn=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}})):qt=typeof Ae=="string"?Ae:(ur=Ae==null?void 0:Ae.text)!=null?ur:null}if(!tn){qt!==null&&qt.trim()!==""?N.content=qt:de.has(N.id)||(N.content=$e(ut));let Ae=pe.get(N.id);if(Ae){let Ct=(Zn=Ae.close)==null?void 0:Zn.call(Ae);Ct instanceof Promise&&Ct.catch(()=>{}),pe.delete(N.id)}de.delete(N.id),N.streaming=!1,u(N)}}}}else if(We==="step_complete"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;if(M){if(f!==null){let Q=f;pe.delete(Q.id),de.delete(Q.id),Q.streaming!==!1&&(Q.streaming=!1,u(Q))}continue}let G=(gr=x.result)==null?void 0:gr.response,N=ge();if(G!=null){let Q=pe.get(N.id),ut=!1,Mt=!1;if(Q){let Bt=Q.getExtractedText(),en=de.get(N.id),qt=en!=null?en:$e(G);if(N.rawContent=qt,Bt!==null&&Bt.trim()!=="")N.content=Bt,ut=!0;else{let tn=rs(qt);if(tn!==null)N.content=tn,ut=!0;else{let Ae=Q.processChunk(qt);if(Ae instanceof Promise)Mt=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null&&yt.trim()!==""){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}else{let Dt=Q.getExtractedText(),Wn=f;Wn&&Wn.id===N.id&&(Dt!==null&&Dt.trim()!==""?Wn.content=Dt:de.has(Wn.id)||(Wn.content=$e(G)),Wn.streaming=!1,pe.delete(Wn.id),de.delete(Wn.id),u(Wn))}});else{let Ct=typeof Ae=="string"?Ae:(qn=Ae==null?void 0:Ae.text)!=null?qn:null;if(Ct!==null&&Ct.trim()!=="")N.content=Ct,ut=!0;else{let yt=Q.getExtractedText();yt!==null&&yt.trim()!==""&&(N.content=yt,ut=!0)}}}}}if(!Mt){if(!N.rawContent){let Bt=de.get(N.id);N.rawContent=Bt!=null?Bt:$e(G)}if(!ut&&!de.has(N.id)&&(N.content=$e(G)),Q){let Bt=(Cn=Q.close)==null?void 0:Cn.call(Q);Bt instanceof Promise&&Bt.catch(()=>{})}pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}}else pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}else if(We==="flow_complete"){let I=(Jn=x.result)==null?void 0:Jn.response;if(M){if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}}else if(I!=null){let A=ge(),G=de.get(A.id),N=G!=null?G:$e(I);A.rawContent=N;let Q=$e(I),ut=pe.get(A.id);if(ut){let en=rs(N);if(en!==null)Q=en;else{let qt=ut.processChunk(N);qt instanceof Promise&&qt.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null){let bt=f;bt&&bt.id===A.id&&(bt.content=Ct,bt.streaming=!1,u(bt))}});let tn=ut.getExtractedText();tn!==null&&(Q=tn)}}pe.delete(A.id),de.delete(A.id);let Mt=Q!==A.content,Bt=A.streaming!==!1;Mt&&(A.content=Q),A.streaming=!1,(Mt||Bt)&&u(A)}else if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(We==="agent_start")se={executionId:x.executionId,agentId:(ht=x.agentId)!=null?ht:"virtual",agentName:(Wt=x.agentName)!=null?Wt:"",status:"running",currentIteration:0,maxTurns:(Rt=x.maxTurns)!=null?Rt:1,startedAt:be(x.startedAt)};else if(We==="agent_iteration_start"){if(se&&(se.currentIteration=x.iteration),ot==="separate"&&x.iteration>1){let I=f;I&&(I.streaming=!1,u(I),De.set(x.iteration-1,I),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(x.contentType==="text"){let I=ge();I.content+=(wn=x.delta)!=null?wn:"",I.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId,agentName:se==null?void 0:se.agentName},u(I)}else if(x.contentType==="thinking"){let I=(mr=x.turnId)!=null?mr:`agent-think-${x.iteration}`,A=ne(I);A.reasoning=(Nn=A.reasoning)!=null?Nn:{id:I,status:"streaming",chunks:[]},A.reasoning.chunks.push((Sn=x.delta)!=null?Sn:""),A.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId},u(A)}else if(x.contentType==="tool_input"){let I=(D=x.toolCallId)!=null?D:R.lastId;if(I){let A=C.get(I);A!=null&&A.toolCall&&(A.toolCall.chunks=(On=A.toolCall.chunks)!=null?On:[],A.toolCall.chunks.push((In=x.delta)!=null?In:""),u(A))}}}else if(We==="agent_turn_complete"){let I=x.turnId;if(I){let A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be(x.completedAt);let G=(fr=A.reasoning.startedAt)!=null?fr:Date.now();A.reasoning.durationMs=Math.max(0,((gn=A.reasoning.completedAt)!=null?gn:Date.now())-G),A.streaming=!1,u(A)}}}else if(We==="agent_tool_start"){let I=(An=x.toolCallId)!=null?An:`agent-tool-${c()}`;Te(B(x),I);let A=oe(I),G=(te=A.toolCall)!=null?te:{id:I,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};G.name=(qr=($n=x.toolName)!=null?$n:x.name)!=null?qr:G.name,G.status="running",x.parameters!==void 0&&(G.args=x.parameters),G.startedAt=be((fo=x.startedAt)!=null?fo:x.timestamp),A.toolCall=G,A.streaming=!0,A.agentMetadata={executionId:x.executionId,iteration:x.iteration},u(A)}else if(We==="agent_tool_delta"){let I=(Jr=x.toolCallId)!=null?Jr:R.lastId;if(I){let A=(Je=C.get(I))!=null?Je:oe(I);A.toolCall&&(A.toolCall.chunks=(ho=A.toolCall.chunks)!=null?ho:[],A.toolCall.chunks.push((Pn=x.delta)!=null?Pn:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(We==="agent_tool_complete"){let I=(mn=x.toolCallId)!=null?mn:R.lastId;if(I){let A=(Yo=C.get(I))!=null?Yo:oe(I);if(A.toolCall){A.toolCall.status="complete",x.result!==void 0&&(A.toolCall.result=x.result),typeof x.executionTime=="number"&&(A.toolCall.durationMs=x.executionTime),A.toolCall.completedAt=be((Go=x.completedAt)!=null?Go:x.timestamp),A.streaming=!1,u(A);let G=B(x);G&&R.byCall.delete(G)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let I=`agent-reflection-${x.executionId}-${x.iteration}`,A={id:I,role:"assistant",content:(yo=x.reflection)!=null?yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(Qn=x.reflection)!=null?Qn:""]},agentMetadata:{executionId:x.executionId,iteration:x.iteration}};u(A)}else if(We==="agent_complete"){se&&(se.status=x.success?"complete":"error",se.completedAt=be(x.completedAt),se.stopReason=x.stopReason);let I=f;I&&(I.streaming=!1,u(I)),t({type:"status",status:"idle"})}else if(We==="agent_error"){let I=typeof x.error=="string"?x.error:(Yr=(Xo=x.error)==null?void 0:Xo.message)!=null?Yr:"Agent execution error";x.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let I=(Gr=x.approvalId)!=null?Gr:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(er=se==null?void 0:se.agentId)!=null?er:"virtual",executionId:(hr=(bo=x.executionId)!=null?bo:se==null?void 0:se.executionId)!=null?hr:"",toolName:(yr=x.toolName)!=null?yr:"",toolType:x.toolType,description:(Zo=x.description)!=null?Zo:`Execute ${(Ko=x.toolName)!=null?Ko:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="step_await"&&x.awaitReason==="approval_required"){let I=(zs=x.approvalId)!=null?zs:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(Lr=se==null?void 0:se.agentId)!=null?Lr:"virtual",executionId:(Tt=(Ir=x.executionId)!=null?Ir:se==null?void 0:se.executionId)!=null?Tt:"",toolName:(Xr=x.toolName)!=null?Xr:"",toolType:x.toolType,description:(xo=x.description)!=null?xo:`Execute ${(Kr=x.toolName)!=null?Kr:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="agent_approval_complete"){let I=x.approvalId;if(I){let G={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(vo=x.decision)!=null?vo:"approved",agentId:(Co=se==null?void 0:se.agentId)!=null?Co:"virtual",executionId:(cn=(wo=x.executionId)!=null?wo:se==null?void 0:se.executionId)!=null?cn:"",toolName:(En=x.toolName)!=null?En:"",description:(tr=x.description)!=null?tr:"",resolvedAt:Date.now()}};u(G)}}else if(We==="artifact_start"||We==="artifact_delta"||We==="artifact_update"||We==="artifact_complete"){if(We==="artifact_start"){let I=x.artifactType,A=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:A,artifactType:I,title:G,component:typeof x.component=="string"?x.component:void 0}),he.set(A,{markdown:"",title:G}),!He.has(A)){He.add(A);let N={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:G,artifactType:I,status:"streaming"}})};Se.set(A,N),u(N)}}else if(We==="artifact_delta"){let I=String(x.id),A=typeof x.delta=="string"?x.delta:String((je=x.delta)!=null?je:"");t({type:"artifact_delta",id:I,artDelta:A});let G=he.get(I);G&&(G.markdown+=A)}else if(We==="artifact_update"){let I=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:I,component:typeof x.component=="string"?x.component:void 0})}else if(We==="artifact_complete"){let I=String(x.id);t({type:"artifact_complete",id:I});let A=Se.get(I);if(A){A.streaming=!1;try{let G=JSON.parse((So=A.rawContent)!=null?So:"{}");if(G.props){G.props.status="complete";let N=he.get(I);N!=null&&N.markdown&&(G.props.markdown=N.markdown)}A.rawContent=JSON.stringify(G)}catch{}he.delete(I),u(A),Se.delete(I)}}}else if(We==="transcript_insert"){let I=x.message;if(!I||typeof I!="object")continue;let A=String((Pr=I.id)!=null?Pr:`msg-${c()}`),G=I.role,Q={id:A,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(u(Q),Q.rawContent)try{let ut=JSON.parse(Q.rawContent),Mt=(_n=ut==null?void 0:ut.props)==null?void 0:_n.artifactId;typeof Mt=="string"&&He.add(Mt)}catch{}f=null,m.current=null,pe.delete(A),de.delete(A)}else We==="error"&&x.error&&t({type:"error",error:x.error instanceof Error?x.error:new Error(String(x.error))})}}}}}};function yc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function ro(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Fr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ls="[Image]";function bc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function xc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function vc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Cc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function cs(e){return{type:"text",text:e}}function wc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Sc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ac(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var Ec=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],up=["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"],ar=[...Ec,...up];function gp(e){return Ec.includes(e)||e.startsWith("image/")}function ds(e){return gp(e.type)}async function Tc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ds(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Mc(e,r=ar,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function mp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function kc(e,r){let t=mp(r).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 ps=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.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 r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var us=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):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 Io=class{constructor(r){this.config=r;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 us;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.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=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,M=C=>{v||(v=!0,clearTimeout(b),m(new Error(C)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let S=C.code!==1006?` (code ${C.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ps(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;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 o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),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(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Nr=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Or(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Io(e.runtype);case"browser":if(!Nr.isSupported())throw new Error("Browser speech recognition not supported");return new Nr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function gs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Or({type:"runtype",runtype:e.runtype});if(Nr.isSupported())return Or({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Po(e){try{return gs(e),!0}catch{return!1}}var oo=class e{constructor(r={},t){this.config=r;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=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.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,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Dr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Po((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Or(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,f,m,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.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 b=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;b&&this.ttsSpokenMessageIds.add(b)}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 p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Dr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?ro():t==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?ro():s==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...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(r,t){var c,p,u,f,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=ro(),o=Fr(),a={id:s,role:"user",content:n||ls,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:o},this.handleEvent)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){let b={id:o,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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Fr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,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(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let f=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.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(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;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 s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Yn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var fp=ac(require("lucide"),1),me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=fp[s];return o?hp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function hp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var ms={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function yp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bp(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 $r=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ms.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ms.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ms.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ms.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Mc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Tc(c),f=ds(c)?URL.createObjectURL(c):null,m={id:yp(),file:c,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ds(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.appendChild(a)}else{let a=h("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=bp(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=kc(r.file.type,r.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),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Lc(o)&&Lc(s)?t[n]=Wo(o,s):t[n]=s}return t}var Mn="min(440px, calc(100vw - 24px))",fs="440px",xt={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{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:void 0,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",borderColor:void 0,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:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""}},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 Ic(e,r){if(!(!e&&!r))return e?r?Wo(e,r):e:r}function hs(e){var r,t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R,w,L;return e?{...xt,...e,theme:Ic(xt.theme,e.theme),darkTheme:Ic(xt.darkTheme,e.darkTheme),launcher:{...xt.launcher,...e.launcher,dock:{...(r=xt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=xt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...xt.copy,...e.copy},sendButton:{...xt.sendButton,...e.sendButton},statusIndicator:{...xt.statusIndicator,...e.statusIndicator},voiceRecognition:{...xt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ne,Te,re,Se;let B=(ne=xt.features)==null?void 0:ne.artifacts,T=(Te=e.features)==null?void 0:Te.artifacts,Y=(re=xt.features)==null?void 0:re.scrollToBottom,ge=(Se=e.features)==null?void 0:Se.scrollToBottom,ce=B===void 0&&T===void 0?void 0:{...B,...T,layout:{...B==null?void 0:B.layout,...T==null?void 0:T.layout}},$=Y===void 0&&ge===void 0?void 0:{...Y,...ge};return{...xt.features,...e.features,...$!==void 0?{scrollToBottom:$}:{},...ce!==void 0?{artifacts:ce}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:xt.suggestionChips,suggestionChipsConfig:{...xt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...xt.layout,...e.layout,header:{...(a=xt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=xt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=xt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(M=(v=xt.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(C=(b=e.layout)==null?void 0:b.messages)==null?void 0:C.timestamp}},slots:{...(S=xt.layout)==null?void 0:S.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...xt.markdown,...e.markdown,options:{...(w=xt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...xt.messageActions,...e.messageActions}}:xt}var Ys={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},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"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},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"}},Gs={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",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.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.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"}},Xs={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Mn,maxWidth:fs,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},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"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ro(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ro(e,n):n}function ys(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Ro(e,a);d!==void 0&&(r[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.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"),r}function Ks(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function Pc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=Pc(o,s):t[n]=s}return t}function xp(e,r){return r?Pc(e,r):e}function so(e,r={}){var s,o,a,i,d,c,p,u,f,m,v,M,b;let t={palette:Ys,semantic:Gs,components:Xs},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:xp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=Ks(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function bs(e){var v,M,b,C,S,R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O,Le,ue,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Dn,Xe,Mr,Vn,kr,kn,Vr,dr,Kn,et,xn,Fn,an,pr,vn,ft,ln,Ln,ur,Zn,gr,qn,Cn,Jn,ht,Wt,Rt,wn,mr,Nn,Sn,D,On,In,fr,gn,An;let r=ys(e),t={};for(let[te,$n]of Object.entries(r)){let qr=te.replace(/\./g,"-");t[`--persona-${qr}`]=$n.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(C=t["--persona-semantic-colors-surface"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ge=t["--persona-components-voice-recording-indicator"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ce=t["--persona-components-voice-recording-background"])!=null?ce:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(re=t["--persona-components-approval-requested-border"])!=null?re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Se=t["--persona-components-approval-requested-text"])!=null?Se:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(He=t["--persona-components-approval-approve-background"])!=null?He:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ke=t["--persona-components-attachment-image-border"])!=null?ke:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(be=t["--persona-semantic-typography-fontSize"])!=null?be:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=($e=t["--persona-semantic-typography-fontWeight"])!=null?$e:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(pe=t["--persona-semantic-typography-lineHeight"])!=null?pe:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(de=t["--persona-palette-radius-sm"])!=null?de:"0.125rem",t["--persona-radius-md"]=(se=t["--persona-palette-radius-md"])!=null?se:"0.375rem",t["--persona-radius-lg"]=(De=t["--persona-palette-radius-lg"])!=null?De:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(St=t["--persona-palette-radius-full"])!=null?St:"9999px",t["--persona-launcher-radius"]=(q=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?q:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(ee=t["--persona-components-button-primary-background"])!=null?ee:t["--persona-primary"],t["--persona-button-primary-fg"]=(Fe=t["--persona-components-button-primary-foreground"])!=null?Fe:t["--persona-text-inverse"],t["--persona-button-radius"]=(K=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-panel-radius"]=(tt=(vt=t["--persona-components-panel-borderRadius"])!=null?vt:t["--persona-radius-xl"])!=null?tt:"0.75rem",t["--persona-panel-border"]=(Lt=t["--persona-components-panel-border"])!=null?Lt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ne=(Vt=t["--persona-components-panel-shadow"])!=null?Vt:t["--persona-palette-shadows-xl"])!=null?Ne:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ie=(le=t["--persona-components-input-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-message-user-radius"]=(Et=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?Et:"0.5rem",t["--persona-message-assistant-radius"]=(Qe=(Ze=t["--persona-components-message-assistant-borderRadius"])!=null?Ze:t["--persona-radius-lg"])!=null?Qe:"0.5rem",t["--persona-header-bg"]=(Kt=t["--persona-components-header-background"])!=null?Kt:t["--persona-surface"],t["--persona-header-border"]=(Gt=t["--persona-components-header-border"])!=null?Gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Zt=t["--persona-components-header-iconBackground"])!=null?Zt:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(at=t["--persona-components-header-actionIconForeground"])!=null?at:t["--persona-muted"];let n=(Be=e.components)==null?void 0:Be.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(Z=t["--persona-components-input-background"])!=null?Z:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(dt=t["--persona-components-message-user-text"])!=null?dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ot=t["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(nt=t["--persona-components-message-assistant-background"])!=null?nt:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(it=t["--persona-components-message-assistant-border"])!=null?it:t["--persona-border"],t["--persona-message-assistant-shadow"]=(qe=t["--persona-components-message-assistant-shadow"])!=null?qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(_e=(lt=t["--persona-components-scrollToBottom-background"])!=null?lt:t["--persona-button-primary-bg"])!=null?_e:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Un=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?Un:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Xn=t["--persona-components-scrollToBottom-border"])!=null?Xn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Dn=t["--persona-components-scrollToBottom-size"])!=null?Dn:"40px",t["--persona-scroll-to-bottom-radius"]=(Vn=(Mr=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Mr:t["--persona-radius-full"])!=null?Vn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(kn=(kr=t["--persona-components-scrollToBottom-shadow"])!=null?kr:t["--persona-palette-shadows-sm"])!=null?kn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Vr=t["--persona-components-scrollToBottom-padding"])!=null?Vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(dr=t["--persona-components-scrollToBottom-gap"])!=null?dr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(et=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?et:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Fn=t["--persona-components-toolBubble-shadow"])!=null?Fn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(pr=t["--persona-components-composer-shadow"])!=null?pr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(ft=t["--persona-components-markdown-inlineCode-foreground"])!=null?ft:t["--persona-text"],t["--persona-md-link-color"]=(Ln=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?Ln:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(ur=t["--persona-components-markdown-codeBlock-background"])!=null?ur:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Zn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Zn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(gr=t["--persona-components-markdown-codeBlock-textColor"])!=null?gr:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(Jn=t["--persona-components-markdown-hr-color"])!=null?Jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(ht=t["--persona-components-markdown-blockquote-borderColor"])!=null?ht:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(mr=t["--persona-components-collapsibleWidget-surface"])!=null?mr:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let te=m.toolbar;te.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=te.iconHoverColor),te.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=te.iconHoverBackground),te.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=te.iconPadding),te.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=te.iconBorderRadius),te.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=te.iconBorder),te.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=te.toggleGroupGap),te.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=te.toggleBorderRadius),te.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=te.copyBackground),te.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=te.copyBorder),te.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=te.copyColor),te.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=te.copyBorderRadius),te.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=te.copyPadding),te.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=te.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:te.copyMenuBackground),te.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=te.copyMenuBorder,t["--persona-dropdown-border"]=(On=t["--persona-dropdown-border"])!=null?On:te.copyMenuBorder),te.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=te.copyMenuShadow,t["--persona-dropdown-shadow"]=(In=t["--persona-dropdown-shadow"])!=null?In:te.copyMenuShadow),te.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=te.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(fr=t["--persona-dropdown-radius"])!=null?fr:te.copyMenuBorderRadius),te.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=te.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:te.copyMenuItemHoverBackground),te.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=te.iconBackground),te.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=te.toolbarBorder)}if(m!=null&&m.tab){let te=m.tab;te.background&&(t["--persona-artifact-tab-bg"]=te.background),te.activeBackground&&(t["--persona-artifact-tab-active-bg"]=te.activeBackground),te.activeBorder&&(t["--persona-artifact-tab-active-border"]=te.activeBorder),te.borderRadius&&(t["--persona-artifact-tab-radius"]=te.borderRadius),te.textColor&&(t["--persona-artifact-tab-color"]=te.textColor),te.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=te.hoverBackground),te.listBackground&&(t["--persona-artifact-tab-list-bg"]=te.listBackground),te.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=te.listBorderColor),te.listPadding&&(t["--persona-artifact-tab-list-padding"]=te.listPadding)}if(m!=null&&m.pane){let te=m.pane;if(te.toolbarBackground){let $n=(An=Ro(e,te.toolbarBackground))!=null?An:te.toolbarBackground;t["--persona-artifact-toolbar-bg"]=$n}}return t}var Wc={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var vp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},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"}}},Rc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ho=()=>{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"},Cp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Ho()},Zs=e=>Cp(e),wp=e=>so(e),Sp=e=>{var t;let r=so(void 0,{validate:!1});return so({...e,palette:{...r.palette,colors:{...vp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Bo=e=>{let r=Zs(e),t=Rc(e==null?void 0:e.theme),n=Rc(e==null?void 0:e.darkTheme);return r==="dark"?Sp(Wo(t!=null?t:{},n!=null?n:{})):wp(t)},Ap=e=>bs(e),wr=(e,r)=>{var o;let t=Bo(r),n=Ap(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},xs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ho())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Ho());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Hc=require("idiomorph"),Bc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Hc.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Dc(e,r){var t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(C=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?C:0,(R=(S=e.contentParts)==null?void 0:S.length)!=null?R:0,r].join("\0")}function Fc(){return new Map}function Nc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Oc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function $c(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function vs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Do(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fo(e,r){return Do(e)-e.scrollTop<=r}function Cs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function ws(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,Sr=yn+1;function Qs(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var No=0,Ar=null;function ea(e=document){var t;if(No++,No===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Ar={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,No=Math.max(0,No-1),No===0&&Ar)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Ar.originalOverflow,s.style.position=Ar.originalPosition,s.style.top=Ar.originalTop,s.style.width=Ar.originalWidth,o.scrollTo(0,Ar.scrollY),Ar=null}}}var Ss={side:"right",width:"420px",animate:!0,reveal:"resize"},Ut=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Hn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Ss.side,width:(s=r==null?void 0:r.width)!=null?s:Ss.width,animate:(o=r==null?void 0:r.animate)!=null?o:Ss.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Ss.reveal}};var zn={"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 Oo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
7
|
+
`),Qt="message",Ht="";for(let I of Pt)I.startsWith("event:")?Qt=I.replace("event:","").trim():I.startsWith("data:")&&(Ht+=I.replace("data:","").trim());if(!Ht)continue;let x;try{x=JSON.parse(Ht)}catch(I){t({type:"error",error:I instanceof Error?I:new Error("Failed to parse chat stream payload")});continue}let We=Qt!=="message"?Qt:(q=x.type)!=null?q:"message";if((ae=this.onSSEEvent)==null||ae.call(this,We,x),this.parseSSEEvent){m.current=f;let I=await this.handleCustomSSEEvent(x,t,m,u,c,v);if(m.current&&m.current!==f&&(f=m.current),I)continue}if(We==="reason_start"){let I=(_=$(x,!0))!=null?_:`reason-${c()}`,A=ne(I);A.reasoning=(z=A.reasoning)!=null?z:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Fe=A.reasoning.startedAt)!=null?Fe:be((ee=x.startedAt)!=null?ee:x.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",u(A)}else if(We==="reason_delta"||We==="reason_chunk"){let I=(K=(J=$(x,!1))!=null?J:$(x,!0))!=null?K:`reason-${c()}`,A=ne(I);A.reasoning=(vt=A.reasoning)!=null?vt:{id:I,status:"streaming",chunks:[]},A.reasoning.startedAt=(Lt=A.reasoning.startedAt)!=null?Lt:be((tt=x.startedAt)!=null?tt:x.timestamp);let G=(le=(Ne=(Vt=x.reasoningText)!=null?Vt:x.text)!=null?Ne:x.delta)!=null?le:"";if(G&&x.hidden!==!0&&A.reasoning.chunks.push(String(G)),A.reasoning.status=x.done?"complete":"streaming",x.done){A.reasoning.completedAt=be((Ie=x.completedAt)!=null?Ie:x.timestamp);let N=(At=A.reasoning.startedAt)!=null?At:Date.now();A.reasoning.durationMs=Math.max(0,((Et=A.reasoning.completedAt)!=null?Et:Date.now())-N)}A.streaming=A.reasoning.status!=="complete",u(A)}else if(We==="reason_complete"){let I=(Qe=(Ze=$(x,!1))!=null?Ze:$(x,!0))!=null?Qe:`reason-${c()}`,A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be((Kt=x.completedAt)!=null?Kt:x.timestamp);let N=(Gt=A.reasoning.startedAt)!=null?Gt:Date.now();A.reasoning.durationMs=Math.max(0,((Zt=A.reasoning.completedAt)!=null?Zt:Date.now())-N),A.streaming=!1,u(A)}let G=L(x);G&&S.byStep.delete(G)}else if(We==="tool_start"){let I=(O=ke(x,!0))!=null?O:`tool-${c()}`,A=(Le=x.toolName)!=null?Le:x.name;if(Me(A)){re.add(I);continue}let G=oe(I),N=(ue=G.toolCall)!=null?ue:{id:I,status:"pending"};N.name=A!=null?A:N.name,N.status="running",x.args!==void 0?N.args=x.args:x.parameters!==void 0&&(N.args=x.parameters),N.startedAt=(Be=N.startedAt)!=null?Be:be((at=x.startedAt)!=null?at:x.timestamp),N.completedAt=void 0,N.durationMs=void 0,G.toolCall=N,G.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(G.agentMetadata={executionId:(Z=Q==null?void 0:Q.executionId)!=null?Z:x.executionId,iteration:(ye=Q==null?void 0:Q.iteration)!=null?ye:x.iteration}),u(G)}else if(We==="tool_chunk"||We==="tool_delta"){let I=(dt=(Pe=ke(x,!1))!=null?Pe:ke(x,!0))!=null?dt:`tool-${c()}`;if(re.has(I))continue;let A=oe(I),G=(Ot=A.toolCall)!=null?Ot:{id:I,status:"running"};G.startedAt=($t=G.startedAt)!=null?$t:be((nt=x.startedAt)!=null?nt:x.timestamp);let N=(lt=(qe=(it=x.text)!=null?it:x.delta)!=null?qe:x.message)!=null?lt:"";N&&(G.chunks=(_e=G.chunks)!=null?_e:[],G.chunks.push(String(N))),G.status="running",A.toolCall=G,A.streaming=!0;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(Xn=A.agentMetadata)!=null?Xn:{executionId:(_t=Q==null?void 0:Q.executionId)!=null?_t:x.executionId,iteration:(Un=Q==null?void 0:Q.iteration)!=null?Un:x.iteration}),u(A)}else if(We==="tool_complete"){let I=(Xe=(Dn=ke(x,!1))!=null?Dn:ke(x,!0))!=null?Xe:`tool-${c()}`;if(re.has(I)){re.delete(I);continue}let A=oe(I),G=(Mr=A.toolCall)!=null?Mr:{id:I,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=be((Vn=x.completedAt)!=null?Vn:x.timestamp);let N=(kr=x.duration)!=null?kr:x.executionTime;if(typeof N=="number")G.durationMs=N;else{let Mt=(kn=G.startedAt)!=null?kn:Date.now();G.durationMs=Math.max(0,((Vr=G.completedAt)!=null?Vr:Date.now())-Mt)}A.toolCall=G,A.streaming=!1;let Q=x.agentContext;(Q||x.executionId)&&(A.agentMetadata=(et=A.agentMetadata)!=null?et:{executionId:(dr=Q==null?void 0:Q.executionId)!=null?dr:x.executionId,iteration:(Kn=Q==null?void 0:Q.iteration)!=null?Kn:x.iteration}),u(A);let ut=B(x);ut&&R.byCall.delete(ut)}else if(We==="text_start"){let I=x.partId;if(I!==void 0&&v.current!==null&&I!==v.current){let A=f;A&&(A.streaming=!1,u(A),f=null,M=!0)}I!==void 0&&(v.current=I)}else if(We==="text_end"){let I=f;I&&(I.streaming=!1,u(I),f=null,M=!0)}else if(We==="step_chunk"||We==="step_delta"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;let G=x.partId;if(G!==void 0&&v.current!==null&&G!==v.current){let ut=f;ut&&(ut.streaming=!1,u(ut),f=null,M=!0)}G!==void 0&&(v.current=G);let N=ge();G!==void 0&&!N.partId&&(N.partId=G);let Q=(pr=(an=(Fn=(xn=x.text)!=null?xn:x.delta)!=null?Fn:x.content)!=null?an:x.chunk)!=null?pr:"";if(Q){let Mt=((vn=de.get(N.id))!=null?vn:"")+Q;N.rawContent=Mt,pe.has(N.id)||pe.set(N.id,this.createStreamParser());let Bt=pe.get(N.id),en=Mt.trim().startsWith("{")||Mt.trim().startsWith("[");if(en&&de.set(N.id,Mt),Bt.__isPlainTextParser===!0){N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N);continue}let tn=Bt.processChunk(Mt);if(tn instanceof Promise)tn.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null&&Ct.trim()!==""){let bt=f;bt&&bt.id===N.id&&(bt.content=Ct,u(bt))}else if(!en&&!Mt.trim().startsWith("<")){let bt=f;bt&&bt.id===N.id&&(bt.content+=Q,de.delete(bt.id),pe.delete(bt.id),bt.rawContent=void 0,u(bt))}}).catch(()=>{N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N)});else{let Ae=typeof tn=="string"?tn:(ft=tn==null?void 0:tn.text)!=null?ft:null;Ae!==null&&Ae.trim()!==""?(N.content=Ae,u(N)):!en&&!Mt.trim().startsWith("<")&&(N.content+=Q,de.delete(N.id),pe.delete(N.id),N.rawContent=void 0,u(N))}}if(x.isComplete){let ut=(Ln=(ln=x.result)==null?void 0:ln.response)!=null?Ln:N.content;if(ut){let Mt=de.get(N.id),Bt=Mt!=null?Mt:$e(ut);N.rawContent=Bt;let en=pe.get(N.id),qt=null,tn=!1;if(en&&(qt=en.getExtractedText(),qt===null&&(qt=rs(Bt)),qt===null)){let Ae=en.processChunk(Bt);Ae instanceof Promise?(tn=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}})):qt=typeof Ae=="string"?Ae:(ur=Ae==null?void 0:Ae.text)!=null?ur:null}if(!tn){qt!==null&&qt.trim()!==""?N.content=qt:de.has(N.id)||(N.content=$e(ut));let Ae=pe.get(N.id);if(Ae){let Ct=(Zn=Ae.close)==null?void 0:Zn.call(Ae);Ct instanceof Promise&&Ct.catch(()=>{}),pe.delete(N.id)}de.delete(N.id),N.streaming=!1,u(N)}}}}else if(We==="step_complete"){let I=x.stepType,A=x.executionType;if(I==="tool"||A==="context")continue;if(M){if(f!==null){let Q=f;pe.delete(Q.id),de.delete(Q.id),Q.streaming!==!1&&(Q.streaming=!1,u(Q))}continue}let G=(gr=x.result)==null?void 0:gr.response,N=ge();if(G!=null){let Q=pe.get(N.id),ut=!1,Mt=!1;if(Q){let Bt=Q.getExtractedText(),en=de.get(N.id),qt=en!=null?en:$e(G);if(N.rawContent=qt,Bt!==null&&Bt.trim()!=="")N.content=Bt,ut=!0;else{let tn=rs(qt);if(tn!==null)N.content=tn,ut=!0;else{let Ae=Q.processChunk(qt);if(Ae instanceof Promise)Mt=!0,Ae.then(Ct=>{var bt;let yt=typeof Ct=="string"?Ct:(bt=Ct==null?void 0:Ct.text)!=null?bt:null;if(yt!==null&&yt.trim()!==""){let Dt=f;Dt&&Dt.id===N.id&&(Dt.content=yt,Dt.streaming=!1,pe.delete(Dt.id),de.delete(Dt.id),u(Dt))}else{let Dt=Q.getExtractedText(),Wn=f;Wn&&Wn.id===N.id&&(Dt!==null&&Dt.trim()!==""?Wn.content=Dt:de.has(Wn.id)||(Wn.content=$e(G)),Wn.streaming=!1,pe.delete(Wn.id),de.delete(Wn.id),u(Wn))}});else{let Ct=typeof Ae=="string"?Ae:(qn=Ae==null?void 0:Ae.text)!=null?qn:null;if(Ct!==null&&Ct.trim()!=="")N.content=Ct,ut=!0;else{let yt=Q.getExtractedText();yt!==null&&yt.trim()!==""&&(N.content=yt,ut=!0)}}}}}if(!Mt){if(!N.rawContent){let Bt=de.get(N.id);N.rawContent=Bt!=null?Bt:$e(G)}if(!ut&&!de.has(N.id)&&(N.content=$e(G)),Q){let Bt=(Cn=Q.close)==null?void 0:Cn.call(Q);Bt instanceof Promise&&Bt.catch(()=>{})}pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}}else pe.delete(N.id),de.delete(N.id),N.streaming=!1,u(N)}else if(We==="flow_complete"){let I=(Jn=x.result)==null?void 0:Jn.response;if(M){if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}}else if(I!=null){let A=ge(),G=de.get(A.id),N=G!=null?G:$e(I);A.rawContent=N;let Q=$e(I),ut=pe.get(A.id);if(ut){let en=rs(N);if(en!==null)Q=en;else{let qt=ut.processChunk(N);qt instanceof Promise&&qt.then(Ae=>{var yt;let Ct=typeof Ae=="string"?Ae:(yt=Ae==null?void 0:Ae.text)!=null?yt:null;if(Ct!==null){let bt=f;bt&&bt.id===A.id&&(bt.content=Ct,bt.streaming=!1,u(bt))}});let tn=ut.getExtractedText();tn!==null&&(Q=tn)}}pe.delete(A.id),de.delete(A.id);let Mt=Q!==A.content,Bt=A.streaming!==!1;Mt&&(A.content=Q),A.streaming=!1,(Mt||Bt)&&u(A)}else if(f!==null){let A=f;pe.delete(A.id),de.delete(A.id),A.streaming!==!1&&(A.streaming=!1,u(A))}t({type:"status",status:"idle"})}else if(We==="agent_start")se={executionId:x.executionId,agentId:(ht=x.agentId)!=null?ht:"virtual",agentName:(Wt=x.agentName)!=null?Wt:"",status:"running",currentIteration:0,maxTurns:(Rt=x.maxTurns)!=null?Rt:1,startedAt:be(x.startedAt)};else if(We==="agent_iteration_start"){if(se&&(se.currentIteration=x.iteration),ot==="separate"&&x.iteration>1){let I=f;I&&(I.streaming=!1,u(I),De.set(x.iteration-1,I),f=null)}}else if(We!=="agent_turn_start"){if(We==="agent_turn_delta"){if(x.contentType==="text"){let I=ge();I.content+=(wn=x.delta)!=null?wn:"",I.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId,agentName:se==null?void 0:se.agentName},u(I)}else if(x.contentType==="thinking"){let I=(mr=x.turnId)!=null?mr:`agent-think-${x.iteration}`,A=ne(I);A.reasoning=(Nn=A.reasoning)!=null?Nn:{id:I,status:"streaming",chunks:[]},A.reasoning.chunks.push((Sn=x.delta)!=null?Sn:""),A.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:x.turnId},u(A)}else if(x.contentType==="tool_input"){let I=(D=x.toolCallId)!=null?D:R.lastId;if(I){let A=C.get(I);A!=null&&A.toolCall&&(A.toolCall.chunks=(On=A.toolCall.chunks)!=null?On:[],A.toolCall.chunks.push((In=x.delta)!=null?In:""),u(A))}}}else if(We==="agent_turn_complete"){let I=x.turnId;if(I){let A=b.get(I);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=be(x.completedAt);let G=(fr=A.reasoning.startedAt)!=null?fr:Date.now();A.reasoning.durationMs=Math.max(0,((gn=A.reasoning.completedAt)!=null?gn:Date.now())-G),A.streaming=!1,u(A)}}}else if(We==="agent_tool_start"){let I=(An=x.toolCallId)!=null?An:`agent-tool-${c()}`;Te(B(x),I);let A=oe(I),G=(te=A.toolCall)!=null?te:{id:I,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};G.name=(qr=($n=x.toolName)!=null?$n:x.name)!=null?qr:G.name,G.status="running",x.parameters!==void 0&&(G.args=x.parameters),G.startedAt=be((fo=x.startedAt)!=null?fo:x.timestamp),A.toolCall=G,A.streaming=!0,A.agentMetadata={executionId:x.executionId,iteration:x.iteration},u(A)}else if(We==="agent_tool_delta"){let I=(Jr=x.toolCallId)!=null?Jr:R.lastId;if(I){let A=(Je=C.get(I))!=null?Je:oe(I);A.toolCall&&(A.toolCall.chunks=(ho=A.toolCall.chunks)!=null?ho:[],A.toolCall.chunks.push((Pn=x.delta)!=null?Pn:""),A.toolCall.status="running",A.streaming=!0,u(A))}}else if(We==="agent_tool_complete"){let I=(mn=x.toolCallId)!=null?mn:R.lastId;if(I){let A=(Yo=C.get(I))!=null?Yo:oe(I);if(A.toolCall){A.toolCall.status="complete",x.result!==void 0&&(A.toolCall.result=x.result),typeof x.executionTime=="number"&&(A.toolCall.durationMs=x.executionTime),A.toolCall.completedAt=be((Go=x.completedAt)!=null?Go:x.timestamp),A.streaming=!1,u(A);let G=B(x);G&&R.byCall.delete(G)}}}else if(We!=="agent_iteration_complete"){if(We==="agent_reflection"||We==="agent_reflect"){let I=`agent-reflection-${x.executionId}-${x.iteration}`,A={id:I,role:"assistant",content:(yo=x.reflection)!=null?yo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:I,status:"complete",chunks:[(Qn=x.reflection)!=null?Qn:""]},agentMetadata:{executionId:x.executionId,iteration:x.iteration}};u(A)}else if(We==="agent_complete"){se&&(se.status=x.success?"complete":"error",se.completedAt=be(x.completedAt),se.stopReason=x.stopReason);let I=f;I&&(I.streaming=!1,u(I)),t({type:"status",status:"idle"})}else if(We==="agent_error"){let I=typeof x.error=="string"?x.error:(Yr=(Xo=x.error)==null?void 0:Xo.message)!=null?Yr:"Agent execution error";x.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",I):t({type:"error",error:new Error(I)})}else if(We!=="agent_ping")if(We==="agent_approval_start"){let I=(Gr=x.approvalId)!=null?Gr:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(er=se==null?void 0:se.agentId)!=null?er:"virtual",executionId:(hr=(bo=x.executionId)!=null?bo:se==null?void 0:se.executionId)!=null?hr:"",toolName:(yr=x.toolName)!=null?yr:"",toolType:x.toolType,description:(Zo=x.description)!=null?Zo:`Execute ${(Ko=x.toolName)!=null?Ko:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="step_await"&&x.awaitReason==="approval_required"){let I=(zs=x.approvalId)!=null?zs:`approval-${c()}`,A={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:"pending",agentId:(Lr=se==null?void 0:se.agentId)!=null?Lr:"virtual",executionId:(Tt=(Ir=x.executionId)!=null?Ir:se==null?void 0:se.executionId)!=null?Tt:"",toolName:(Xr=x.toolName)!=null?Xr:"",toolType:x.toolType,description:(xo=x.description)!=null?xo:`Execute ${(Kr=x.toolName)!=null?Kr:"tool"}`,parameters:x.parameters}};u(A)}else if(We==="agent_approval_complete"){let I=x.approvalId;if(I){let G={id:`approval-${I}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:I,status:(vo=x.decision)!=null?vo:"approved",agentId:(Co=se==null?void 0:se.agentId)!=null?Co:"virtual",executionId:(cn=(wo=x.executionId)!=null?wo:se==null?void 0:se.executionId)!=null?cn:"",toolName:(En=x.toolName)!=null?En:"",description:(tr=x.description)!=null?tr:"",resolvedAt:Date.now()}};u(G)}}else if(We==="artifact_start"||We==="artifact_delta"||We==="artifact_update"||We==="artifact_complete"){if(We==="artifact_start"){let I=x.artifactType,A=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:A,artifactType:I,title:G,component:typeof x.component=="string"?x.component:void 0}),he.set(A,{markdown:"",title:G}),!He.has(A)){He.add(A);let N={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:G,artifactType:I,status:"streaming"}})};Se.set(A,N),u(N)}}else if(We==="artifact_delta"){let I=String(x.id),A=typeof x.delta=="string"?x.delta:String((je=x.delta)!=null?je:"");t({type:"artifact_delta",id:I,artDelta:A});let G=he.get(I);G&&(G.markdown+=A)}else if(We==="artifact_update"){let I=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:I,component:typeof x.component=="string"?x.component:void 0})}else if(We==="artifact_complete"){let I=String(x.id);t({type:"artifact_complete",id:I});let A=Se.get(I);if(A){A.streaming=!1;try{let G=JSON.parse((So=A.rawContent)!=null?So:"{}");if(G.props){G.props.status="complete";let N=he.get(I);N!=null&&N.markdown&&(G.props.markdown=N.markdown)}A.rawContent=JSON.stringify(G)}catch{}he.delete(I),u(A),Se.delete(I)}}}else if(We==="transcript_insert"){let I=x.message;if(!I||typeof I!="object")continue;let A=String((Pr=I.id)!=null?Pr:`msg-${c()}`),G=I.role,Q={id:A,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof I.content=="string"?I.content:"",rawContent:typeof I.rawContent=="string"?I.rawContent:void 0,createdAt:typeof I.createdAt=="string"?I.createdAt:new Date().toISOString(),streaming:I.streaming===!0,...typeof I.variant=="string"?{variant:I.variant}:{},sequence:c()};if(u(Q),Q.rawContent)try{let ut=JSON.parse(Q.rawContent),Mt=(_n=ut==null?void 0:ut.props)==null?void 0:_n.artifactId;typeof Mt=="string"&&He.add(Mt)}catch{}f=null,m.current=null,pe.delete(A),de.delete(A)}else We==="error"&&x.error&&t({type:"error",error:x.error instanceof Error?x.error:new Error(String(x.error))})}}}}}};function yc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function ro(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Fr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ls="[Image]";function bc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function xc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function vc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Cc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function cs(e){return{type:"text",text:e}}function wc(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function Sc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Ac(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.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: ${r.join(", ")}`}}var Ec=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],up=["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"],ar=[...Ec,...up];function gp(e){return Ec.includes(e)||e.startsWith("image/")}function ds(e){return gp(e.type)}async function Tc(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;ds(e)?r({type:"image",image:s,mimeType:e.type,alt:e.name}):r({type:"file",data:s,mimeType:e.type,filename:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function Mc(e,r=ar,t=10*1024*1024){return r.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: ${r.join(", ")}`}}function mp(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function kc(e,r){let t=mp(r).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 ps=class{constructor(r=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=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,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 n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.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 r of this.activeSources)try{r.stop(),r.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(r){this.finishedCallbacks.push(r)}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 r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var us=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(r,t,n,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=r.createMediaStreamSource(t),this.analyserNode=r.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 p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):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 Io=class{constructor(r){this.config=r;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 us;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(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.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=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,M=C=>{v||(v=!0,clearTimeout(b),m(new Error(C)))},b=setTimeout(()=>M("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{M("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",C=>{if(!C.wasClean&&!v){let S=C.code!==1006?` (code ${C.code})`:"";M("WebSocket connection failed"+S+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new ps(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(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("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 r,t,n,s;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 o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.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(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),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(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}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(r=>r.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(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Nr=class{constructor(r={}){this.config=r;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(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Or(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Io(e.runtype);case"browser":if(!Nr.isSupported())throw new Error("Browser speech recognition not supported");return new Nr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function gs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Or({type:"runtype",runtype:e.runtype});if(Nr.isSupported())return Or({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Po(e){try{return gs(e),!0}catch{return!1}}var oo=class e{constructor(r={},t){this.config=r;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=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.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,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Dr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return Po((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Or(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"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 p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var p,u,f,m,v,M;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((p=c.transcript)!=null&&p.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(u=c.transcript)!=null&&u.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.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 b=(M=this.pendingVoiceAssistantMessageId)!=null?M:(v=[...this.messages].reverse().find(C=>C.role==="assistant"))==null?void 0:v.id;b&&this.ttsSpokenMessageIds.add(b)}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 p,u;this.voiceStatus=c,this.voiceActive=c==="listening",(u=(p=this.callbacks).onVoiceStatusChanged)==null||u.call(p,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}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(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(p=r.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var r,t;if(!this.isClientTokenMode())return null;try{let n=await this.client.initSession();return this.setClientSession(n),n}catch(n){return(t=(r=this.callbacks).onError)==null||t.call(r,n instanceof Error?n:new Error(String(n))),null}}setClientSession(r){if(this.clientSession=r,r.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:r.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var r;return(r=this.clientSession)!=null?r:this.client.getClientSession()}isSessionValid(){let r=this.getClientSession();return r?new Date<r.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(r,t){return this.client.submitMessageFeedback(r,t)}async submitCSATFeedback(r,t){return this.client.submitCSATFeedback(r,t)}async submitNPSFeedback(r,t){return this.client.submitNPSFeedback(r,t)}updateConfig(r){let t=this.client.getSSEEventCallback();this.config={...this.config,...r},this.client=new Dr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?ro():t==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...p!==void 0&&{voiceProcessing:p}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1}=n,m={id:d!=null?d:s==="user"?ro():s==="assistant"?Fr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...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(r,t){var c,p,u,f,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=ro(),o=Fr(),a={id:s,role:"user",content:n||ls,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:o},this.handleEvent)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!M){let b={id:o,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(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,M||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Fr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let n=[...this.messages];try{await this.client.dispatch({messages:n,signal:t.signal,assistantMessageId:r},this.handleEvent)}catch(c){let p={id:r,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(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,p;let n=`approval-${r.id}`,s={...r,status:t,resolvedAt:Date.now()},o={id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:s};this.upsertMessage(o);let a=this.config.approval,i=a&&typeof a=="object"?a.onDecision:void 0;try{let u;if(i?u=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):u=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),u){let f=null;if(u instanceof Response){if(!u.ok){let m=await u.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${u.status}`)}f=u.body}else u instanceof ReadableStream&&(f=u);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(u){(p=(c=this.callbacks).onError)==null||p.call(c,u instanceof Error?u:new Error(String(u)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.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(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;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 s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},Yn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var fp=ac(require("lucide"),1),me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=fp[s];return o?hp(o,r,t,n):(console.warn(`Lucide icon "${e}" not found (tried "${s}"). Available icons: https://lucide.dev/icons`),null)}catch(s){return console.warn(`Failed to render Lucide icon "${e}":`,s),null}};function hp(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),s.appendChild(d)}}}),s}var ms={allowedTypes:ar,maxFileSize:10*1024*1024,maxFiles:4};function yp(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function bp(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 $r=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:ms.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:ms.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:ms.maxFiles,onFileRejected:r.onFileRejected,onAttachmentsChange:r.onAttachmentsChange}}setPreviewsContainer(r){this.previewsContainer=r}updateConfig(r){r.allowedTypes!==void 0&&(this.config.allowedTypes=r.allowedTypes.length>0?r.allowedTypes:ms.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let p=Mc(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,u);continue}try{let u=await Tc(c),f=ds(c)?URL.createObjectURL(c):null,m={id:yp(),file:c,previewUrl:f,contentPart:u};this.attachments.push(m),this.renderPreview(m)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=ds(r.file),n=h("div","persona-attachment-preview persona-relative persona-inline-block");if(n.setAttribute("data-attachment-id",r.id),n.style.width="48px",n.style.height="48px",t&&r.previewUrl){let a=h("img");a.src=r.previewUrl,a.alt=r.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",n.appendChild(a)}else{let a=h("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=bp(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=kc(r.file.type,r.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),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var Lc=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Wo(e,r){if(!e)return r;if(!r)return e;let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];Lc(o)&&Lc(s)?t[n]=Wo(o,s):t[n]=s}return t}var Mn="min(440px, calc(100vw - 24px))",fs="440px",xt={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:Mn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{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:void 0,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",borderColor:void 0,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:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""}},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 Ic(e,r){if(!(!e&&!r))return e?r?Wo(e,r):e:r}function hs(e){var r,t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R,w,L;return e?{...xt,...e,theme:Ic(xt.theme,e.theme),darkTheme:Ic(xt.darkTheme,e.darkTheme),launcher:{...xt.launcher,...e.launcher,dock:{...(r=xt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=xt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...xt.copy,...e.copy},sendButton:{...xt.sendButton,...e.sendButton},statusIndicator:{...xt.statusIndicator,...e.statusIndicator},voiceRecognition:{...xt.voiceRecognition,...e.voiceRecognition},features:(()=>{var ne,Te,re,Se;let B=(ne=xt.features)==null?void 0:ne.artifacts,T=(Te=e.features)==null?void 0:Te.artifacts,Y=(re=xt.features)==null?void 0:re.scrollToBottom,ge=(Se=e.features)==null?void 0:Se.scrollToBottom,ce=B===void 0&&T===void 0?void 0:{...B,...T,layout:{...B==null?void 0:B.layout,...T==null?void 0:T.layout}},$=Y===void 0&&ge===void 0?void 0:{...Y,...ge};return{...xt.features,...e.features,...$!==void 0?{scrollToBottom:$}:{},...ce!==void 0?{artifacts:ce}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:xt.suggestionChips,suggestionChipsConfig:{...xt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...xt.layout,...e.layout,header:{...(a=xt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=xt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=xt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(M=(v=xt.layout)==null?void 0:v.messages)==null?void 0:M.timestamp,...(C=(b=e.layout)==null?void 0:b.messages)==null?void 0:C.timestamp}},slots:{...(S=xt.layout)==null?void 0:S.slots,...(R=e.layout)==null?void 0:R.slots}},markdown:{...xt.markdown,...e.markdown,options:{...(w=xt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...xt.messageActions,...e.messageActions}}:xt}var Ys={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},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"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},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"}},Gs={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",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.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.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"}},Xs={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",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:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:Mn,maxWidth:fs,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},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"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Ro(e,r){if(!r.startsWith("palette.")&&!r.startsWith("semantic.")&&!r.startsWith("components."))return r;let t=r.split("."),n=e;for(let s of t){if(n==null)return;n=n[s]}return typeof n=="string"&&(n.startsWith("palette.")||n.startsWith("semantic.")||n.startsWith("components."))?Ro(e,n):n}function ys(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Ro(e,a);d!==void 0&&(r[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.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"),r}function Ks(e){let r=[],t=[];return e.palette||r.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:r.length===0,errors:r,warnings:t}}function Pc(e,r){let t={...e};for(let[n,s]of Object.entries(r)){let o=t[n];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[n]=Pc(o,s):t[n]=s}return t}function xp(e,r){return r?Pc(e,r):e}function so(e,r={}){var s,o,a,i,d,c,p,u,f,m,v,M,b;let t={palette:Ys,semantic:Gs,components:Xs},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.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,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(M=e==null?void 0:e.semantic)==null?void 0:M.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:xp(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let C=Ks(n);if(!C.valid)throw new Error(`Theme validation failed: ${C.errors.map(S=>S.message).join(", ")}`)}if(r.plugins)for(let C of r.plugins)n=C.transform(n);return n}function bs(e){var v,M,b,C,S,R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O,Le,ue,at,Be,Z,ye,Pe,dt,Ot,nt,$t,it,qe,lt,_e,_t,Un,Xn,Dn,Xe,Mr,Vn,kr,kn,Vr,dr,Kn,et,xn,Fn,an,pr,vn,ft,ln,Ln,ur,Zn,gr,qn,Cn,Jn,ht,Wt,Rt,wn,mr,Nn,Sn,D,On,In,fr,gn,An;let r=ys(e),t={};for(let[te,$n]of Object.entries(r)){let qr=te.replace(/\./g,"-");t[`--persona-${qr}`]=$n.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(M=t["--persona-semantic-colors-secondary"])!=null?M:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(C=t["--persona-semantic-colors-surface"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(S=t["--persona-semantic-colors-background"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(R=t["--persona-semantic-colors-container"])!=null?R:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(w=t["--persona-semantic-colors-text"])!=null?w:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(L=t["--persona-semantic-colors-text-muted"])!=null?L:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(B=t["--persona-semantic-colors-text-inverse"])!=null?B:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(T=t["--persona-semantic-colors-border"])!=null?T:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(Y=t["--persona-semantic-colors-divider"])!=null?Y:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ge=t["--persona-components-voice-recording-indicator"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ce=t["--persona-components-voice-recording-background"])!=null?ce:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=($=t["--persona-components-voice-processing-icon"])!=null?$:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(re=t["--persona-components-approval-requested-border"])!=null?re:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Se=t["--persona-components-approval-requested-text"])!=null?Se:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(He=t["--persona-components-approval-approve-background"])!=null?He:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(he=t["--persona-components-approval-deny-background"])!=null?he:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Me=t["--persona-components-attachment-image-background"])!=null?Me:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ke=t["--persona-components-attachment-image-border"])!=null?ke:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(be=t["--persona-semantic-typography-fontSize"])!=null?be:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=($e=t["--persona-semantic-typography-fontWeight"])!=null?$e:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(pe=t["--persona-semantic-typography-lineHeight"])!=null?pe:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(de=t["--persona-palette-radius-sm"])!=null?de:"0.125rem",t["--persona-radius-md"]=(se=t["--persona-palette-radius-md"])!=null?se:"0.375rem",t["--persona-radius-lg"]=(De=t["--persona-palette-radius-lg"])!=null?De:"0.5rem",t["--persona-radius-xl"]=(ot=t["--persona-palette-radius-xl"])!=null?ot:"0.75rem",t["--persona-radius-full"]=(St=t["--persona-palette-radius-full"])!=null?St:"9999px",t["--persona-launcher-radius"]=(q=(j=t["--persona-components-launcher-borderRadius"])!=null?j:t["--persona-palette-radius-full"])!=null?q:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=(_=t["--persona-components-launcher-foreground"])!=null?_:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(ee=t["--persona-components-button-primary-background"])!=null?ee:t["--persona-primary"],t["--persona-button-primary-fg"]=(Fe=t["--persona-components-button-primary-foreground"])!=null?Fe:t["--persona-text-inverse"],t["--persona-button-radius"]=(K=(J=t["--persona-components-button-primary-borderRadius"])!=null?J:t["--persona-palette-radius-full"])!=null?K:"9999px",t["--persona-panel-radius"]=(tt=(vt=t["--persona-components-panel-borderRadius"])!=null?vt:t["--persona-radius-xl"])!=null?tt:"0.75rem",t["--persona-panel-border"]=(Lt=t["--persona-components-panel-border"])!=null?Lt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ne=(Vt=t["--persona-components-panel-shadow"])!=null?Vt:t["--persona-palette-shadows-xl"])!=null?Ne:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ie=(le=t["--persona-components-input-borderRadius"])!=null?le:t["--persona-radius-lg"])!=null?Ie:"0.5rem",t["--persona-message-user-radius"]=(Et=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?Et:"0.5rem",t["--persona-message-assistant-radius"]=(Qe=(Ze=t["--persona-components-message-assistant-borderRadius"])!=null?Ze:t["--persona-radius-lg"])!=null?Qe:"0.5rem",t["--persona-header-bg"]=(Kt=t["--persona-components-header-background"])!=null?Kt:t["--persona-surface"],t["--persona-header-border"]=(Gt=t["--persona-components-header-border"])!=null?Gt:t["--persona-divider"],t["--persona-header-icon-bg"]=(Zt=t["--persona-components-header-iconBackground"])!=null?Zt:t["--persona-primary"],t["--persona-header-icon-fg"]=(O=t["--persona-components-header-iconForeground"])!=null?O:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ue=t["--persona-components-header-subtitleForeground"])!=null?ue:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(at=t["--persona-components-header-actionIconForeground"])!=null?at:t["--persona-muted"];let n=(Be=e.components)==null?void 0:Be.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(Z=t["--persona-components-input-background"])!=null?Z:t["--persona-surface"],t["--persona-input-placeholder"]=(ye=t["--persona-components-input-placeholder"])!=null?ye:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Pe=t["--persona-components-message-user-background"])!=null?Pe:t["--persona-accent"],t["--persona-message-user-text"]=(dt=t["--persona-components-message-user-text"])!=null?dt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ot=t["--persona-components-message-user-shadow"])!=null?Ot:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(nt=t["--persona-components-message-assistant-background"])!=null?nt:t["--persona-surface"],t["--persona-message-assistant-text"]=($t=t["--persona-components-message-assistant-text"])!=null?$t:t["--persona-text"],t["--persona-message-assistant-border"]=(it=t["--persona-components-message-assistant-border"])!=null?it:t["--persona-border"],t["--persona-message-assistant-shadow"]=(qe=t["--persona-components-message-assistant-shadow"])!=null?qe:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(_e=(lt=t["--persona-components-scrollToBottom-background"])!=null?lt:t["--persona-button-primary-bg"])!=null?_e:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Un=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?Un:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Xn=t["--persona-components-scrollToBottom-border"])!=null?Xn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Dn=t["--persona-components-scrollToBottom-size"])!=null?Dn:"40px",t["--persona-scroll-to-bottom-radius"]=(Vn=(Mr=(Xe=t["--persona-components-scrollToBottom-borderRadius"])!=null?Xe:t["--persona-button-radius"])!=null?Mr:t["--persona-radius-full"])!=null?Vn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(kn=(kr=t["--persona-components-scrollToBottom-shadow"])!=null?kr:t["--persona-palette-shadows-sm"])!=null?kn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Vr=t["--persona-components-scrollToBottom-padding"])!=null?Vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(dr=t["--persona-components-scrollToBottom-gap"])!=null?dr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(et=(Kn=t["--persona-components-scrollToBottom-fontSize"])!=null?Kn:t["--persona-palette-typography-fontSize-sm"])!=null?et:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(xn=t["--persona-components-scrollToBottom-iconSize"])!=null?xn:"14px",t["--persona-tool-bubble-shadow"]=(Fn=t["--persona-components-toolBubble-shadow"])!=null?Fn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(an=t["--persona-components-reasoningBubble-shadow"])!=null?an:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(pr=t["--persona-components-composer-shadow"])!=null?pr:"none",t["--persona-md-inline-code-bg"]=(vn=t["--persona-components-markdown-inlineCode-background"])!=null?vn:t["--persona-container"],t["--persona-md-inline-code-color"]=(ft=t["--persona-components-markdown-inlineCode-foreground"])!=null?ft:t["--persona-text"],t["--persona-md-link-color"]=(Ln=(ln=t["--persona-components-markdown-link-foreground"])!=null?ln:t["--persona-accent"])!=null?Ln:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d),t["--persona-md-code-block-bg"]=(ur=t["--persona-components-markdown-codeBlock-background"])!=null?ur:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Zn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Zn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(gr=t["--persona-components-markdown-codeBlock-textColor"])!=null?gr:"inherit",t["--persona-md-table-header-bg"]=(qn=t["--persona-components-markdown-table-headerBackground"])!=null?qn:t["--persona-container"],t["--persona-md-table-border-color"]=(Cn=t["--persona-components-markdown-table-borderColor"])!=null?Cn:t["--persona-border"],t["--persona-md-hr-color"]=(Jn=t["--persona-components-markdown-hr-color"])!=null?Jn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(ht=t["--persona-components-markdown-blockquote-borderColor"])!=null?ht:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Wt=t["--persona-components-markdown-blockquote-background"])!=null?Wt:"transparent",t["--persona-md-blockquote-text-color"]=(Rt=t["--persona-components-markdown-blockquote-textColor"])!=null?Rt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(wn=t["--persona-components-collapsibleWidget-container"])!=null?wn:t["--persona-surface"],t["--cw-surface"]=(mr=t["--persona-components-collapsibleWidget-surface"])!=null?mr:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Sn=t["--persona-components-message-border"])!=null?Sn:t["--persona-border"];let c=e.components,p=c==null?void 0:c.iconButton;p&&(p.background&&(t["--persona-icon-btn-bg"]=p.background),p.border&&(t["--persona-icon-btn-border"]=p.border),p.color&&(t["--persona-icon-btn-color"]=p.color),p.padding&&(t["--persona-icon-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-icon-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=p.hoverBackground),p.hoverColor&&(t["--persona-icon-btn-hover-color"]=p.hoverColor),p.activeBackground&&(t["--persona-icon-btn-active-bg"]=p.activeBackground),p.activeBorder&&(t["--persona-icon-btn-active-border"]=p.activeBorder));let u=c==null?void 0:c.labelButton;u&&(u.background&&(t["--persona-label-btn-bg"]=u.background),u.border&&(t["--persona-label-btn-border"]=u.border),u.color&&(t["--persona-label-btn-color"]=u.color),u.padding&&(t["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(t["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(t["--persona-label-btn-gap"]=u.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let te=m.toolbar;te.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=te.iconHoverColor),te.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=te.iconHoverBackground),te.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=te.iconPadding),te.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=te.iconBorderRadius),te.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=te.iconBorder),te.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=te.toggleGroupGap),te.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=te.toggleBorderRadius),te.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=te.copyBackground),te.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=te.copyBorder),te.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=te.copyColor),te.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=te.copyBorderRadius),te.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=te.copyPadding),te.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=te.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:te.copyMenuBackground),te.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=te.copyMenuBorder,t["--persona-dropdown-border"]=(On=t["--persona-dropdown-border"])!=null?On:te.copyMenuBorder),te.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=te.copyMenuShadow,t["--persona-dropdown-shadow"]=(In=t["--persona-dropdown-shadow"])!=null?In:te.copyMenuShadow),te.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=te.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(fr=t["--persona-dropdown-radius"])!=null?fr:te.copyMenuBorderRadius),te.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=te.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(gn=t["--persona-dropdown-item-hover-bg"])!=null?gn:te.copyMenuItemHoverBackground),te.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=te.iconBackground),te.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=te.toolbarBorder)}if(m!=null&&m.tab){let te=m.tab;te.background&&(t["--persona-artifact-tab-bg"]=te.background),te.activeBackground&&(t["--persona-artifact-tab-active-bg"]=te.activeBackground),te.activeBorder&&(t["--persona-artifact-tab-active-border"]=te.activeBorder),te.borderRadius&&(t["--persona-artifact-tab-radius"]=te.borderRadius),te.textColor&&(t["--persona-artifact-tab-color"]=te.textColor),te.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=te.hoverBackground),te.listBackground&&(t["--persona-artifact-tab-list-bg"]=te.listBackground),te.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=te.listBorderColor),te.listPadding&&(t["--persona-artifact-tab-list-padding"]=te.listPadding)}if(m!=null&&m.pane){let te=m.pane;if(te.toolbarBackground){let $n=(An=Ro(e,te.toolbarBackground))!=null?An:te.toolbarBackground;t["--persona-artifact-toolbar-bg"]=$n}}return t}var Wc={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var vp={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},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"}}},Rc=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ho=()=>{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"},Cp=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Ho()},Zs=e=>Cp(e),wp=e=>so(e),Sp=e=>{var t;let r=so(void 0,{validate:!1});return so({...e,palette:{...r.palette,colors:{...vp.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Bo=e=>{let r=Zs(e),t=Rc(e==null?void 0:e.theme),n=Rc(e==null?void 0:e.darkTheme);return r==="dark"?Sp(Wo(t!=null?t:{},n!=null?n:{})):wp(t)},Ap=e=>bs(e),wr=(e,r)=>{var o;let t=Bo(r),n=Ap(t);for(let[a,i]of Object.entries(n))e.style.setProperty(a,i);let s=(o=r==null?void 0:r.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},xs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ho())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e(Ho());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};var Hc=require("idiomorph"),Bc=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Hc.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Dc(e,r){var t,n,s,o,a,i,d,c,p,u,f,m,v,M,b,C,S,R;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(C=(b=(M=e.reasoning)==null?void 0:M.chunks)==null?void 0:b.length)!=null?C:0,(R=(S=e.contentParts)==null?void 0:S.length)!=null?R:0,r].join("\0")}function Fc(){return new Map}function Nc(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Oc(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function $c(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function vs(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function Do(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Fo(e,r){return Do(e)-e.scrollTop<=r}function Cs(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-n;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!r&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:r&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:r&&d&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function ws(e){let{following:r,deltaY:t,nearBottom:n=!1,resumeWhenNearBottom:s=!1}=e;return r&&t<0?"pause":!r&&s&&t>0&&n?"resume":"none"}var sn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},yn=1e5,Sr=yn+1;function Qs(e,r=yn){let t=e.style.position,n=e.style.zIndex,s=e.style.isolation,o=getComputedStyle(e),a=o.position==="static"||o.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(r),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=n,e.style.isolation=s}}var No=0,Ar=null;function ea(e=document){var t;if(No++,No===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Ar={originalOverflow:n.style.overflow,originalPosition:n.style.position,originalTop:n.style.top,originalWidth:n.style.width,scrollY:o},n.style.overflow="hidden",n.style.position="fixed",n.style.top=`-${o}px`,n.style.width="100%"}let r=!1;return()=>{var n;if(!r&&(r=!0,No=Math.max(0,No-1),No===0&&Ar)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Ar.originalOverflow,s.style.position=Ar.originalPosition,s.style.top=Ar.originalTop,s.style.width=Ar.originalWidth,o.scrollTo(0,Ar.scrollY),Ar=null}}}var Ss={side:"right",width:"420px",animate:!0,reveal:"resize"},Ut=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Hn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:Ss.side,width:(s=r==null?void 0:r.width)!=null?s:Ss.width,animate:(o=r==null?void 0:r.animate)!=null?o:Ss.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:Ss.reveal}};var zn={"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 Oo=(e,r)=>{let t=h("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-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,8 +12,7 @@
|
|
|
12
12
|
<span class="persona-block persona-w-full persona-truncate 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
|
-
`,t.addEventListener("click",r);let n=o=>{var R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He;let a=(R=o.launcher)!=null?R:{},i=Ut(o),d=t.querySelector("[data-role='launcher-title']");if(d){let he=(w=a.title)!=null?w:"Chat Assistant";d.textContent=he,d.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=t.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let he=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=he,u.style.width=he,u.innerHTML="",a.agentIconName){let Me=parseFloat(he)||24,ke=me(a.agentIconName,Me*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",u.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(ge=a.agentIconSize)!=null?ge:"40px";f.style.height=he,f.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let he=(ce=a.callToActionIconSize)!=null?ce:"32px";m.style.height=he,m.style.width=he,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Me=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Me=(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 ke=parseFloat(he)||24,oe=Math.max(ke-Me,8),be=me(a.callToActionIconName,oe,"currentColor",2);be?m.appendChild(be):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],M="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",b="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?b:`${M} ${v}`,i||(t.style.zIndex=String((Te=a.zIndex)!=null?Te:yn));let C="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(re=a.border)!=null?re:C,t.style.boxShadow=(Se=a.shadow)!=null?Se:S,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(He=a.collapsedMaxWidth)!=null?He:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ir=e=>{var ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(ce=r==null?void 0:r.launcher)!=null?ce:{},o=($=s.headerIconSize)!=null?$:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",d=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let Ne=parseFloat(o)||24,le=me(c,Ne*.6,"currentColor",1);le?p.replaceChildren(le):p.textContent=(He=(Se=r==null?void 0:r.launcher)==null?void 0:Se.agentIconText)!=null?He:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let Ne=h("img");Ne.src=r.launcher.iconUrl,Ne.alt="",Ne.className="persona-rounded-xl persona-object-cover",Ne.style.height=o,Ne.style.width=o,p.replaceChildren(Ne)}else p.textContent=(ke=(Me=r==null?void 0:r.launcher)==null?void 0:Me.agentIconText)!=null?ke:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(be=(oe=r==null?void 0:r.launcher)==null?void 0:oe.title)!=null?be:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(pe=($e=r==null?void 0:r.launcher)==null?void 0:$e.subtitle)!=null?pe:"Here to help you get answers fast",u.append(f,m),d?n.append(u):n.append(p,u);let v=(de=s.clearChat)!=null?de:{},M=(se=v.enabled)!=null?se:!0,b=(De=v.placement)!=null?De:"inline",C=null,S=null;if(M){let Ne=(ot=v.size)!=null?ot:"32px",le=(St=v.iconName)!=null?St:"refresh-cw",Ie=(j=v.iconColor)!=null?j:"",At=(q=v.backgroundColor)!=null?q:"",Et=(ae=v.borderWidth)!=null?ae:"",Ze=(_=v.borderColor)!=null?_:"",Qe=(z=v.borderRadius)!=null?z:"",Kt=(ee=v.paddingX)!=null?ee:"",Gt=(Fe=v.paddingY)!=null?Fe:"",Zt=(J=v.tooltipText)!=null?J:"Clear chat",O=(K=v.showTooltip)!=null?K:!0;S=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(S.style.right="48px"),C=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),C.style.height=Ne,C.style.width=Ne,C.type="button",C.setAttribute("aria-label",Zt),C.style.color=Ie||bn.actionIconColor;let Le=me(le,"20px","currentColor",1);if(Le&&C.appendChild(Le),At&&(C.style.backgroundColor=At,C.classList.remove("hover:persona-bg-gray-100")),Et||Ze){let ue=Et||"0px",at=Ze||"transparent";C.style.border=`${ue} solid ${at}`,C.classList.remove("persona-border-none")}if(Qe&&(C.style.borderRadius=Qe,C.classList.remove("persona-rounded-full")),Kt?(C.style.paddingLeft=Kt,C.style.paddingRight=Kt):(C.style.paddingLeft="",C.style.paddingRight=""),Gt?(C.style.paddingTop=Gt,C.style.paddingBottom=Gt):(C.style.paddingTop="",C.style.paddingBottom=""),S.appendChild(C),O&&Zt&&C&&S){let ue=null,at=()=>{if(ue||!C)return;let Z=C.ownerDocument,ye=Z.body;if(!ye)return;ue=Yn(Z,"div","persona-clear-chat-tooltip"),ue.textContent=Zt;let Pe=Yn(Z,"div");Pe.className="persona-clear-chat-tooltip-arrow",ue.appendChild(Pe);let dt=C.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(Sr),ue.style.left=`${dt.left+dt.width/2}px`,ue.style.top=`${dt.top-8}px`,ue.style.transform="translate(-50%, -100%)",ye.appendChild(ue)},Be=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};S.addEventListener("mouseenter",at),S.addEventListener("mouseleave",Be),C.addEventListener("focus",at),C.addEventListener("blur",Be),S._cleanupTooltip=()=>{Be(),S&&(S.removeEventListener("mouseenter",at),S.removeEventListener("mouseleave",Be)),C&&(C.removeEventListener("focus",at),C.removeEventListener("blur",Be))}}b==="inline"&&n.appendChild(S)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&b==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(vt=s.closeButtonTooltipText)!=null?vt:"Close chat",B=(tt=s.closeButtonShowTooltip)!=null?tt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let T=(Lt=s.closeButtonIconName)!=null?Lt:"x",Y=(Vt=s.closeButtonIconText)!=null?Vt:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ge=me(T,"20px","currentColor",1);if(ge?w.appendChild(ge):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Ne=s.closeButtonBorderWidth||"0px",le=s.closeButtonBorderColor||"transparent";w.style.border=`${Ne} solid ${le}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),B&&L){let Ne=null,le=()=>{if(Ne)return;let At=w.ownerDocument,Et=At.body;if(!Et)return;Ne=Yn(At,"div","persona-clear-chat-tooltip"),Ne.textContent=L;let Ze=Yn(At,"div");Ze.className="persona-clear-chat-tooltip-arrow",Ne.appendChild(Ze);let Qe=w.getBoundingClientRect();Ne.style.position="fixed",Ne.style.zIndex=String(Sr),Ne.style.left=`${Qe.left+Qe.width/2}px`,Ne.style.top=`${Qe.top-8}px`,Ne.style.transform="translate(-50%, -100%)",Et.appendChild(Ne)},Ie=()=>{Ne&&Ne.parentNode&&(Ne.parentNode.removeChild(Ne),Ne=null)};R.addEventListener("mouseenter",le),R.addEventListener("mouseleave",Ie),w.addEventListener("focus",le),w.addEventListener("blur",Ie),R._cleanupTooltip=()=>{Ie(),R.removeEventListener("mouseenter",le),R.removeEventListener("mouseleave",Ie),w.removeEventListener("focus",le),w.removeEventListener("blur",Ie)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:R,clearChatButton:C,clearChatButtonWrapper:S}},_r=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Er(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Sr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of r){if(m.dividerBefore){let b=document.createElement("hr");a.appendChild(b)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let M=document.createElement("span");M.textContent=m.label,v.appendChild(M),v.addEventListener("click",b=>{b.stopPropagation(),p(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function wt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function $o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=t,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function _o(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let u;p.icon?u=wt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function c(p){a=p,d()}return{element:o,setSelected:c}}function As(e){var m,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let u=me(t,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var M,b;c.style.backgroundColor=(M=d.background)!=null?M:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Er({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var ta=e=>{var n;let r=ir({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function Ep(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("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(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=Er({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var na=e=>{var S,R,w,L,B,T,Y,ge,ce;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(S=r==null?void 0:r.launcher)!=null?S:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=As({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),Ep(c,s==null?void 0:s.trailingActions,(B=s==null?void 0:s.onAction)!=null?B:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||ne()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),ne())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(T=$.borderRadius)!=null?T:"10px",c.style.padding=(Y=$.padding)!=null?Y:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Te;c.style.backgroundColor=(ne=$.background)!=null?ne:"",c.style.borderColor=(Te=$.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(ge=a.closeButtonSize)!=null?ge:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ce=a.closeButtonIconName)!=null?ce:"x",M=me(v,"20px","currentColor",2);M?m.appendChild(M):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:b,headerTitle:p,headerSubtitle:C,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Es={default:ta,minimal:na},ra=e=>{var r;return(r=Es[e])!=null?r:Es.default},ao=(e,r,t)=>{var a,i,d;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=ra(n)({config:e,showClose:(d=(i=r==null?void 0:r.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:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var io=e=>{var De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ot=(De=r==null?void 0:r.copy)==null?void 0:De.inputPlaceholder)!=null?ot:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Le=Math.min(o.scrollHeight,d);o.style.height=`${Le}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(St=r==null?void 0:r.sendButton)!=null?St:{},u=(j=p.useIcon)!=null?j:!1,f=(q=p.iconText)!=null?q:"\u2191",m=p.iconName,v=(ae=p.tooltipText)!=null?ae:"Send message",M=(_=p.showTooltip)!=null?_:!1,b=(z=p.size)!=null?z:"40px",C=p.backgroundColor,S=p.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",u?"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(w.type="submit",w.setAttribute("data-persona-composer-submit",""),u){if(w.style.width=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",S?w.style.color=S:w.style.color="var(--persona-button-primary-fg, #ffffff)",m){let Le=parseFloat(b)||24,ue=(S==null?void 0:S.trim())||"currentColor",at=me(m,Le,ue,2);at?w.appendChild(at):w.textContent=f}else w.textContent=f;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Fe=(ee=r==null?void 0:r.copy)==null?void 0:ee.sendButtonLabel)!=null?Fe:"Send",S?w.style.color=S:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let Le=h("div","persona-send-button-tooltip");Le.textContent=v,R.appendChild(Le)}R.appendChild(w);let L=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},B=L.enabled===!0,T=null,Y=null,ge=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ce=((K=L.provider)==null?void 0:K.type)==="runtype";if(B&&(ge||ce)){Y=h("div","persona-send-button-wrapper"),T=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Le=(vt=L.iconName)!=null?vt:"mic",ue=(tt=L.iconSize)!=null?tt:b,at=parseFloat(ue)||24,Be=(Lt=L.backgroundColor)!=null?Lt:C,Z=(Vt=L.iconColor)!=null?Vt:S;T.style.width=ue,T.style.height=ue,T.style.minWidth=ue,T.style.minHeight=ue,T.style.fontSize="18px",T.style.lineHeight="1",Z?T.style.color=Z:T.style.color="var(--persona-text, #111827)";let Pe=me(Le,at,Z||"currentColor",1.5);Pe?T.appendChild(Pe):T.textContent="\u{1F3A4}",Be&&(T.style.backgroundColor=Be),L.borderWidth&&(T.style.borderWidth=L.borderWidth,T.style.borderStyle="solid"),L.borderColor&&(T.style.borderColor=L.borderColor),L.paddingX&&(T.style.paddingLeft=L.paddingX,T.style.paddingRight=L.paddingX),L.paddingY&&(T.style.paddingTop=L.paddingY,T.style.paddingBottom=L.paddingY),Y.appendChild(T);let dt=(Ne=L.tooltipText)!=null?Ne:"Start voice recognition";if(((le=L.showTooltip)!=null?le:!1)&&dt){let nt=h("div","persona-send-button-tooltip");nt.textContent=dt,Y.appendChild(nt)}}let ne=(Ie=r==null?void 0:r.attachments)!=null?Ie:{},Te=ne.enabled===!0,re=null,Se=null,He=null,he=null;if(Te){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",He=h("input"),He.type="file",He.accept=((At=ne.allowedTypes)!=null?At:ar).join(","),He.multiple=((Et=ne.maxFiles)!=null?Et:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),Se=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(Ze=ne.buttonTooltipText)!=null?Ze:"Attach file");let Le=(Qe=ne.buttonIconName)!=null?Qe:"paperclip",ue=b,at=parseFloat(ue)||40,Be=Math.round(at*.6);re.style.width=ue,re.style.height=ue,re.style.minWidth=ue,re.style.minHeight=ue,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let Z=me(Le,Be,"currentColor",1.5);Z?re.appendChild(Z):re.textContent="\u{1F4CE}",re.addEventListener("click",dt=>{dt.preventDefault(),He==null||He.click()}),Se.appendChild(re);let ye=(Kt=ne.buttonTooltipText)!=null?Kt:"Attach file",Pe=h("div","persona-send-button-tooltip");Pe.textContent=ye,Se.appendChild(Pe)}s.addEventListener("click",Le=>{Le.target!==w&&Le.target!==R&&Le.target!==T&&Le.target!==Y&&Le.target!==re&&Le.target!==Se&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),He&&s.append(He),s.append(o);let Me=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),ke=h("div","persona-flex persona-items-center persona-gap-2");Se&&ke.append(Se);let oe=h("div","persona-flex persona-items-center persona-gap-1");Y&&oe.append(Y),oe.append(R),Me.append(ke,oe),s.append(Me);let be=(Gt=r==null?void 0:r.statusIndicator)!=null?Gt:{},$e=be.align==="left"?"persona-text-left":be.align==="center"?"persona-text-center":"persona-text-right",pe=h("div",`persona-mt-2 ${$e} persona-text-xs persona-text-persona-muted`);pe.setAttribute("data-persona-composer-status","");let de=(Zt=be.visible)!=null?Zt:!0;pe.style.display=de?"":"none";let se=(O=be.idleText)!=null?O:"Online";if(be.idleLink){let Le=h("a");Le.href=be.idleLink,Le.target="_blank",Le.rel="noopener noreferrer",Le.textContent=se,Le.style.color="inherit",Le.style.textDecoration="none",pe.appendChild(Le)}else pe.textContent=se;return t.append(n,s,pe),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:T,micButtonWrapper:Y,statusText:pe,attachmentButton:re,attachmentButtonWrapper:Se,attachmentInput:He,attachmentPreviewsContainer:he,actionsRow:Me,leftActions:ke,rightActions:oe}};var _c=e=>{var c,p,u,f,m,v,M,b,C;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Ut(e)){let S=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(R),{wrapper:S,panel:R}}if(!r){let S=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),R=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(u=e==null?void 0:e.launcher)==null?void 0:u.width)!=null?f:"100%";return S.style.width=w,R.style.width="100%",S.appendChild(R),{wrapper:S,panel:R}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&zn[n.position]?zn[n.position]:zn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:yn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?C:e==null?void 0:e.launcherWidth,d=i!=null?i:Mn;return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},jc=(e,r=!0)=>{var b,C,S,R,w,L,B,T,Y;let t=h("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");t.setAttribute("data-persona-theme-zone","container");let n=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?ao(e,n,{showClose:r}):ir({config:e,showClose:r}),a=h("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",a.setAttribute("data-persona-theme-zone","messages");let i=Ut(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(R=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?R:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",d.append(c,p);let u=h("div","persona-flex persona-flex-col persona-gap-3"),f=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),d.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,u);let v=io({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?_r(t,o,e):(o.header.style.display="none",_r(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:u,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var Tp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Mp=320,kp=320,Lp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Ip=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var u;let c=h("img");c.alt=((u=i.alt)==null?void 0:u.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=`${Mp}px`,c.style.maxHeight=`${kp}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 p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Tp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},jr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},oa=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:jr};if(r){let s=r(n);if(s!==null)return s}return jr()},Pp=(e,r)=>{let t=h("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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},zc=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Wp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-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("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-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("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-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},sa=(e,r,t)=>{var m,v,M,b,C,S;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(b=r.visibility)!=null?b:"hover",i=(C=r.align)!=null?C:"right",d=(S=r.layout)!=null?S:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(R,w,L)=>{let B=wt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",L),B};return n&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},lo=(e,r,t,n,s,o)=>{var ce,$,ne,Te,re,Se,He;let a=t!=null?t:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,c=a.timestamp,p=($=d==null?void 0:d.show)!=null?$:!1,u=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Te=d==null?void 0:d.position)!=null?Te:"left",m=(re=c==null?void 0:c.position)!=null?re:"below",v=Wp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Lp(e),C=(He=(Se=e.content)==null?void 0:Se.trim())!=null?He:"",R=b.length>0&&C===ls,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),B=null;if(R?(B=document.createElement("div"),B.innerHTML=L,B.style.display="none",w.appendChild(B)):w.innerHTML=L,u&&m==="inline"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(b.length>0){let he=Ip(b,!R&&!!C,()=>{R&&B&&(B.style.display="")});he?M.appendChild(he):R&&B&&(B.style.display="")}if(M.appendChild(w),u&&m==="below"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-mt-1"),M.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=oa("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&M.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=sa(e,n,s);M.appendChild(he)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=Pp(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,ge):Y.append(ge,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Uc=(e,r,t,n,s,o)=>{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}):lo(e,r,t,n,s,o)};var co=new Set,Vc=(e,r)=>{let t=co.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},aa=e=>{let r=e.reasoning,t=h("div",["persona-message-bubble","persona-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),!r)return t;let n=co.has(e.id),s=h("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");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=mc(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),p=me(n?"chevron-up":"chevron-down",16,"currentColor",2);p?d.appendChild(p):d.textContent=n?"Hide":"Show";let u=h("div","persona-flex persona-items-center persona-ml-auto");u.append(d),s.append(o,u);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let C=me(n?"chevron-up":"chevron-down",16,"currentColor",2);C?d.appendChild(C):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var po=new Set,qc=(e,r,t)=>{var c;let n=po.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",u=me(n?"chevron-up":"chevron-down",16,p,2);u?d.appendChild(u):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},ia=(e,r)=>{var M;let t=e.toolCall,n=(M=r==null?void 0:r.toolCall)!=null?M:{},s=h("div",["persona-message-bubble","persona-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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=po.has(e.id),a=h("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",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=fc(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),p=n.toggleTextColor||n.headerTextColor||"currentColor",u=me(o?"chevron-up":"chevron-down",16,p,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("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=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Arguments";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.args),b.append(C,S),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Activity";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=t.chunks.join(`
|
|
16
|
-
`),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Result";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.result),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",C=me(o?"chevron-up":"chevron-down",16,b,2);C?c.appendChild(C):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var la=(e,r)=>{var M,b,C,S,R,w,L,B,T,Y,ge,ce;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("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)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",p=me(d,20,c,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",f.appendChild(m),!s){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}u.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,u.appendChild(v),t.parameters){let $=h("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");n!=null&&n.parameterBackgroundColor&&($.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&($.style.color=n.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=Lo(t.parameters),u.appendChild($)}if(s){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let ne=h("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");ne.type="button",ne.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ne.setAttribute("data-approval-action","approve");let Te=me("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Te&&(Te.style.marginRight="4px",ne.appendChild(Te));let re=document.createTextNode((B=n==null?void 0:n.approveLabel)!=null?B:"Approve");ne.appendChild(re);let Se=h("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");Se.type="button",Se.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Se.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",Se.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Se.setAttribute("data-approval-action","deny");let He=me("shield-x",14,(ge=n==null?void 0:n.denyButtonTextColor)!=null?ge:"var(--persona-feedback-error, #dc2626)",2);He&&(He.style.marginRight="4px",Se.appendChild(He));let he=document.createTextNode((ce=n==null?void 0:n.denyLabel)!=null?ce:"Deny");Se.appendChild(he),$.append(ne,Se),u.appendChild($)}return a.append(i,u),o.appendChild(a),o};var Jc=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=s?s.isStreaming():!1,f=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'}};n.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var jo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function uo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Rp={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, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},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)"}},Hp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bp=["flowName","stepName","reasoningText","text","name","tool","toolName"],Dp=100;function Fp(e,r){let t={...Rp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Hp}function Np(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Op(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function $p(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function _p(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function jp(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function zp(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function ca(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");uo(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(u()),c;function u(){var ne,Te;let m=h("div",""),v=h("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");v.setAttribute("data-event-id",e.id);let M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&M.appendChild(b);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(ne=n.timestampFormat)!=null?ne:"relative";C.textContent=S==="relative"?Np(e.timestamp,t):Op(e.timestamp);let R=null;n.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(r+1));let w=Fp(e.type,n.badgeColors),L=h("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");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let B=(Te=n.descriptionFields)!=null?Te:Bp,T=$p(e.payload,B),Y=null;T&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=T);let ge=h("div","persona-flex-1 persona-min-w-0"),ce=h("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"),$=me("clipboard","12px","currentColor",1.5);return $&&ce.appendChild($),ce.addEventListener("click",async re=>{re.stopPropagation(),await _p(jp(e)),ce.innerHTML="";let Se=me("check","12px","currentColor",1.5);Se&&ce.appendChild(Se),setTimeout(()=>{ce.innerHTML="";let He=me("clipboard","12px","currentColor",1.5);He&&ce.appendChild(He)},1500)}),v.appendChild(M),v.appendChild(C),R&&v.appendChild(R),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(ge),v.appendChild(ce),m.appendChild(v),d&&m.appendChild(zp(e,a,i)),m}}function Yc(e){var m,v,M,b,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(C=(b=s==null?void 0:s.features)==null?void 0:b.eventStream)!=null?C:{},u=o.find(S=>S.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&s){let S=u.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return f();function f(){let S=p.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");uo(R,S==null?void 0:S.panel);let w=[],L="",B="",T=null,Y=[],ge={},ce=0,$=vs(),ne=0,Te=0,re=!1,Se=null,He=!1,he=0,Me=new Set,ke=new Map,oe="",be="",$e=null,pe,de,se,De,ot;function St(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ye=h("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");uo(ye,S==null?void 0:S.headerBar);let Pe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",pe=h("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"),pe.textContent="0";let dt=h("div","persona-flex-1");de=h("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 Ot=h("option","");Ot.value="",Ot.textContent="All events",de.appendChild(Ot),se=h("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"),se.type="button",se.title="Copy All";let $t=me("clipboard-copy","12px","currentColor",1.5);$t&&se.appendChild($t);let it=h("span","persona-text-xs");it.textContent="Copy All",se.appendChild(it),ye.appendChild(Pe),ye.appendChild(pe),ye.appendChild(dt),ye.appendChild(de),ye.appendChild(se);let qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");uo(qe,S==null?void 0:S.searchBar);let lt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),_e=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");lt&&_e.appendChild(lt),De=h("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"),uo(De,S==null?void 0:S.searchInput),De.type="text",De.placeholder="Search event payloads...",ot=h("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"),ot.type="button",ot.style.display="none";let _t=me("x","12px","currentColor",2);return _t&&ot.appendChild(_t),qe.appendChild(_e),qe.appendChild(De),qe.appendChild(ot),Z.appendChild(ye),Z.appendChild(qe),Z}let j,q=o.find(Z=>Z.renderEventStreamToolbar);if(q!=null&&q.renderEventStreamToolbar&&s){let Z=q.renderEventStreamToolbar({config:s,defaultRenderer:()=>St(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{L=ye,Vt(),Ie()},onSearchChange:ye=>{B=ye,Vt(),Ie()}});j=Z!=null?Z:St()}else j=St();let ae=h("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");ae.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let ee=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");uo(ee,S==null?void 0:S.scrollIndicator),ee.style.display="none",ee.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Fe=me(d,"14px","currentColor",2);Fe&&ee.appendChild(Fe);let J=h("span","");J.textContent=c,ee.appendChild(J);let K=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");K.style.display="none",_.appendChild(z),_.appendChild(K),_.appendChild(ee),R.setAttribute("tabindex","0"),R.appendChild(j),R.appendChild(ae),R.appendChild(_);function vt(){let Z=r.getAll(),ye={};for(let it of Z)ye[it.type]=(ye[it.type]||0)+1;let Pe=Object.keys(ye).sort(),dt=Pe.length!==Y.length||!Pe.every((it,qe)=>it===Y[qe]),Ot=!dt&&Pe.some(it=>ye[it]!==ge[it]),nt=Z.length!==Object.values(ge).reduce((it,qe)=>it+qe,0);if(!dt&&!Ot&&!nt||(Y=Pe,ge=ye,!de))return;let $t=de.value;if(de.options[0].textContent="All events",dt){for(;de.options.length>1;)de.remove(1);for(let it of Pe){let qe=h("option","");qe.value=it,qe.textContent=`${it} (${ye[it]||0})`,de.appendChild(qe)}$t&&Pe.includes($t)?de.value=$t:$t&&(de.value="",L="")}else for(let it=1;it<de.options.length;it++){let qe=de.options[it];qe.textContent=`${qe.value} (${ye[qe.value]||0})`}}function tt(){let Z=r.getAll();if(L&&(Z=Z.filter(ye=>ye.type===L)),B){let ye=B.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(ye)||Pe.payload.toLowerCase().includes(ye))}return Z}function Lt(){return L!==""||B!==""}function Vt(){ce=0,ne=0,$.resume(),ee.style.display="none"}function Ne(Z){Me.has(Z)?Me.delete(Z):Me.add(Z),$e=Z;let ye=z.scrollTop,Pe=$.isFollowing();He=!0,$.pause(),Ie(),z.scrollTop=ye,Pe&&$.resume(),He=!1}function le(){return Fo(z,50)}function Ie(){Te=Date.now(),re=!1,vt();let Z=r.getEvictedCount();Z>0?(ae.textContent=`${Z.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",w=tt();let ye=w.length,Pe=r.getSize()>0;pe&&(pe.textContent=String(r.getSize())),ye===0&&Pe&&Lt()?(K.textContent=B?`No events matching '${B}'`:"No events matching filter",K.style.display="",z.style.display="none"):(K.style.display="none",z.style.display=""),se&&(se.title=Lt()?`Copy Filtered (${ye})`:"Copy All"),i&&!$.isFollowing()&&ye>ce&&(ne+=ye-ce,J.textContent=c?`${c}${ne>0?` (${ne})`:""}`:"",ee.style.display=""),ce=ye;let dt=r.getAll(),Ot=dt.length>0?dt[0].timestamp:0,nt=new Set(w.map(qe=>qe.id));for(let qe of Me)nt.has(qe)||Me.delete(qe);let $t=L!==oe||B!==be,it=ke.size===0&&w.length>0;if($t||it||w.length===0){z.innerHTML="",ke.clear();let qe=document.createDocumentFragment();for(let lt=0;lt<w.length;lt++){let _e=ca(w[lt],lt,Ot,p,Me,Ne,o,s);ke.set(w[lt].id,_e),qe.appendChild(_e)}z.appendChild(qe),oe=L,be=B,$e=null}else{if($e!==null){let lt=ke.get($e);if(lt&<.parentNode===z){let _e=w.findIndex(_t=>_t.id===$e);if(_e>=0){let _t=ca(w[_e],_e,Ot,p,Me,Ne,o,s);z.insertBefore(_t,lt),lt.remove(),ke.set($e,_t)}}$e=null}let qe=new Set(w.map(lt=>lt.id));for(let[lt,_e]of ke)qe.has(lt)||(_e.remove(),ke.delete(lt));for(let lt=0;lt<w.length;lt++){let _e=w[lt];if(!ke.has(_e.id)){let _t=ca(_e,lt,Ot,p,Me,Ne,o,s);ke.set(_e.id,_t),z.appendChild(_t)}}}$.isFollowing()&&(z.scrollTop=z.scrollHeight)}function At(){if(Date.now()-Te>=Dp){Se!==null&&(cancelAnimationFrame(Se),Se=null),Ie();return}re||(re=!0,Se=requestAnimationFrame(()=>{Se=null,Ie()}))}let Et=(Z,ye)=>{if(!se)return;se.innerHTML="";let Pe=me(Z,"12px","currentColor",1.5);Pe&&se.appendChild(Pe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",se.appendChild(dt),setTimeout(()=>{se.innerHTML="";let Ot=me("clipboard-copy","12px","currentColor",1.5);Ot&&se.appendChild(Ot);let nt=h("span","persona-text-xs");nt.textContent="Copy All",se.appendChild(nt),se.disabled=!1},ye)},Ze=async()=>{if(se){se.disabled=!0;try{let Z;Lt()?Z=w:t?(Z=await t(),Z.length===0&&(Z=r.getAll())):Z=r.getAll();let ye=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Et("check",1500)}catch{Et("x",1500)}}},Qe=()=>{de&&(L=de.value,Vt(),Ie())},Kt=()=>{!De||!ot||(ot.style.display=De.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{B=De.value,Vt(),Ie()},150))},Gt=()=>{!De||!ot||(De.value="",B="",ot.style.display="none",T&&clearTimeout(T),Vt(),Ie())},Zt=()=>{if(He)return;let Z=z.scrollTop,{action:ye,nextLastScrollTop:Pe}=Cs({following:$.isFollowing(),currentScrollTop:Z,lastScrollTop:he,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Pe,ye==="resume"?($.resume(),ne=0,ee.style.display="none"):ye==="pause"&&($.pause(),i&&(J.textContent=c,ee.style.display=""))},O=Z=>{let ye=ws({following:$.isFollowing(),deltaY:Z.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});ye==="pause"?($.pause(),i&&(J.textContent=c,ee.style.display="")):ye==="resume"&&($.resume(),ne=0,ee.style.display="none")},Le=()=>{i&&(z.scrollTop=z.scrollHeight,$.resume(),ne=0,ee.style.display="none")},ue=Z=>{let ye=Z.target;if(!ye||ye.closest("button"))return;let Pe=ye.closest("[data-event-id]");if(!Pe)return;let dt=Pe.getAttribute("data-event-id");dt&&Ne(dt)},at=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),De==null||De.focus(),De==null||De.select();return}Z.key==="Escape"&&(De&&document.activeElement===De?(Gt(),De.blur(),R.focus()):n&&n())};se&&se.addEventListener("click",Ze),de&&de.addEventListener("change",Qe),De&&De.addEventListener("input",Kt),ot&&ot.addEventListener("click",Gt),z.addEventListener("scroll",Zt),z.addEventListener("wheel",O,{passive:!0}),z.addEventListener("click",ue),ee.addEventListener("click",Le),R.addEventListener("keydown",at);function Be(){T&&clearTimeout(T),Se!==null&&(cancelAnimationFrame(Se),Se=null),re=!1,ke.clear(),se&&se.removeEventListener("click",Ze),de&&de.removeEventListener("change",Qe),De&&De.removeEventListener("input",Kt),ot&&ot.removeEventListener("click",Gt),z.removeEventListener("scroll",Zt),z.removeEventListener("wheel",O),z.removeEventListener("click",ue),ee.removeEventListener("click",Le),R.removeEventListener("keydown",at)}return{element:R,update:At,destroy:Be}}}function Gc(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.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",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(c.append(p,u),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var Xc=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>Gc(e,r)});if(p)return p}return Gc(e,r)};var da=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lr=new da;lr.register("PersonaArtifactCard",Xc);function Up(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Kc(e,r){var se,De,ot,St;let t=(De=(se=e.features)==null?void 0:se.artifacts)==null?void 0:De.layout,s=((ot=t==null?void 0:t.toolbarPreset)!=null?ot:"default")==="document",o=(St=t==null?void 0:t.panePadding)==null?void 0:St.trim(),a=e.markdown?Br(e.markdown):null,i=no(e.sanitize),d=j=>{let q=a?a(j):to(j);return i?i(q):q},c=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let u=h("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");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.classList.add("persona-artifact-pane-document");let f=h("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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?wt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):wt({icon:"eye",label:"Rendered view"}),S=s?wt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):wt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,B=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(L&&B&&B.length>0),Y=null,ge,ce=null,$=null;if(s&&(w||L)&&!T){if(ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=me("chevron-down",14,"currentColor",2);j&&ge.appendChild(j)}}else s&&T?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ce=wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),Y.append(ge,ce)):s?ge=wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ge=wt({icon:"copy",label:"Copy"});let ne=s?wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):wt({icon:"refresh-cw",label:"Refresh"}),Te=s?wt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):wt({icon:"x",label:"Close"}),re=()=>{var z,ee,Fe;let j=(z=oe.find(J=>J.id===be))!=null?z:oe[oe.length-1],q=(ee=j==null?void 0:j.id)!=null?ee:null,ae=(j==null?void 0:j.artifactType)==="markdown"&&(Fe=j.markdown)!=null?Fe:"",_=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:ae,jsonPayload:_,id:q}},Se=async()=>{var z;let{markdown:j,jsonPayload:q}=re(),ae=(z=oe.find(ee=>ee.id===be))!=null?z:oe[oe.length-1],_=(ae==null?void 0:ae.artifactType)==="markdown"?j:ae?q:"";try{await navigator.clipboard.writeText(_)}catch{}};if(ge.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&T){let{markdown:q,jsonPayload:ae,id:_}=re();try{await j({actionId:"primary",artifactId:_,markdown:q,jsonPayload:ae})}catch{}return}await Se()}),ce&&(B!=null&&B.length)){let j=()=>{var ae;return(ae=u.closest("[data-persona-root]"))!=null?ae:document.body},q=()=>{$=Er({items:B.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:_,jsonPayload:z,id:ee}=re(),Fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Fe?await Fe({actionId:ae,artifactId:ee,markdown:_,jsonPayload:z}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(_):ae==="json"||ae==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(_||z)}catch{}},anchor:Y!=null?Y:ce,position:"bottom-right",portal:j()})};u.isConnected?q():requestAnimationFrame(q),ce.addEventListener("click",ae=>{ae.stopPropagation(),$==null||$.toggle()})}ne.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}pe()}),Te.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let He=()=>{s&&(C.setAttribute("aria-pressed",M==="rendered"?"true":"false"),S.setAttribute("aria-pressed",M==="source"?"true":"false"))};C.addEventListener("click",()=>{M="rendered",He(),pe()}),S.addEventListener("click",()=>{M="source",He(),pe()});let he=h("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");s?(f.replaceChildren(),b.append(C,S),Y?R.append(Y,ne,Te):R.append(ge,ne,Te),f.append(b,he,R),He()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Me=h("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"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Me.style.paddingLeft=o,Me.style.paddingRight=o,ke.style.padding=o),u.appendChild(f),u.appendChild(Me),u.appendChild(ke);let oe=[],be=null,$e=!1,pe=()=>{var _,z,ee,Fe;let j=s&&oe.length<=1;Me.classList.toggle("persona-hidden",j),Me.replaceChildren();for(let J of oe){let K=h("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");K.type="button",K.textContent=J.title||J.id.slice(0,8),J.id===be&&K.classList.add("persona-bg-persona-container","persona-border-persona-border"),K.addEventListener("click",()=>r.onSelect(J.id)),Me.appendChild(K)}ke.replaceChildren();let q=be&&oe.find(J=>J.id===be)||oe[oe.length-1];if(!q)return;if(s){let J=q.artifactType==="markdown"?"MD":(_=q.component)!=null?_:"Component",vt=(q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${vt} \xB7 ${J}`}else m.textContent="Artifacts";if(q.artifactType==="markdown"){if(s&&M==="source"){let K=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");K.textContent=(z=q.markdown)!=null?z:"",ke.appendChild(K);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=d((ee=q.markdown)!=null?ee:""),ke.appendChild(J);return}let ae=q.component?lr.get(q.component):void 0;if(ae){let K={message:{id:q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let vt=ae((Fe=q.props)!=null?Fe:{},K);if(vt){ke.appendChild(vt);return}}catch{}}ke.appendChild(Up(q))},de=()=>{var q;let j=oe.length>0;if(u.classList.toggle("persona-hidden",!j),c){let ae=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,z=((q=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&z&&$e?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(j){var q,ae,_;oe=j.artifacts,be=(_=(ae=j.selectedId)!=null?ae:(q=j.artifacts[j.artifacts.length-1])==null?void 0:q.id)!=null?_:null,oe.length>0&&($e=!0),pe(),de()},setMobileOpen(j){$e=j,!j&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}function Bn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Zc(e,r){var o,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"),!Bn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Vp(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 Ts(e,r){var d,c,p,u,f,m,v,M,b,C;if(!Bn(r)){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"),Vp(e),Zc(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=t==null?void 0:t.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Zc(e,r)}var Qc=["panel","seamless"];function Ms(e,r){var i,d,c,p,u,f;for(let m of Qc)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"),!Bn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Qc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=t==null?void 0:t.paneShadow)==null?void 0:u.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=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ed(e,r){var t,n,s;return!r||!Bn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function qp(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Jp(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function Yp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Gp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function td(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function nd(e,r,t,n,s,o){let a=qp(s,200),i=Gp(r,t,n,200);i=Math.max(a,i);let d=Jp(o);return d!==null&&(i=Math.min(i,d)),Yp(e,a,i)}var rd={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"}},pa=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=rd[a])!=null?M:rd.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var B,T;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${a}-${C.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=C.label,S.appendChild(R);let w=(B=C.type)!=null?B:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.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",L.id=`${r.id}-${a}-${C.name}`,L.name=C.name,L.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(L.required=!0),S.appendChild(L),p.appendChild(S)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("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=(b=i.submitLabel)!=null?b:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async C=>{var L,B;C.preventDefault();let S=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(p),w={};R.forEach((T,Y)=>{w[Y]=T}),w.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let T=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let Y=await T.json();f.textContent=(B=Y.message)!=null?B:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var ua=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Uo=new ua;var od=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Xp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Kp=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Vo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Xp(e),t=Kp(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ga=e=>typeof e=="string"?e:e==null?"":String(e),zr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ga(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ga(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ga(t.text)}}},sd=e=>Array.isArray(e)?e.map(r=>String(r)):[],qo=e=>{let r=new Set(sd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(sd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.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,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Zp=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Qp=e=>e.map(r=>({...r,streaming:!1})),ks=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Zp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Qp(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var go=require("partial-json");function eu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function tu(e,r){if(!eu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function Ls(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,go.parse)(t,go.STR|go.OBJ),o=tu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function ad(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Is(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=lr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function id(){let e=Ls();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ps(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Ws(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var nu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rs(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=nu}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,m.appendChild(M),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let B=1;B<=5;B++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${c[B-1]}`),T.title=c[B-1],T.dataset.rating=String(B),T.innerHTML=`
|
|
15
|
+
`,t.addEventListener("click",r);let n=o=>{var R,w,L,B,T,Y,ge,ce,$,ne,Te,re,Se,He;let a=(R=o.launcher)!=null?R:{},i=Ut(o),d=t.querySelector("[data-role='launcher-title']");if(d){let he=(w=a.title)!=null?w:"Chat Assistant";d.textContent=he,d.setAttribute("title",he)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let he=(L=a.subtitle)!=null?L:"Get answers fast";c.textContent=he,c.setAttribute("title",he)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=t.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let he=(B=a.agentIconSize)!=null?B:"40px";if(u.style.height=he,u.style.width=he,u.innerHTML="",a.agentIconName){let Me=parseFloat(he)||24,ke=me(a.agentIconName,Me*.6,"var(--persona-text-inverse, #ffffff)",2);ke?(u.appendChild(ke),u.style.display=""):(u.textContent=(T=a.agentIconText)!=null?T:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(Y=a.agentIconText)!=null?Y:"\u{1F4AC}",u.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(ge=a.agentIconSize)!=null?ge:"40px";f.style.height=he,f.style.width=he,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let he=(ce=a.callToActionIconSize)!=null?ce:"32px";m.style.height=he,m.style.width=he,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Me=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Me=(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 ke=parseFloat(he)||24,oe=Math.max(ke-Me,8),be=me(a.callToActionIconName,oe,"currentColor",2);be?m.appendChild(be):m.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&zn[a.position]?zn[a.position]:zn["bottom-right"],M="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",b="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?b:`${M} ${v}`,i||(t.style.zIndex=String((Te=a.zIndex)!=null?Te:yn));let C="1px solid var(--persona-border, #e5e7eb)",S="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(re=a.border)!=null?re:C,t.style.boxShadow=(Se=a.shadow)!=null?Se:S,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(He=a.collapsedMaxWidth)!=null?He:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},ir=e=>{var ce,$,ne,Te,re,Se,He,he,Me,ke,oe,be,$e,pe,de,se,De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt;let{config:r,showClose:t=!0}=e,n=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");n.setAttribute("data-persona-theme-zone","header"),n.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",n.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",n.style.boxShadow="var(--persona-header-shadow, none)",n.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(ce=r==null?void 0:r.launcher)!=null?ce:{},o=($=s.headerIconSize)!=null?$:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",d=(re=s.headerIconHidden)!=null?re:!1,c=s.headerIconName,p=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(p.style.height=o,p.style.width=o,p.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",p.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let Ne=parseFloat(o)||24,le=me(c,Ne*.6,"currentColor",1);le?p.replaceChildren(le):p.textContent=(He=(Se=r==null?void 0:r.launcher)==null?void 0:Se.agentIconText)!=null?He:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let Ne=h("img");Ne.src=r.launcher.iconUrl,Ne.alt="",Ne.className="persona-rounded-xl persona-object-cover",Ne.style.height=o,Ne.style.width=o,p.replaceChildren(Ne)}else p.textContent=(ke=(Me=r==null?void 0:r.launcher)==null?void 0:Me.agentIconText)!=null?ke:"\u{1F4AC}";let u=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(be=(oe=r==null?void 0:r.launcher)==null?void 0:oe.title)!=null?be:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(pe=($e=r==null?void 0:r.launcher)==null?void 0:$e.subtitle)!=null?pe:"Here to help you get answers fast",u.append(f,m),d?n.append(u):n.append(p,u);let v=(de=s.clearChat)!=null?de:{},M=(se=v.enabled)!=null?se:!0,b=(De=v.placement)!=null?De:"inline",C=null,S=null;if(M){let Ne=(ot=v.size)!=null?ot:"32px",le=(St=v.iconName)!=null?St:"refresh-cw",Ie=(j=v.iconColor)!=null?j:"",At=(q=v.backgroundColor)!=null?q:"",Et=(ae=v.borderWidth)!=null?ae:"",Ze=(_=v.borderColor)!=null?_:"",Qe=(z=v.borderRadius)!=null?z:"",Kt=(ee=v.paddingX)!=null?ee:"",Gt=(Fe=v.paddingY)!=null?Fe:"",Zt=(J=v.tooltipText)!=null?J:"Clear chat",O=(K=v.showTooltip)!=null?K:!0;S=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(S.style.right="48px"),C=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),C.style.height=Ne,C.style.width=Ne,C.type="button",C.setAttribute("aria-label",Zt),C.style.color=Ie||bn.actionIconColor;let Le=me(le,"20px","currentColor",1);if(Le&&C.appendChild(Le),At&&(C.style.backgroundColor=At,C.classList.remove("hover:persona-bg-gray-100")),Et||Ze){let ue=Et||"0px",at=Ze||"transparent";C.style.border=`${ue} solid ${at}`,C.classList.remove("persona-border-none")}if(Qe&&(C.style.borderRadius=Qe,C.classList.remove("persona-rounded-full")),Kt?(C.style.paddingLeft=Kt,C.style.paddingRight=Kt):(C.style.paddingLeft="",C.style.paddingRight=""),Gt?(C.style.paddingTop=Gt,C.style.paddingBottom=Gt):(C.style.paddingTop="",C.style.paddingBottom=""),S.appendChild(C),O&&Zt&&C&&S){let ue=null,at=()=>{if(ue||!C)return;let Z=C.ownerDocument,ye=Z.body;if(!ye)return;ue=Yn(Z,"div","persona-clear-chat-tooltip"),ue.textContent=Zt;let Pe=Yn(Z,"div");Pe.className="persona-clear-chat-tooltip-arrow",ue.appendChild(Pe);let dt=C.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(Sr),ue.style.left=`${dt.left+dt.width/2}px`,ue.style.top=`${dt.top-8}px`,ue.style.transform="translate(-50%, -100%)",ye.appendChild(ue)},Be=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};S.addEventListener("mouseenter",at),S.addEventListener("mouseleave",Be),C.addEventListener("focus",at),C.addEventListener("blur",Be),S._cleanupTooltip=()=>{Be(),S&&(S.removeEventListener("mouseenter",at),S.removeEventListener("mouseleave",Be)),C&&(C.removeEventListener("focus",at),C.removeEventListener("blur",Be))}}b==="inline"&&n.appendChild(S)}let R=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":M&&b==="inline"?"":"persona-ml-auto"),w=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");w.style.height=a,w.style.width=a,w.type="button";let L=(vt=s.closeButtonTooltipText)!=null?vt:"Close chat",B=(tt=s.closeButtonShowTooltip)!=null?tt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let T=(Lt=s.closeButtonIconName)!=null?Lt:"x",Y=(Vt=s.closeButtonIconText)!=null?Vt:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ge=me(T,"20px","currentColor",1);if(ge?w.appendChild(ge):w.textContent=Y,s.closeButtonBackgroundColor?(w.style.backgroundColor=s.closeButtonBackgroundColor,w.classList.remove("hover:persona-bg-gray-100")):(w.style.backgroundColor="",w.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Ne=s.closeButtonBorderWidth||"0px",le=s.closeButtonBorderColor||"transparent";w.style.border=`${Ne} solid ${le}`,w.classList.remove("persona-border-none")}else w.style.border="",w.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(w.style.borderRadius=s.closeButtonBorderRadius,w.classList.remove("persona-rounded-full")):(w.style.borderRadius="",w.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(w.style.paddingLeft=s.closeButtonPaddingX,w.style.paddingRight=s.closeButtonPaddingX):(w.style.paddingLeft="",w.style.paddingRight=""),s.closeButtonPaddingY?(w.style.paddingTop=s.closeButtonPaddingY,w.style.paddingBottom=s.closeButtonPaddingY):(w.style.paddingTop="",w.style.paddingBottom=""),R.appendChild(w),B&&L){let Ne=null,le=()=>{if(Ne)return;let At=w.ownerDocument,Et=At.body;if(!Et)return;Ne=Yn(At,"div","persona-clear-chat-tooltip"),Ne.textContent=L;let Ze=Yn(At,"div");Ze.className="persona-clear-chat-tooltip-arrow",Ne.appendChild(Ze);let Qe=w.getBoundingClientRect();Ne.style.position="fixed",Ne.style.zIndex=String(Sr),Ne.style.left=`${Qe.left+Qe.width/2}px`,Ne.style.top=`${Qe.top-8}px`,Ne.style.transform="translate(-50%, -100%)",Et.appendChild(Ne)},Ie=()=>{Ne&&Ne.parentNode&&(Ne.parentNode.removeChild(Ne),Ne=null)};R.addEventListener("mouseenter",le),R.addEventListener("mouseleave",Ie),w.addEventListener("focus",le),w.addEventListener("blur",Ie),R._cleanupTooltip=()=>{Ie(),R.removeEventListener("mouseenter",le),R.removeEventListener("mouseleave",Ie),w.removeEventListener("focus",le),w.removeEventListener("blur",Ie)}}return i!=="top-right"&&n.appendChild(R),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:R,clearChatButton:C,clearChatButtonWrapper:S}},_r=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function Er(e){let{items:r,onSelect:t,anchor:n,position:s="bottom-left",portal:o}=e,a=h("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),o?(a.style.position="fixed",a.style.zIndex=String(Sr)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of r){if(m.dividerBefore){let b=document.createElement("hr");a.appendChild(b)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let M=document.createElement("span");M.textContent=m.label,v.appendChild(M),v.addEventListener("click",b=>{b.stopPropagation(),p(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function wt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function $o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let u=h("span");if(u.textContent=t,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))p.setAttribute(f,m);return p}function _o(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let u;p.icon?u=wt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),n(p.id)}}):(u=h("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),n(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),o.appendChild(u)}function c(p){a=p,d()}return{element:o,setSelected:c}}function As(e){var m,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let p=h("span","persona-combo-btn-label");p.textContent=r,c.appendChild(p);let u=me(t,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var M,b;c.style.backgroundColor=(M=d.background)!=null?M:"",c.style.borderColor=(b=d.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Er({items:n,onSelect:M=>{c.setAttribute("aria-expanded","false"),s(M)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",M=>{M.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",M=>{(M.key==="Enter"||M.key===" ")&&(M.preventDefault(),c.click())}),{element:c,setLabel:M=>{p.textContent=M,c.setAttribute("aria-label",M)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let M=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",M?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var ta=e=>{var n;let r=ir({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(n=e.layoutHeaderConfig)==null?void 0:n.onTitleClick;if(t){let s=r.headerTitle.parentElement;s&&(s.style.cursor="pointer",s.setAttribute("role","button"),s.setAttribute("tabindex","0"),s.addEventListener("click",()=>t()),s.addEventListener("keydown",o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),t())}))}return r};function Ep(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("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(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=Er({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var na=e=>{var S,R,w,L,B,T,Y,ge,ce;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(S=r==null?void 0:r.launcher)!=null?S:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,p;if(d)c=As({label:(R=a.title)!=null?R:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,p=(w=c.querySelector(".persona-combo-btn-label"))!=null?w:c;else{if(c=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=h("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=bn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),Ep(c,s==null?void 0:s.trailingActions,(B=s==null?void 0:s.onAction)!=null?B:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||ne()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),ne())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(T=$.borderRadius)!=null?T:"10px",c.style.padding=(Y=$.padding)!=null?Y:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Te;c.style.backgroundColor=(ne=$.background)!=null?ne:"",c.style.borderColor=(Te=$.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(ge=a.closeButtonSize)!=null?ge:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=u,m.style.width=u,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ce=a.closeButtonIconName)!=null?ce:"x",M=me(v,"20px","currentColor",2);M?m.appendChild(M):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let C=h("span");return C.style.display="none",{header:i,iconHolder:b,headerTitle:p,headerSubtitle:C,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Es={default:ta,minimal:na},ra=e=>{var r;return(r=Es[e])!=null?r:Es.default},ao=(e,r,t)=>{var a,i,d;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),p=h("div");p.style.display="none";let u=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=ra(n)({config:e,showClose:(d=(i=r==null?void 0:r.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:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var io=e=>{var De,ot,St,j,q,ae,_,z,ee,Fe,J,K,vt,tt,Lt,Vt,Ne,le,Ie,At,Et,Ze,Qe,Kt,Gt,Zt,O;let{config:r}=e,t=h("div","persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4");t.setAttribute("data-persona-theme-zone","composer");let n=h("div","persona-mb-3 persona-flex persona-flex-wrap persona-gap-2"),s=h("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");s.setAttribute("data-persona-composer-form",""),s.style.outline="none";let o=h("textarea");o.setAttribute("data-persona-composer-input",""),o.placeholder=(ot=(De=r==null?void 0:r.copy)==null?void 0:De.inputPlaceholder)!=null?ot:"Type your message\u2026",o.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",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Le=Math.min(o.scrollHeight,d);o.style.height=`${Le}px`};o.addEventListener("input",c),o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.addEventListener("focus",()=>{o.style.border="none",o.style.outline="none",o.style.borderWidth="0",o.style.borderStyle="none",o.style.borderColor="transparent",o.style.boxShadow="none"}),o.addEventListener("blur",()=>{o.style.border="none",o.style.outline="none"});let p=(St=r==null?void 0:r.sendButton)!=null?St:{},u=(j=p.useIcon)!=null?j:!1,f=(q=p.iconText)!=null?q:"\u2191",m=p.iconName,v=(ae=p.tooltipText)!=null?ae:"Send message",M=(_=p.showTooltip)!=null?_:!1,b=(z=p.size)!=null?z:"40px",C=p.backgroundColor,S=p.textColor,R=h("div","persona-send-button-wrapper"),w=h("button",u?"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(w.type="submit",w.setAttribute("data-persona-composer-submit",""),u){if(w.style.width=b,w.style.height=b,w.style.minWidth=b,w.style.minHeight=b,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",S?w.style.color=S:w.style.color="var(--persona-button-primary-fg, #ffffff)",m){let Le=parseFloat(b)||24,ue=(S==null?void 0:S.trim())||"currentColor",at=me(m,Le,ue,2);at?w.appendChild(at):w.textContent=f}else w.textContent=f;C?w.style.backgroundColor=C:w.classList.add("persona-bg-persona-primary")}else w.textContent=(Fe=(ee=r==null?void 0:r.copy)==null?void 0:ee.sendButtonLabel)!=null?Fe:"Send",S?w.style.color=S:w.classList.add("persona-text-white");if(p.borderWidth&&(w.style.borderWidth=p.borderWidth,w.style.borderStyle="solid"),p.borderColor&&(w.style.borderColor=p.borderColor),p.paddingX?(w.style.paddingLeft=p.paddingX,w.style.paddingRight=p.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),p.paddingY?(w.style.paddingTop=p.paddingY,w.style.paddingBottom=p.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),M&&v){let Le=h("div","persona-send-button-tooltip");Le.textContent=v,R.appendChild(Le)}R.appendChild(w);let L=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},B=L.enabled===!0,T=null,Y=null,ge=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ce=((K=L.provider)==null?void 0:K.type)==="runtype";if(B&&(ge||ce)){Y=h("div","persona-send-button-wrapper"),T=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),T.type="button",T.setAttribute("data-persona-composer-mic",""),T.setAttribute("aria-label","Start voice recognition");let Le=(vt=L.iconName)!=null?vt:"mic",ue=(tt=L.iconSize)!=null?tt:b,at=parseFloat(ue)||24,Be=(Lt=L.backgroundColor)!=null?Lt:C,Z=(Vt=L.iconColor)!=null?Vt:S;T.style.width=ue,T.style.height=ue,T.style.minWidth=ue,T.style.minHeight=ue,T.style.fontSize="18px",T.style.lineHeight="1",Z?T.style.color=Z:T.style.color="var(--persona-text, #111827)";let Pe=me(Le,at,Z||"currentColor",1.5);Pe?T.appendChild(Pe):T.textContent="\u{1F3A4}",Be&&(T.style.backgroundColor=Be),L.borderWidth&&(T.style.borderWidth=L.borderWidth,T.style.borderStyle="solid"),L.borderColor&&(T.style.borderColor=L.borderColor),L.paddingX&&(T.style.paddingLeft=L.paddingX,T.style.paddingRight=L.paddingX),L.paddingY&&(T.style.paddingTop=L.paddingY,T.style.paddingBottom=L.paddingY),Y.appendChild(T);let dt=(Ne=L.tooltipText)!=null?Ne:"Start voice recognition";if(((le=L.showTooltip)!=null?le:!1)&&dt){let nt=h("div","persona-send-button-tooltip");nt.textContent=dt,Y.appendChild(nt)}}let ne=(Ie=r==null?void 0:r.attachments)!=null?Ie:{},Te=ne.enabled===!0,re=null,Se=null,He=null,he=null;if(Te){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",He=h("input"),He.type="file",He.accept=((At=ne.allowedTypes)!=null?At:ar).join(","),He.multiple=((Et=ne.maxFiles)!=null?Et:4)>1,He.style.display="none",He.setAttribute("aria-label","Attach files"),Se=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(Ze=ne.buttonTooltipText)!=null?Ze:"Attach file");let Le=(Qe=ne.buttonIconName)!=null?Qe:"paperclip",ue=b,at=parseFloat(ue)||40,Be=Math.round(at*.6);re.style.width=ue,re.style.height=ue,re.style.minWidth=ue,re.style.minHeight=ue,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let Z=me(Le,Be,"currentColor",1.5);Z?re.appendChild(Z):re.textContent="\u{1F4CE}",re.addEventListener("click",dt=>{dt.preventDefault(),He==null||He.click()}),Se.appendChild(re);let ye=(Kt=ne.buttonTooltipText)!=null?Kt:"Attach file",Pe=h("div","persona-send-button-tooltip");Pe.textContent=ye,Se.appendChild(Pe)}s.addEventListener("click",Le=>{Le.target!==w&&Le.target!==R&&Le.target!==T&&Le.target!==Y&&Le.target!==re&&Le.target!==Se&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),He&&s.append(He),s.append(o);let Me=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),ke=h("div","persona-flex persona-items-center persona-gap-2");Se&&ke.append(Se);let oe=h("div","persona-flex persona-items-center persona-gap-1");Y&&oe.append(Y),oe.append(R),Me.append(ke,oe),s.append(Me);let be=(Gt=r==null?void 0:r.statusIndicator)!=null?Gt:{},$e=be.align==="left"?"persona-text-left":be.align==="center"?"persona-text-center":"persona-text-right",pe=h("div",`persona-mt-2 ${$e} persona-text-xs persona-text-persona-muted`);pe.setAttribute("data-persona-composer-status","");let de=(Zt=be.visible)!=null?Zt:!0;pe.style.display=de?"":"none";let se=(O=be.idleText)!=null?O:"Online";if(be.idleLink){let Le=h("a");Le.href=be.idleLink,Le.target="_blank",Le.rel="noopener noreferrer",Le.textContent=se,Le.style.color="inherit",Le.style.textDecoration="none",pe.appendChild(Le)}else pe.textContent=se;return t.append(n,s,pe),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:R,micButton:T,micButtonWrapper:Y,statusText:pe,attachmentButton:re,attachmentButtonWrapper:Se,attachmentInput:He,attachmentPreviewsContainer:he,actionsRow:Me,leftActions:ke,rightActions:oe}};var _c=e=>{var c,p,u,f,m,v,M,b,C;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Ut(e)){let S=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),R=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(R),{wrapper:S,panel:R}}if(!r){let S=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),R=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(u=e==null?void 0:e.launcher)==null?void 0:u.width)!=null?f:"100%";return S.style.width=w,R.style.width="100%",S.appendChild(R),{wrapper:S,panel:R}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&zn[n.position]?zn[n.position]:zn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((M=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?M:yn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(C=(b=e==null?void 0:e.launcher)==null?void 0:b.width)!=null?C:e==null?void 0:e.launcherWidth,d=i!=null?i:Mn;return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},jc=(e,r=!0)=>{var b,C,S,R,w,L,B,T,Y;let t=h("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");t.setAttribute("data-persona-theme-zone","container");let n=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((C=e==null?void 0:e.layout)==null?void 0:C.showHeader)!==!1,o=n?ao(e,n,{showClose:r}):ir({config:e,showClose:r}),a=h("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",a.setAttribute("data-persona-theme-zone","messages");let i=Ut(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(R=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeTitle)!=null?R:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(L=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?L:"Ask anything about your account or products.",d.append(c,p);let u=h("div","persona-flex persona-flex-col persona-gap-3"),f=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;f&&(u.style.maxWidth=f,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),d.setAttribute("data-persona-intro-card",""),((T=e==null?void 0:e.copy)==null?void 0:T.showWelcomeCard)!==!1||(d.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(d,u);let v=io({config:e}),M=((Y=e==null?void 0:e.layout)==null?void 0:Y.showFooter)!==!1;return s?_r(t,o,e):(o.header.style.display="none",_r(t,o,e)),t.append(a),M||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:u,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle:p,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var Tp=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},Mp=320,kp=320,Lp=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Ip=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var u;let c=h("img");c.alt=((u=i.alt)==null?void 0:u.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=`${Mp}px`,c.style.maxHeight=`${kp}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 p=!1;s+=1,c.addEventListener("error",()=>{p||(p=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{p=!0}),Tp(i.image)?(c.src=i.image,n.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},jr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},oa=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:jr};if(r){let s=r(n);if(s!==null)return s}return jr()},Pp=(e,r)=>{let t=h("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"),n=r==="user"?e.userAvatar:e.assistantAvatar;if(n)if(n.startsWith("http")||n.startsWith("/")||n.startsWith("data:")){let s=h("img");s.src=n,s.alt=r==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=n,t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=r==="user"?"U":"A",t.classList.add(r==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},zc=(e,r)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return r.format?t.textContent=r.format(n):t.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Wp=(e,r="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("persona-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("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("persona-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("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("persona-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},sa=(e,r,t)=>{var m,v,M,b,C,S;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(M=r.showDownvote)!=null?M:!0;if(!n&&!s&&!o){let R=h("div");return R.style.display="none",R.id=`actions-${e.id}`,R.setAttribute("data-actions-for",e.id),R}let a=(b=r.visibility)!=null?b:"hover",i=(C=r.align)!=null?C:"right",d=(S=r.layout)!=null?S:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],p={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],u=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let f=(R,w,L)=>{let B=wt({icon:R,label:w,size:14,className:"persona-message-action-btn"});return B.setAttribute("data-action",L),B};return n&&u.appendChild(f("copy","Copy message","copy")),s&&u.appendChild(f("thumbs-up","Upvote","upvote")),o&&u.appendChild(f("thumbs-down","Downvote","downvote")),u},lo=(e,r,t,n,s,o)=>{var ce,$,ne,Te,re,Se,He;let a=t!=null?t:{},i=(ce=a.layout)!=null?ce:"bubble",d=a.avatar,c=a.timestamp,p=($=d==null?void 0:d.show)!=null?$:!1,u=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Te=d==null?void 0:d.position)!=null?Te:"left",m=(re=c==null?void 0:c.position)!=null?re:"below",v=Wp(e.role,i),M=h("div",v.join(" "));M.id=`bubble-${e.id}`,M.setAttribute("data-message-id",e.id),M.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(M.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",M.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(M.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",M.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Lp(e),C=(He=(Se=e.content)==null?void 0:Se.trim())!=null?He:"",R=b.length>0&&C===ls,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),B=null;if(R?(B=document.createElement("div"),B.innerHTML=L,B.style.display="none",w.appendChild(B)):w.innerHTML=L,u&&m==="inline"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(b.length>0){let he=Ip(b,!R&&!!C,()=>{R&&B&&(B.style.display="")});he?M.appendChild(he):R&&B&&(B.style.display="")}if(M.appendChild(w),u&&m==="below"&&e.createdAt){let he=zc(e,c);he.classList.add("persona-mt-1"),M.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=oa("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&M.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=sa(e,n,s);M.appendChild(he)}if(!p||e.role==="system")return M;let Y=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=Pp(d,e.role);return f==="right"||f==="left"&&e.role==="user"?Y.append(M,ge):Y.append(ge,M),M.classList.remove("persona-max-w-[85%]"),M.classList.add("persona-max-w-[calc(85%-2.5rem)]"),Y},Uc=(e,r,t,n,s,o)=>{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}):lo(e,r,t,n,s,o)};var co=new Set,Vc=(e,r)=>{let t=co.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},aa=e=>{let r=e.reasoning,t=h("div",["persona-message-bubble","persona-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),!r)return t;let n=co.has(e.id),s=h("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");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=mc(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),p=me(n?"chevron-up":"chevron-down",16,"currentColor",2);p?d.appendChild(p):d.textContent=n?"Hide":"Show";let u=h("div","persona-flex persona-items-center persona-ml-auto");u.append(d),s.append(o,u);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let C=me(n?"chevron-up":"chevron-down",16,"currentColor",2);C?d.appendChild(C):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var po=new Set,qc=(e,r,t)=>{var c;let n=po.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let p=s.toggleTextColor||s.headerTextColor||"currentColor",u=me(n?"chevron-up":"chevron-down",16,p,2);u?d.appendChild(u):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},ia=(e,r)=>{var M;let t=e.toolCall,n=(M=r==null?void 0:r.toolCall)!=null?M:{},s=h("div",["persona-message-bubble","persona-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(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),n.backgroundColor&&(s.style.backgroundColor=n.backgroundColor),n.borderColor&&(s.style.borderColor=n.borderColor),n.borderWidth&&(s.style.borderWidth=n.borderWidth),n.borderRadius&&(s.style.borderRadius=n.borderRadius),!t)return s;let o=po.has(e.id),a=h("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",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=fc(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),p=n.toggleTextColor||n.headerTextColor||"currentColor",u=me(o?"chevron-up":"chevron-down",16,p,2);u?c.appendChild(u):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("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=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Arguments";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.args),b.append(C,S),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Activity";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=t.chunks.join(""),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),C=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(C.style.color=n.labelTextColor),C.textContent="Result";let S=h("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");S.style.fontSize="0.75rem",S.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(S.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(S.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(S.style.color=n.codeBlockTextColor),S.textContent=Lo(t.result),b.append(C,S),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",C=me(o?"chevron-up":"chevron-down",16,b,2);C?c.appendChild(C):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var la=(e,r)=>{var M,b,C,S,R,w,L,B,T,Y,ge,ce;let t=e.approval,n=(r==null?void 0:r.approval)!==!1?r==null?void 0:r.approval:void 0,s=(t==null?void 0:t.status)==="pending",o=h("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),o.style.backgroundColor=(M=n==null?void 0:n.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("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)":(C=n==null?void 0:n.titleColor)!=null?C:"currentColor",p=me(d,20,c,2);p&&i.appendChild(p);let u=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(S=n==null?void 0:n.title)!=null?S:"Approval Required",f.appendChild(m),!s){let $=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");$.setAttribute("data-approval-status",t.status),t.status==="approved"?($.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",$.style.color="var(--persona-palette-colors-success-700, #15803d)",$.textContent="Approved"):t.status==="denied"?($.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",$.style.color="var(--persona-palette-colors-error-700, #b91c1c)",$.textContent="Denied"):t.status==="timeout"&&($.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",$.style.color="var(--persona-palette-colors-warning-700, #b45309)",$.textContent="Timeout"),f.appendChild($)}u.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,u.appendChild(v),t.parameters){let $=h("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");n!=null&&n.parameterBackgroundColor&&($.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&($.style.color=n.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=Lo(t.parameters),u.appendChild($)}if(s){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let ne=h("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");ne.type="button",ne.style.backgroundColor=(R=n==null?void 0:n.approveButtonColor)!=null?R:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ne.setAttribute("data-approval-action","approve");let Te=me("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Te&&(Te.style.marginRight="4px",ne.appendChild(Te));let re=document.createTextNode((B=n==null?void 0:n.approveLabel)!=null?B:"Approve");ne.appendChild(re);let Se=h("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");Se.type="button",Se.style.backgroundColor=(T=n==null?void 0:n.denyButtonColor)!=null?T:"transparent",Se.style.color=(Y=n==null?void 0:n.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",Se.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Se.setAttribute("data-approval-action","deny");let He=me("shield-x",14,(ge=n==null?void 0:n.denyButtonTextColor)!=null?ge:"var(--persona-feedback-error, #dc2626)",2);He&&(He.style.marginRight="4px",Se.appendChild(He));let he=document.createTextNode((ce=n==null?void 0:n.denyLabel)!=null?ce:"Deny");Se.appendChild(he),$.append(ne,Se),u.appendChild($)}return a.append(i,u),o.appendChild(a),o};var Jc=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let p=document.createDocumentFragment(),u=s?s.isStreaming():!1,f=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'}};n.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=u,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),p.appendChild(v),r.push(v)}),e.appendChild(p)}}};var jo=class{constructor(r=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=r,this.buffer=new Array(r),this.store=t}push(r){var t;this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(r.type),(t=this.store)==null||t.put(r)}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 r=await this.store.getAll();if(r.length===0)return 0;let t=r.length>this.maxSize?r.slice(r.length-this.maxSize):r;for(let n of t)this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(n.type);return this.totalCaptured=r.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(r){let t=this.getAll();return r>=t.length?t:t.slice(t.length-r)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var r;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.clear()}destroy(){var r;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(r=this.store)==null||r.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var zo=class{constructor(r="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=r,this.storeName=t}open(){return new Promise((r,t)=>{try{let n=indexedDB.open(this.dbName,1);n.onupgradeneeded=()=>{let s=n.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},n.onsuccess=()=>{this.db=n.result,r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}put(r){!this.db||this.isDestroyed||(this.pendingWrites.push(r),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(r){if(!(!this.db||this.isDestroyed||r.length===0))try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}getAll(){return new Promise((r,t)=>{if(!this.db){r([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{r(a.result)},a.onerror=()=>{t(a.error)}}catch(n){t(n)}})}getCount(){return new Promise((r,t)=>{if(!this.db){r(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{r(o.result)},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}clear(){return new Promise((r,t)=>{if(!this.db){r();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{r()},o.onerror=()=>{t(o.error)}}catch(n){t(n)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((r,t)=>{try{let n=indexedDB.deleteDatabase(this.dbName);n.onsuccess=()=>{r()},n.onerror=()=>{t(n.error)}}catch(n){t(n)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let r=this.pendingWrites;this.pendingWrites=[];try{let n=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of r)n.put(s)}catch{}}};function uo(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Rp={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, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},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)"}},Hp={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Bp=["flowName","stepName","reasoningText","text","name","tool","toolName"],Dp=100;function Fp(e,r){let t={...Rp,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Hp}function Np(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Op(e){let r=new Date(e),t=String(r.getHours()).padStart(2,"0"),n=String(r.getMinutes()).padStart(2,"0"),s=String(r.getSeconds()).padStart(2,"0"),o=String(r.getMilliseconds()).padStart(3,"0");return`${t}:${n}:${s}.${o}`}function $p(e,r){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let n of r){let s=n.split("."),o=t;for(let a of s)if(o&&typeof o=="object"&&o!==null)o=o[a];else{o=void 0;break}if(typeof o=="string"&&o.trim())return o.trim()}}catch{}return null}function _p(e){var r;return(r=navigator.clipboard)!=null&&r.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let n=document.createElement("textarea");n.value=e,n.style.position="fixed",n.style.opacity="0",document.body.appendChild(n),n.select(),document.execCommand("copy"),document.body.removeChild(n),t()})}function jp(e){let r;try{r=JSON.parse(e.payload)}catch{r=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:r},null,2)}function zp(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("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=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function ca(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");uo(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(u()),c;function u(){var ne,Te;let m=h("div",""),v=h("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");v.setAttribute("data-event-id",e.id);let M=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(d?"chevron-down":"chevron-right","14px","currentColor",2);b&&M.appendChild(b);let C=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),S=(ne=n.timestampFormat)!=null?ne:"relative";C.textContent=S==="relative"?Np(e.timestamp,t):Op(e.timestamp);let R=null;n.showSequenceNumbers!==!1&&(R=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),R.textContent=String(r+1));let w=Fp(e.type,n.badgeColors),L=h("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");L.style.backgroundColor=w.bg,L.style.color=w.text,L.style.borderColor=w.text+"50",L.textContent=e.type;let B=(Te=n.descriptionFields)!=null?Te:Bp,T=$p(e.payload,B),Y=null;T&&(Y=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),Y.textContent=T);let ge=h("div","persona-flex-1 persona-min-w-0"),ce=h("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"),$=me("clipboard","12px","currentColor",1.5);return $&&ce.appendChild($),ce.addEventListener("click",async re=>{re.stopPropagation(),await _p(jp(e)),ce.innerHTML="";let Se=me("check","12px","currentColor",1.5);Se&&ce.appendChild(Se),setTimeout(()=>{ce.innerHTML="";let He=me("clipboard","12px","currentColor",1.5);He&&ce.appendChild(He)},1500)}),v.appendChild(M),v.appendChild(C),R&&v.appendChild(R),v.appendChild(L),Y&&v.appendChild(Y),v.appendChild(ge),v.appendChild(ce),m.appendChild(v),d&&m.appendChild(zp(e,a,i)),m}}function Yc(e){var m,v,M,b,C;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(m=s==null?void 0:s.features)==null?void 0:m.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,d=(v=a==null?void 0:a.iconName)!=null?v:"arrow-down",c=(M=a==null?void 0:a.label)!=null?M:"",p=(C=(b=s==null?void 0:s.features)==null?void 0:b.eventStream)!=null?C:{},u=o.find(S=>S.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&s){let S=u.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(S)return{element:S,update:()=>{},destroy:()=>{}}}return f();function f(){let S=p.classNames,R=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");uo(R,S==null?void 0:S.panel);let w=[],L="",B="",T=null,Y=[],ge={},ce=0,$=vs(),ne=0,Te=0,re=!1,Se=null,He=!1,he=0,Me=new Set,ke=new Map,oe="",be="",$e=null,pe,de,se,De,ot;function St(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ye=h("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");uo(ye,S==null?void 0:S.headerBar);let Pe=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Pe.textContent="Events",pe=h("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"),pe.textContent="0";let dt=h("div","persona-flex-1");de=h("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 Ot=h("option","");Ot.value="",Ot.textContent="All events",de.appendChild(Ot),se=h("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"),se.type="button",se.title="Copy All";let $t=me("clipboard-copy","12px","currentColor",1.5);$t&&se.appendChild($t);let it=h("span","persona-text-xs");it.textContent="Copy All",se.appendChild(it),ye.appendChild(Pe),ye.appendChild(pe),ye.appendChild(dt),ye.appendChild(de),ye.appendChild(se);let qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");uo(qe,S==null?void 0:S.searchBar);let lt=me("search","14px","var(--persona-muted, #9ca3af)",1.5),_e=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");lt&&_e.appendChild(lt),De=h("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"),uo(De,S==null?void 0:S.searchInput),De.type="text",De.placeholder="Search event payloads...",ot=h("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"),ot.type="button",ot.style.display="none";let _t=me("x","12px","currentColor",2);return _t&&ot.appendChild(_t),qe.appendChild(_e),qe.appendChild(De),qe.appendChild(ot),Z.appendChild(ye),Z.appendChild(qe),Z}let j,q=o.find(Z=>Z.renderEventStreamToolbar);if(q!=null&&q.renderEventStreamToolbar&&s){let Z=q.renderEventStreamToolbar({config:s,defaultRenderer:()=>St(),eventCount:r.getSize(),filteredCount:0,onFilterChange:ye=>{L=ye,Vt(),Ie()},onSearchChange:ye=>{B=ye,Vt(),Ie()}});j=Z!=null?Z:St()}else j=St();let ae=h("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");ae.style.display="none";let _=h("div","persona-flex-1 persona-min-h-0 persona-relative"),z=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");z.style.height="100%";let ee=h("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");uo(ee,S==null?void 0:S.scrollIndicator),ee.style.display="none",ee.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let Fe=me(d,"14px","currentColor",2);Fe&&ee.appendChild(Fe);let J=h("span","");J.textContent=c,ee.appendChild(J);let K=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");K.style.display="none",_.appendChild(z),_.appendChild(K),_.appendChild(ee),R.setAttribute("tabindex","0"),R.appendChild(j),R.appendChild(ae),R.appendChild(_);function vt(){let Z=r.getAll(),ye={};for(let it of Z)ye[it.type]=(ye[it.type]||0)+1;let Pe=Object.keys(ye).sort(),dt=Pe.length!==Y.length||!Pe.every((it,qe)=>it===Y[qe]),Ot=!dt&&Pe.some(it=>ye[it]!==ge[it]),nt=Z.length!==Object.values(ge).reduce((it,qe)=>it+qe,0);if(!dt&&!Ot&&!nt||(Y=Pe,ge=ye,!de))return;let $t=de.value;if(de.options[0].textContent="All events",dt){for(;de.options.length>1;)de.remove(1);for(let it of Pe){let qe=h("option","");qe.value=it,qe.textContent=`${it} (${ye[it]||0})`,de.appendChild(qe)}$t&&Pe.includes($t)?de.value=$t:$t&&(de.value="",L="")}else for(let it=1;it<de.options.length;it++){let qe=de.options[it];qe.textContent=`${qe.value} (${ye[qe.value]||0})`}}function tt(){let Z=r.getAll();if(L&&(Z=Z.filter(ye=>ye.type===L)),B){let ye=B.toLowerCase();Z=Z.filter(Pe=>Pe.type.toLowerCase().includes(ye)||Pe.payload.toLowerCase().includes(ye))}return Z}function Lt(){return L!==""||B!==""}function Vt(){ce=0,ne=0,$.resume(),ee.style.display="none"}function Ne(Z){Me.has(Z)?Me.delete(Z):Me.add(Z),$e=Z;let ye=z.scrollTop,Pe=$.isFollowing();He=!0,$.pause(),Ie(),z.scrollTop=ye,Pe&&$.resume(),He=!1}function le(){return Fo(z,50)}function Ie(){Te=Date.now(),re=!1,vt();let Z=r.getEvictedCount();Z>0?(ae.textContent=`${Z.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",w=tt();let ye=w.length,Pe=r.getSize()>0;pe&&(pe.textContent=String(r.getSize())),ye===0&&Pe&&Lt()?(K.textContent=B?`No events matching '${B}'`:"No events matching filter",K.style.display="",z.style.display="none"):(K.style.display="none",z.style.display=""),se&&(se.title=Lt()?`Copy Filtered (${ye})`:"Copy All"),i&&!$.isFollowing()&&ye>ce&&(ne+=ye-ce,J.textContent=c?`${c}${ne>0?` (${ne})`:""}`:"",ee.style.display=""),ce=ye;let dt=r.getAll(),Ot=dt.length>0?dt[0].timestamp:0,nt=new Set(w.map(qe=>qe.id));for(let qe of Me)nt.has(qe)||Me.delete(qe);let $t=L!==oe||B!==be,it=ke.size===0&&w.length>0;if($t||it||w.length===0){z.innerHTML="",ke.clear();let qe=document.createDocumentFragment();for(let lt=0;lt<w.length;lt++){let _e=ca(w[lt],lt,Ot,p,Me,Ne,o,s);ke.set(w[lt].id,_e),qe.appendChild(_e)}z.appendChild(qe),oe=L,be=B,$e=null}else{if($e!==null){let lt=ke.get($e);if(lt&<.parentNode===z){let _e=w.findIndex(_t=>_t.id===$e);if(_e>=0){let _t=ca(w[_e],_e,Ot,p,Me,Ne,o,s);z.insertBefore(_t,lt),lt.remove(),ke.set($e,_t)}}$e=null}let qe=new Set(w.map(lt=>lt.id));for(let[lt,_e]of ke)qe.has(lt)||(_e.remove(),ke.delete(lt));for(let lt=0;lt<w.length;lt++){let _e=w[lt];if(!ke.has(_e.id)){let _t=ca(_e,lt,Ot,p,Me,Ne,o,s);ke.set(_e.id,_t),z.appendChild(_t)}}}$.isFollowing()&&(z.scrollTop=z.scrollHeight)}function At(){if(Date.now()-Te>=Dp){Se!==null&&(cancelAnimationFrame(Se),Se=null),Ie();return}re||(re=!0,Se=requestAnimationFrame(()=>{Se=null,Ie()}))}let Et=(Z,ye)=>{if(!se)return;se.innerHTML="";let Pe=me(Z,"12px","currentColor",1.5);Pe&&se.appendChild(Pe);let dt=h("span","persona-text-xs");dt.textContent="Copy All",se.appendChild(dt),setTimeout(()=>{se.innerHTML="";let Ot=me("clipboard-copy","12px","currentColor",1.5);Ot&&se.appendChild(Ot);let nt=h("span","persona-text-xs");nt.textContent="Copy All",se.appendChild(nt),se.disabled=!1},ye)},Ze=async()=>{if(se){se.disabled=!0;try{let Z;Lt()?Z=w:t?(Z=await t(),Z.length===0&&(Z=r.getAll())):Z=r.getAll();let ye=Z.map(Pe=>{try{return JSON.parse(Pe.payload)}catch{return Pe.payload}});await navigator.clipboard.writeText(JSON.stringify(ye,null,2)),Et("check",1500)}catch{Et("x",1500)}}},Qe=()=>{de&&(L=de.value,Vt(),Ie())},Kt=()=>{!De||!ot||(ot.style.display=De.value?"":"none",T&&clearTimeout(T),T=setTimeout(()=>{B=De.value,Vt(),Ie()},150))},Gt=()=>{!De||!ot||(De.value="",B="",ot.style.display="none",T&&clearTimeout(T),Vt(),Ie())},Zt=()=>{if(He)return;let Z=z.scrollTop,{action:ye,nextLastScrollTop:Pe}=Cs({following:$.isFollowing(),currentScrollTop:Z,lastScrollTop:he,nearBottom:le(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Pe,ye==="resume"?($.resume(),ne=0,ee.style.display="none"):ye==="pause"&&($.pause(),i&&(J.textContent=c,ee.style.display=""))},O=Z=>{let ye=ws({following:$.isFollowing(),deltaY:Z.deltaY,nearBottom:le(),resumeWhenNearBottom:!0});ye==="pause"?($.pause(),i&&(J.textContent=c,ee.style.display="")):ye==="resume"&&($.resume(),ne=0,ee.style.display="none")},Le=()=>{i&&(z.scrollTop=z.scrollHeight,$.resume(),ne=0,ee.style.display="none")},ue=Z=>{let ye=Z.target;if(!ye||ye.closest("button"))return;let Pe=ye.closest("[data-event-id]");if(!Pe)return;let dt=Pe.getAttribute("data-event-id");dt&&Ne(dt)},at=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),De==null||De.focus(),De==null||De.select();return}Z.key==="Escape"&&(De&&document.activeElement===De?(Gt(),De.blur(),R.focus()):n&&n())};se&&se.addEventListener("click",Ze),de&&de.addEventListener("change",Qe),De&&De.addEventListener("input",Kt),ot&&ot.addEventListener("click",Gt),z.addEventListener("scroll",Zt),z.addEventListener("wheel",O,{passive:!0}),z.addEventListener("click",ue),ee.addEventListener("click",Le),R.addEventListener("keydown",at);function Be(){T&&clearTimeout(T),Se!==null&&(cancelAnimationFrame(Se),Se=null),re=!1,ke.clear(),se&&se.removeEventListener("click",Ze),de&&de.removeEventListener("change",Qe),De&&De.removeEventListener("input",Kt),ot&&ot.removeEventListener("click",Gt),z.removeEventListener("scroll",Zt),z.removeEventListener("wheel",O),z.removeEventListener("click",ue),ee.removeEventListener("click",Le),R.removeEventListener("keydown",at)}return{element:R,update:At,destroy:Be}}}function Gc(e,r){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",n=typeof e.artifactId=="string"?e.artifactId:"",s=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.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",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.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 c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=t;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(m)}else u.textContent=a;if(c.append(p,u),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var Xc=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>Gc(e,r)});if(p)return p}return Gc(e,r)};var da=class{constructor(){this.components=new Map}register(r,t){this.components.has(r)&&console.warn(`[ComponentRegistry] Component "${r}" is already registered. Overwriting.`),this.components.set(r,t)}unregister(r){this.components.delete(r)}get(r){return this.components.get(r)}has(r){return this.components.has(r)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(r){Object.entries(r).forEach(([t,n])=>{this.register(t,n)})}},lr=new da;lr.register("PersonaArtifactCard",Xc);function Up(e){var s;let r=h("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),t=h("div","persona-font-semibold persona-text-sm persona-mb-2");t.textContent=e.component?`Component: ${e.component}`:"Component";let n=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return n.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),r.appendChild(t),r.appendChild(n),r}function Kc(e,r){var se,De,ot,St;let t=(De=(se=e.features)==null?void 0:se.artifacts)==null?void 0:De.layout,s=((ot=t==null?void 0:t.toolbarPreset)!=null?ot:"default")==="document",o=(St=t==null?void 0:t.panePadding)==null?void 0:St.trim(),a=e.markdown?Br(e.markdown):null,i=no(e.sanitize),d=j=>{let q=a?a(j):to(j);return i?i(q):q},c=typeof document!="undefined"?h("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{c==null||c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let u=h("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");u.setAttribute("data-persona-theme-zone","artifact-pane"),s&&u.classList.add("persona-artifact-pane-document");let f=h("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");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let M="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),C=s?wt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):wt({icon:"eye",label:"Rendered view"}),S=s?wt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):wt({icon:"code-2",label:"Source"}),R=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,L=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,B=t==null?void 0:t.documentToolbarCopyMenuItems,T=!!(L&&B&&B.length>0),Y=null,ge,ce=null,$=null;if(s&&(w||L)&&!T){if(ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let j=me("chevron-down",14,"currentColor",2);j&&ge.appendChild(j)}}else s&&T?(Y=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ge=w?$o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ce=wt({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),Y.append(ge,ce)):s?ge=wt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ge=wt({icon:"copy",label:"Copy"});let ne=s?wt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):wt({icon:"refresh-cw",label:"Refresh"}),Te=s?wt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):wt({icon:"x",label:"Close"}),re=()=>{var z,ee,Fe;let j=(z=oe.find(J=>J.id===be))!=null?z:oe[oe.length-1],q=(ee=j==null?void 0:j.id)!=null?ee:null,ae=(j==null?void 0:j.artifactType)==="markdown"&&(Fe=j.markdown)!=null?Fe:"",_=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:ae,jsonPayload:_,id:q}},Se=async()=>{var z;let{markdown:j,jsonPayload:q}=re(),ae=(z=oe.find(ee=>ee.id===be))!=null?z:oe[oe.length-1],_=(ae==null?void 0:ae.artifactType)==="markdown"?j:ae?q:"";try{await navigator.clipboard.writeText(_)}catch{}};if(ge.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&T){let{markdown:q,jsonPayload:ae,id:_}=re();try{await j({actionId:"primary",artifactId:_,markdown:q,jsonPayload:ae})}catch{}return}await Se()}),ce&&(B!=null&&B.length)){let j=()=>{var ae;return(ae=u.closest("[data-persona-root]"))!=null?ae:document.body},q=()=>{$=Er({items:B.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:_,jsonPayload:z,id:ee}=re(),Fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Fe?await Fe({actionId:ae,artifactId:ee,markdown:_,jsonPayload:z}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(_):ae==="json"||ae==="source"?await navigator.clipboard.writeText(z):await navigator.clipboard.writeText(_||z)}catch{}},anchor:Y!=null?Y:ce,position:"bottom-right",portal:j()})};u.isConnected?q():requestAnimationFrame(q),ce.addEventListener("click",ae=>{ae.stopPropagation(),$==null||$.toggle()})}ne.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}pe()}),Te.addEventListener("click",()=>{var j;p(),(j=r.onDismiss)==null||j.call(r)});let He=()=>{s&&(C.setAttribute("aria-pressed",M==="rendered"?"true":"false"),S.setAttribute("aria-pressed",M==="source"?"true":"false"))};C.addEventListener("click",()=>{M="rendered",He(),pe()}),S.addEventListener("click",()=>{M="source",He(),pe()});let he=h("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");s?(f.replaceChildren(),b.append(C,S),Y?R.append(Y,ne,Te):R.append(ge,ne,Te),f.append(b,he,R),He()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Me=h("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"),ke=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Me.style.paddingLeft=o,Me.style.paddingRight=o,ke.style.padding=o),u.appendChild(f),u.appendChild(Me),u.appendChild(ke);let oe=[],be=null,$e=!1,pe=()=>{var _,z,ee,Fe;let j=s&&oe.length<=1;Me.classList.toggle("persona-hidden",j),Me.replaceChildren();for(let J of oe){let K=h("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");K.type="button",K.textContent=J.title||J.id.slice(0,8),J.id===be&&K.classList.add("persona-bg-persona-container","persona-border-persona-border"),K.addEventListener("click",()=>r.onSelect(J.id)),Me.appendChild(K)}ke.replaceChildren();let q=be&&oe.find(J=>J.id===be)||oe[oe.length-1];if(!q)return;if(s){let J=q.artifactType==="markdown"?"MD":(_=q.component)!=null?_:"Component",vt=(q.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${vt} \xB7 ${J}`}else m.textContent="Artifacts";if(q.artifactType==="markdown"){if(s&&M==="source"){let K=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");K.textContent=(z=q.markdown)!=null?z:"",ke.appendChild(K);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=d((ee=q.markdown)!=null?ee:""),ke.appendChild(J);return}let ae=q.component?lr.get(q.component):void 0;if(ae){let K={message:{id:q.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let vt=ae((Fe=q.props)!=null?Fe:{},K);if(vt){ke.appendChild(vt);return}}catch{}}ke.appendChild(Up(q))},de=()=>{var q;let j=oe.length>0;if(u.classList.toggle("persona-hidden",!j),c){let ae=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,z=((q=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?q:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&z&&$e?(c.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:c,update(j){var q,ae,_;oe=j.artifacts,be=(_=(ae=j.selectedId)!=null?ae:(q=j.artifacts[j.artifacts.length-1])==null?void 0:q.id)!=null?_:null,oe.length>0&&($e=!0),pe(),de()},setMobileOpen(j){$e=j,!j&&c?(c.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):de()}}}function Bn(e){var r,t;return((t=(r=e==null?void 0:e.features)==null?void 0:r.artifacts)==null?void 0:t.enabled)===!0}function Zc(e,r){var o,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"),!Bn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Vp(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 Ts(e,r){var d,c,p,u,f,m,v,M,b,C;if(!Bn(r)){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"),Vp(e),Zc(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(p=t==null?void 0:t.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=t==null?void 0:t.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(M=t==null?void 0:t.documentToolbarIconColor)==null?void 0:M.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(C=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:C.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Zc(e,r)}var Qc=["panel","seamless"];function Ms(e,r){var i,d,c,p,u,f;for(let m of Qc)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"),!Bn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Qc.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(p=t==null?void 0:t.paneBorderRadius)==null?void 0:p.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(u=t==null?void 0:t.paneShadow)==null?void 0:u.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=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function ed(e,r){var t,n,s;return!r||!Bn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function qp(e,r){if(!(e!=null&&e.trim()))return r;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):r}function Jp(e){if(!(e!=null&&e.trim()))return null;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):null}function Yp(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Gp(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function td(e,r){var a;let n=(a=(r.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(n);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(n);return o?Number(o[1]):8}function nd(e,r,t,n,s,o){let a=qp(s,200),i=Gp(r,t,n,200);i=Math.max(a,i);let d=Jp(o);return d!==null&&(i=Math.min(i,d)),Yp(e,a,i)}var rd={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"}},pa=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,M,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(M=rd[a])!=null?M:rd.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let C=h("p","persona-text-sm persona-text-persona-muted");C.textContent=i.description,d.appendChild(C)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(C=>{var B,T;let S=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");S.htmlFor=`${r.id}-${a}-${C.name}`;let R=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");R.textContent=C.label,S.appendChild(R);let w=(B=C.type)!=null?B:"text",L;w==="textarea"?(L=document.createElement("textarea"),L.rows=3):(L=document.createElement("input"),L.type=w),L.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",L.id=`${r.id}-${a}-${C.name}`,L.name=C.name,L.placeholder=(T=C.placeholder)!=null?T:"",C.required&&(L.required=!0),S.appendChild(L),p.appendChild(S)});let u=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("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=(b=i.submitLabel)!=null?b:"Submit",u.appendChild(f),u.appendChild(m),p.appendChild(u),o.replaceChildren(d,p),p.addEventListener("submit",async C=>{var L,B;C.preventDefault();let S=(L=t.formEndpoint)!=null?L:"/form",R=new FormData(p),w={};R.forEach((T,Y)=>{w[Y]=T}),w.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let T=await fetch(S,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!T.ok)throw new Error(`Form submission failed (${T.status})`);let Y=await T.json();f.textContent=(B=Y.message)!=null?B:"Thanks! We'll be in touch soon.",Y.success&&Y.nextPrompt&&await n.sendMessage(String(Y.nextPrompt))}catch(T){f.textContent=T instanceof Error?T.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var ua=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Uo=new ua;var od=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Xp=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Kp=e=>{let r=e.trim(),t=r.indexOf("{");if(t===-1)return null;let n=0;for(let s=t;s<r.length;s+=1){let o=r[s];if(o==="{"&&(n+=1),o==="}"&&(n-=1,n===0))return r.slice(t,s+1)}return null},Vo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Xp(e),t=Kp(r);if(!t)return null;let n=JSON.parse(t);if(!n||typeof n!="object"||!n.action)return null;let{action:s,...o}=n;return{type:String(s),payload:o,raw:n}}catch{return null}},ga=e=>typeof e=="string"?e:e==null?"":String(e),zr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ga(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ga(t.element);if(n&&((s=r.document)!=null&&s.querySelector)){let o=r.document.querySelector(n);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",n)}return{handled:!0,displayText:ga(t.text)}}},sd=e=>Array.isArray(e)?e.map(r=>String(r)):[],qo=e=>{let r=new Set(sd(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(sd(e.getSessionMetadata().processedActionMessageIds))},n=()=>{let o=Array.from(r);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||r.has(o.message.id))return null;let a=typeof o.raw=="string"&&o.raw||typeof o.message.rawContent=="string"&&o.message.rawContent||typeof o.text=="string"&&o.text||null;!a&&typeof o.text=="string"&&o.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,p)=>c||(p==null?void 0:p({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",d)},u=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let f=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:f,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Zp=e=>{if(!e)return null;try{return JSON.parse(e)}catch(r){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",r),null}},Qp=e=>e.map(r=>({...r,streaming:!1})),ks=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Zp(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Qp(t.messages):void 0};n.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=r();if(t)try{t.removeItem(e)}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",n)}}}};var go=require("partial-json");function eu(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function tu(e,r){if(!eu(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:r}}function Ls(){let e=null,r=0;return{getExtractedDirective:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e;try{let s=(0,go.parse)(t,go.STR|go.OBJ),o=tu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function ad(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Is(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=lr.get(e.component);if(!o)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:n,config:t,updateProps:i=>{s&&s(i)}};try{return o(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function id(){let e=Ls();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ps(e){if(!e.rawContent)return!1;try{let r=JSON.parse(e.rawContent);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function Ws(e){if(!e.rawContent)return null;try{let r=JSON.parse(e.rawContent);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string")return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:e.rawContent}}catch{}return null}var nu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Rs(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=nu}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let M=document.createElement("p");M.className="persona-feedback-subtitle",M.textContent=s,m.appendChild(M),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let C=[];for(let B=1;B<=5;B++){let T=document.createElement("button");T.type="button",T.className="persona-feedback-rating-btn persona-feedback-star-btn",T.setAttribute("role","radio"),T.setAttribute("aria-checked","false"),T.setAttribute("aria-label",`${B} star${B>1?"s":""}: ${c[B-1]}`),T.title=c[B-1],T.dataset.rating=String(B),T.innerHTML=`
|
|
17
16
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
18
17
|
<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
18
|
</svg>
|
|
@@ -110,7 +109,7 @@ ${a.join(`
|
|
|
110
109
|
${a.join(`
|
|
111
110
|
`)}`)}return n.join(`
|
|
112
111
|
|
|
113
|
-
`)}var Td={name:"@runtypelabs/persona",version:"3.9.
|
|
112
|
+
`)}var Td={name:"@runtypelabs/persona",version:"3.9.2",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"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","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:{dompurify:"^3.3.3",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",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",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 Ur=Td.version;function cr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Hu(e){if(e)return{getHeaders:cr(e.getHeaders),onFeedback:cr(e.onFeedback),onCopy:cr(e.onCopy),requestMiddleware:cr(e.requestMiddleware),actionHandlers:cr(e.actionHandlers),actionParsers:cr(e.actionParsers),postprocessMessage:cr(e.postprocessMessage),contextProviders:cr(e.contextProviders),streamParser:cr(e.streamParser)}}var Md=`({ text, message }: any) => {
|
|
114
113
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
115
114
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
116
115
|
let cleanJson = jsonSource
|