@runtypelabs/persona 3.15.1 → 3.17.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/animations/glyph-cycle.cjs +279 -0
- package/dist/animations/glyph-cycle.d.cts +5 -0
- package/dist/animations/glyph-cycle.d.ts +5 -0
- package/dist/animations/glyph-cycle.js +252 -0
- package/dist/animations/types-HPZY7oAI.d.cts +282 -0
- package/dist/animations/types-HPZY7oAI.d.ts +282 -0
- package/dist/animations/wipe.cjs +107 -0
- package/dist/animations/wipe.d.cts +5 -0
- package/dist/animations/wipe.d.ts +5 -0
- package/dist/animations/wipe.js +80 -0
- package/dist/index.cjs +49 -48
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +216 -1
- package/dist/index.d.ts +216 -1
- package/dist/index.global.js +137 -82
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +49 -48
- package/dist/index.js.map +1 -1
- package/dist/testing.cjs +85 -0
- package/dist/testing.d.cts +39 -0
- package/dist/testing.d.ts +39 -0
- package/dist/testing.js +56 -0
- package/dist/theme-editor.cjs +847 -127
- package/dist/theme-editor.d.cts +225 -2
- package/dist/theme-editor.d.ts +225 -2
- package/dist/theme-editor.js +845 -127
- package/dist/widget.css +133 -0
- package/package.json +20 -3
- package/src/animations/glyph-cycle.ts +332 -0
- package/src/animations/wipe.ts +66 -0
- package/src/client.test.ts +141 -0
- package/src/client.ts +197 -2
- package/src/components/composer-builder.ts +61 -10
- package/src/components/header-builder.ts +18 -7
- package/src/components/header-layouts.ts +3 -1
- package/src/components/message-bubble.test.ts +181 -2
- package/src/components/message-bubble.ts +209 -14
- package/src/components/panel.ts +4 -1
- package/src/defaults.ts +22 -0
- package/src/index-global.ts +31 -0
- package/src/index.ts +18 -0
- package/src/session.test.ts +93 -1
- package/src/session.ts +5 -0
- package/src/styles/widget.css +133 -0
- package/src/testing/index.ts +11 -0
- package/src/testing/mock-stream.test.ts +80 -0
- package/src/testing/mock-stream.ts +94 -0
- package/src/testing.ts +2 -0
- package/src/theme-editor/index.ts +4 -0
- package/src/theme-editor/preview-utils.test.ts +60 -0
- package/src/theme-editor/preview-utils.ts +129 -0
- package/src/theme-editor/sections.test.ts +19 -0
- package/src/theme-editor/sections.ts +84 -1
- package/src/types.ts +221 -0
- package/src/ui.stop-button.test.ts +165 -0
- package/src/ui.ts +79 -8
- package/src/utils/message-fingerprint.ts +2 -0
- package/src/utils/morph.ts +7 -0
- package/src/utils/stream-animation.test.ts +417 -0
- package/src/utils/stream-animation.ts +449 -0
package/dist/index.cjs
CHANGED
|
@@ -1,10 +1,11 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),
|
|
3
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=
|
|
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()=>{}}},Fr=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},Ss=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},As=()=>{var r;let e=Kp();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)}},Es=()=>{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,or.parse)(t,or.STR|or.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?xs(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=xs(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},td=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?xs(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?xs(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,or.parse)(o,or.STR|or.OBJ),u=s(i);u!==null&&(r=u)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},Ts=()=>{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 Ms=class{constructor(r,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=r,this.gapTimeoutMs=t}push(r,t){var o,a,i;let n=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(n==null){this.buffer.size>0&&this.flushAll(),this.emitter(r,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),n===this.nextExpectedSeq){this.emitter(r,t),this.nextExpectedSeq=n+1,this.drainConsecutive();return}if(n<this.nextExpectedSeq){this.emitter(r,t);return}let s=this.buffer.get(n);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${n} (${s.payloadType} vs ${r}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(n,{payloadType:r,payload:t,seq:n}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let r=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(r.payloadType,r.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let r=[...this.buffer.entries()].sort((t,n)=>t[0]-n[0]);for(let[t,n]of r)this.buffer.delete(t),this.emitter(n.payloadType,n.payload);r.length>0&&(this.nextExpectedSeq=r[r.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Xp="https://api.runtype.com/v1/dispatch",fa="https://api.runtype.com",ha=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 Zp(e){switch(e){case"json":return Es;case"regex-json":return As;case"xml":return Ts;default:return Ss}}var nd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Qp(e,r){if(!e)return r;let t=e.trim(),n=r.trim();if(t.length===0)return r;if(n.length===0)return e;let s=nd(t);if(!nd(n))return e;if(!s||n===t||n.startsWith(t))return r;let a=Fr(e);return Fr(r)!==null&&a===null?r:e}var Or=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:Xp,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:Zp(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$/,""))||fa;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$/,""))||fa}/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 u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(r.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:r.messages.filter(ha).map(g=>{var x,T,C;return{id:g.id,role:g.role,content:(C=(T=(x=g.contentParts)!=null?x:g.llmContent)!=null?T:g.rawContent)!=null?C:g.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",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let g=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 T=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:T}),T}if(f.status===429){let T=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:T}),T}let x=new Error(g.error||"Failed to send message");throw t({type:"error",error:x}),x}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&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 u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}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 u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}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$/,""))||fa}/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(ha).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(ha).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 u=p=>{let d={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=d,s(d),d},c=p=>n.current?n.current:u(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)),u(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 Lt,dt,Wt,Gt;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=P=>{let $=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,ne=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Pe=P.tools?P.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...P,reasoning:$,toolCall:ne,tools:Pe}},d=P=>{t({type:"message",message:p(P)})},f=null,g={current:null},x={current:null},T=!1,C=new Map,S=new Map,M={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},w=P=>{if(P==null)return null;try{return String(P)}catch{return null}},L=P=>{var $,ne,Pe,Fe,Ce;return w((Ce=(Fe=(Pe=(ne=($=P.stepId)!=null?$:P.step_id)!=null?ne:P.step)!=null?Pe:P.parentId)!=null?Fe:P.flowStepId)!=null?Ce:P.flow_step_id)},W=P=>{var $,ne,Pe,Fe,Ce,be,at;return w((at=(be=(Ce=(Fe=(Pe=(ne=($=P.callId)!=null?$:P.call_id)!=null?ne:P.requestId)!=null?Pe:P.request_id)!=null?Fe:P.toolCallId)!=null?Ce:P.tool_call_id)!=null?be:P.stepId)!=null?at:P.step_id)},E=n,K=!1,Q=()=>{if(f)return f;let P;return!K&&E?(P=E,K=!0):E&&x.current?P=`${E}_${x.current}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},X=(P,$)=>{M.lastId=$,P&&M.byStep.set(P,$)},O=(P,$)=>{var Ce;let ne=(Ce=P.reasoningId)!=null?Ce:P.id,Pe=L(P);if(ne){let be=String(ne);return X(Pe,be),be}if(Pe){let be=M.byStep.get(Pe);if(be)return M.lastId=be,be}if(M.lastId&&!$)return M.lastId;if(!$)return null;let Fe=`reason-${c()}`;return X(Pe,Fe),Fe},oe=P=>{let $=C.get(P);if($)return $;let ne={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:P,status:"streaming",chunks:[]}};return C.set(P,ne),d(ne),ne},Ee=(P,$)=>{H.lastId=$,P&&H.byCall.set(P,$)},ae=new Set,we=new Map,$e=new Set,he=new Map,We=P=>{if(!P)return!1;let $=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return $==="emit_artifact_markdown"||$==="emit_artifact_component"},Re=(P,$)=>{var Ce;let ne=(Ce=P.toolId)!=null?Ce:P.id,Pe=W(P);if(ne){let be=String(ne);return Ee(Pe,be),be}if(Pe){let be=H.byCall.get(Pe);if(be)return H.lastId=be,be}if(H.lastId&&!$)return H.lastId;if(!$)return null;let Fe=`tool-${c()}`;return Ee(Pe,Fe),Fe},ie=P=>{let $=S.get(P);if($)return $;let ne={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:P,status:"pending"}};return S.set(P,ne),d(ne),ne},Z=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let $=Number(P);if(!Number.isNaN($)&&Number.isFinite($))return $;let ne=Date.parse(P);if(!Number.isNaN(ne))return ne}return Date.now()},me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},V=new Map,re=new Map,He=new Map,ge=new Map,Be=null,st=(P,$,ne)=>{var at;let Pe=He.get(P);Pe||(Pe=[],He.set(P,Pe));let Fe=0,Ce=Pe.length;for(;Fe<Ce;){let mt=Fe+Ce>>>1;Pe[mt].seq<$?Fe=mt+1:Ce=mt}((at=Pe[Fe])==null?void 0:at.seq)===$?Pe[Fe]={seq:$,text:ne}:Pe.splice(Fe,0,{seq:$,text:ne});let be="";for(let mt=0;mt<Pe.length;mt++)be+=Pe[mt].text;return be},z=(P,$)=>{let ne=me($),Pe=re.get(P.id),Fe=Qp(Pe,ne);P.rawContent=Fe;let Ce=V.get(P.id),be=xe=>{var Ze;let ue=(Ze=P.content)!=null?Ze:"";xe.trim()!==""&&(ue.trim().length===0||xe.startsWith(ue)||xe.trimStart().startsWith(ue.trim()))&&(P.content=xe)},at=()=>{var xe;if(Ce){let ue=(xe=Ce.close)==null?void 0:xe.call(Ce);ue instanceof Promise&&ue.catch(()=>{})}V.delete(P.id),re.delete(P.id),P.streaming=!1,d(P)};if(!Ce){be(ne),at();return}let mt=Fr(Fe);if(mt!==null&&mt.trim()!==""){be(mt),at();return}let At=xe=>{var qe;let ue=typeof xe=="string"?xe:(qe=xe==null?void 0:xe.text)!=null?qe:null;if(ue!==null&&ue.trim()!=="")return ue;let Ze=Ce.getExtractedText();return Ze!==null&&Ze.trim()!==""?Ze:ne},j;try{j=Ce.processChunk(Fe)}catch{be(ne),at();return}if(j instanceof Promise){j.then(xe=>{be(At(xe)),at()}).catch(()=>{be(ne),at()});return}be(At(j)),at()},U=[],se=!1,N,J=()=>{se||(se=!0,queueMicrotask(()=>{se=!1,N()}))},ce=new Ms((P,$)=>{U.push({payloadType:P,payload:$}),J()}),fe=null,te=new Map,pe=(Lt=this.config.iterationDisplay)!=null?Lt:"separate";for(N=()=>{var P,$,ne,Pe,Fe,Ce,be,at,mt,At,j,xe,ue,Ze,qe,de,Te,Ve,vt,Ot,pt,$t,ht,Qe,yt,je,_t,zn,Kn,Rn,tt,Ar,qn,Er,En,Gr,cr,Xn,it,hn,Hn,nn,dr,yn,Et,rn,Tn,pr,Zn,ur,Un,bn,Vn,Ct,Bt,Dt,xn,mr,Bn,vn,D,Dn,Mn,gr,an,ln,le,Cn,Qn,es,yo,ts,Yr,et,bo,kn,cn,ns,rs,xo,er,os,Tr,vo,tr,Co,fr,hr,ss,as,ca,Mr,kr,Pt,Kr,Xr,wo,Jn,is,So,Ao,Eo,on,wn,nr,Je,To,Lr,Nn,ls,Zr,Qr,Ir,yr,cs,ds,Fn,Pr,ps;for(let eo=0;eo<U.length;eo++){let De=U[eo].payloadType,b=U[eo].payload;if(De==="reason_start"){let k=(P=O(b,!0))!=null?P:`reason-${c()}`,v=oe(k);v.reasoning=($=v.reasoning)!=null?$:{id:k,status:"streaming",chunks:[]},v.reasoning.startedAt=(Pe=v.reasoning.startedAt)!=null?Pe:Z((ne=b.startedAt)!=null?ne:b.timestamp),v.reasoning.completedAt=void 0,v.reasoning.durationMs=void 0,v.streaming=!0,v.reasoning.status="streaming",d(v)}else if(De==="reason_delta"||De==="reason_chunk"){let k=(Ce=(Fe=O(b,!1))!=null?Fe:O(b,!0))!=null?Ce:`reason-${c()}`,v=oe(k);v.reasoning=(be=v.reasoning)!=null?be:{id:k,status:"streaming",chunks:[]},v.reasoning.startedAt=(mt=v.reasoning.startedAt)!=null?mt:Z((at=b.startedAt)!=null?at:b.timestamp);let ee=(xe=(j=(At=b.reasoningText)!=null?At:b.text)!=null?j:b.delta)!=null?xe:"";if(ee&&b.hidden!==!0){let q=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(q!==void 0){let Le=st(k,q,String(ee));v.reasoning.chunks=[Le]}else v.reasoning.chunks.push(String(ee))}if(v.reasoning.status=b.done?"complete":"streaming",b.done){v.reasoning.completedAt=Z((ue=b.completedAt)!=null?ue:b.timestamp);let q=(Ze=v.reasoning.startedAt)!=null?Ze:Date.now();v.reasoning.durationMs=Math.max(0,((qe=v.reasoning.completedAt)!=null?qe:Date.now())-q)}v.streaming=v.reasoning.status!=="complete",d(v)}else if(De==="reason_complete"){let k=(Te=(de=O(b,!1))!=null?de:O(b,!0))!=null?Te:`reason-${c()}`,v=C.get(k);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=Z((Ve=b.completedAt)!=null?Ve:b.timestamp);let q=(vt=v.reasoning.startedAt)!=null?vt:Date.now();v.reasoning.durationMs=Math.max(0,((Ot=v.reasoning.completedAt)!=null?Ot:Date.now())-q),v.streaming=!1,d(v)}let ee=L(b);ee&&M.byStep.delete(ee)}else if(De==="tool_start"){let k=(pt=Re(b,!0))!=null?pt:`tool-${c()}`,v=($t=b.toolName)!=null?$t:b.name;if(We(v)){ae.add(k);continue}let ee=ie(k),q=(ht=ee.toolCall)!=null?ht:{id:k,status:"pending"};q.name=v!=null?v:q.name,q.status="running",b.args!==void 0?q.args=b.args:b.parameters!==void 0&&(q.args=b.parameters),q.startedAt=(yt=q.startedAt)!=null?yt:Z((Qe=b.startedAt)!=null?Qe:b.timestamp),q.completedAt=void 0,q.durationMs=void 0,ee.toolCall=q,ee.streaming=!0;let Le=b.agentContext;(Le||b.executionId)&&(ee.agentMetadata={executionId:(je=Le==null?void 0:Le.executionId)!=null?je:b.executionId,iteration:(_t=Le==null?void 0:Le.iteration)!=null?_t:b.iteration}),d(ee)}else if(De==="tool_chunk"||De==="tool_delta"){let k=(Kn=(zn=Re(b,!1))!=null?zn:Re(b,!0))!=null?Kn:`tool-${c()}`;if(ae.has(k))continue;let v=ie(k),ee=(Rn=v.toolCall)!=null?Rn:{id:k,status:"running"};ee.startedAt=(Ar=ee.startedAt)!=null?Ar:Z((tt=b.startedAt)!=null?tt:b.timestamp);let q=(En=(Er=(qn=b.text)!=null?qn:b.delta)!=null?Er:b.message)!=null?En:"";q&&(ee.chunks=(Gr=ee.chunks)!=null?Gr:[],ee.chunks.push(String(q))),ee.status="running",v.toolCall=ee,v.streaming=!0;let Le=b.agentContext;(Le||b.executionId)&&(v.agentMetadata=(it=v.agentMetadata)!=null?it:{executionId:(cr=Le==null?void 0:Le.executionId)!=null?cr:b.executionId,iteration:(Xn=Le==null?void 0:Le.iteration)!=null?Xn:b.iteration}),d(v)}else if(De==="tool_complete"){let k=(Hn=(hn=Re(b,!1))!=null?hn:Re(b,!0))!=null?Hn:`tool-${c()}`;if(ae.has(k)){ae.delete(k);continue}let v=ie(k),ee=(nn=v.toolCall)!=null?nn:{id:k,status:"running"};ee.status="complete",b.result!==void 0&&(ee.result=b.result),typeof b.duration=="number"&&(ee.duration=b.duration),ee.completedAt=Z((dr=b.completedAt)!=null?dr:b.timestamp);let q=(yn=b.duration)!=null?yn:b.executionTime;if(typeof q=="number")ee.durationMs=q;else{let Rt=(Et=ee.startedAt)!=null?Et:Date.now();ee.durationMs=Math.max(0,((rn=ee.completedAt)!=null?rn:Date.now())-Rt)}v.toolCall=ee,v.streaming=!1;let Le=b.agentContext;(Le||b.executionId)&&(v.agentMetadata=(Zn=v.agentMetadata)!=null?Zn:{executionId:(Tn=Le==null?void 0:Le.executionId)!=null?Tn:b.executionId,iteration:(pr=Le==null?void 0:Le.iteration)!=null?pr:b.iteration}),d(v);let Xe=W(b);Xe&&H.byCall.delete(Xe)}else if(De==="text_start"){let k=b.partId;if(k!==void 0&&x.current!==null&&k!==x.current){let v=f;v&&(v.streaming=!1,d(v),Be=v,f=null,T=!0)}k!==void 0&&(x.current=k)}else if(De==="text_end"){let k=f;k&&(k.streaming=!1,d(k),Be=k,f=null,T=!0)}else if(De==="step_chunk"||De==="step_delta"){let k=b.stepType,v=b.executionType;if(k==="tool"||v==="context")continue;let ee=b.partId;if(ee!==void 0&&x.current!==null&&ee!==x.current){let Xe=f;Xe&&(Xe.streaming=!1,d(Xe),Be=Xe,f=null,T=!0)}ee!==void 0&&(x.current=ee);let q=ee!==void 0&&(ur=ge.get(ee))!=null?ur:Q();ee!==void 0&&(q.partId||(q.partId=ee),ge.set(ee,q));let Le=(Ct=(Vn=(bn=(Un=b.text)!=null?Un:b.delta)!=null?bn:b.content)!=null?Vn:b.chunk)!=null?Ct:"";if(Le){let Xe=typeof b.seq=="number"?b.seq:void 0,Rt=ee!=null?ee:q.id,wt=Xe!==void 0?st(Rt,Xe,String(Le)):((Bt=re.get(q.id))!=null?Bt:"")+Le;q.rawContent=wt,V.has(q.id)||V.set(q.id,this.createStreamParser());let Yt=V.get(q.id),Ht=wt.trim().startsWith("{")||wt.trim().startsWith("[");if(Ht&&re.set(q.id,wt),Yt.__isPlainTextParser===!0){q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q);continue}let rt=Yt.processChunk(wt);if(rt instanceof Promise)rt.then(ut=>{var On;let zt=typeof ut=="string"?ut:(On=ut==null?void 0:ut.text)!=null?On:null;if(zt!==null&&zt.trim()!=="")q.content=zt,d(q);else if(!Ht&&!wt.trim().startsWith("<")){let bt=f,Nt=bt&&bt.id===q.id?bt:q;Nt.id===q.id&&(Nt.content=Xe!==void 0?wt:Nt.content+Le,re.delete(Nt.id),V.delete(Nt.id),Nt.rawContent=void 0,d(Nt))}}).catch(()=>{q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q)});else{let ut=typeof rt=="string"?rt:(Dt=rt==null?void 0:rt.text)!=null?Dt:null;ut!==null&&ut.trim()!==""?(q.content=ut,d(q)):!Ht&&!wt.trim().startsWith("<")&&(q.content=Xe!==void 0?wt:q.content+Le,re.delete(q.id),V.delete(q.id),q.rawContent=void 0,d(q))}}if(b.isComplete){let Xe=(mr=(xn=b.result)==null?void 0:xn.response)!=null?mr:q.content;if(Xe){let Rt=re.get(q.id),wt=Rt!=null?Rt:me(Xe);q.rawContent=wt;let Yt=V.get(q.id),Ht=null,Zt=!1;if(Yt&&(Ht=Yt.getExtractedText(),Ht===null&&(Ht=Fr(wt)),Ht===null)){let rt=Yt.processChunk(wt);rt instanceof Promise?(Zt=!0,rt.then(ut=>{var On;let zt=typeof ut=="string"?ut:(On=ut==null?void 0:ut.text)!=null?On:null;if(zt!==null){let bt=f;bt&&bt.id===q.id&&(bt.content=zt,bt.streaming=!1,V.delete(bt.id),re.delete(bt.id),d(bt))}})):Ht=typeof rt=="string"?rt:(Bn=rt==null?void 0:rt.text)!=null?Bn:null}if(!Zt){Ht!==null&&Ht.trim()!==""?q.content=Ht:re.has(q.id)||(q.content=me(Xe));let rt=V.get(q.id);if(rt){let ut=(vn=rt.close)==null?void 0:vn.call(rt);ut instanceof Promise&&ut.catch(()=>{}),V.delete(q.id)}re.delete(q.id),q.streaming=!1,d(q)}}}}else if(De==="step_complete"){let k=b.stepType,v=b.executionType;if(k==="tool"||v==="context")continue;if(T){if(f!==null){let Rt=f;V.delete(Rt.id),re.delete(Rt.id),Rt.streaming!==!1&&(Rt.streaming=!1,d(Rt))}let Le=(D=b.result)==null?void 0:D.response,Xe=Be;Xe&&(Le!=null?z(Xe,Le):(V.delete(Xe.id),re.delete(Xe.id))),Be=null;continue}let ee=(Dn=b.result)==null?void 0:Dn.response,q=Q();if(ee!=null){let Le=V.get(q.id),Xe=!1,Rt=!1;if(Le){let wt=Le.getExtractedText(),Yt=re.get(q.id),Ht=Yt!=null?Yt:me(ee);if(q.rawContent=Ht,wt!==null&&wt.trim()!=="")q.content=wt,Xe=!0;else{let Zt=Fr(Ht);if(Zt!==null)q.content=Zt,Xe=!0;else{let rt=Le.processChunk(Ht);if(rt instanceof Promise)Rt=!0,rt.then(ut=>{var On;let zt=typeof ut=="string"?ut:(On=ut==null?void 0:ut.text)!=null?On:null;if(zt!==null&&zt.trim()!==""){let bt=f;bt&&bt.id===q.id&&(bt.content=zt,bt.streaming=!1,V.delete(bt.id),re.delete(bt.id),d(bt))}else{let bt=Le.getExtractedText(),Nt=f;Nt&&Nt.id===q.id&&(bt!==null&&bt.trim()!==""?Nt.content=bt:re.has(Nt.id)||(Nt.content=me(ee)),Nt.streaming=!1,V.delete(Nt.id),re.delete(Nt.id),d(Nt))}});else{let ut=typeof rt=="string"?rt:(Mn=rt==null?void 0:rt.text)!=null?Mn:null;if(ut!==null&&ut.trim()!=="")q.content=ut,Xe=!0;else{let zt=Le.getExtractedText();zt!==null&&zt.trim()!==""&&(q.content=zt,Xe=!0)}}}}}if(!Rt){if(!q.rawContent){let wt=re.get(q.id);q.rawContent=wt!=null?wt:me(ee)}if(!Xe&&!re.has(q.id)&&(q.content=me(ee)),Le){let wt=(gr=Le.close)==null?void 0:gr.call(Le);wt instanceof Promise&&wt.catch(()=>{})}V.delete(q.id),re.delete(q.id),q.streaming=!1,d(q)}}else V.delete(q.id),re.delete(q.id),q.streaming=!1,d(q)}else if(De==="flow_complete"){let k=(an=b.result)==null?void 0:an.response;if(T){if(f!==null){let v=f;V.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,d(v))}}else if(k!=null){let v=Q(),ee=re.get(v.id),q=ee!=null?ee:me(k);v.rawContent=q;let Le=me(k),Xe=V.get(v.id);if(Xe){let Yt=Fr(q);if(Yt!==null)Le=Yt;else{let Ht=Xe.processChunk(q);Ht instanceof Promise&&Ht.then(rt=>{var zt;let ut=typeof rt=="string"?rt:(zt=rt==null?void 0:rt.text)!=null?zt:null;ut!==null&&(v.content=ut,v.streaming=!1,d(v))});let Zt=Xe.getExtractedText();Zt!==null&&(Le=Zt)}}V.delete(v.id),re.delete(v.id);let Rt=Le!==v.content,wt=v.streaming!==!1;Rt&&(v.content=Le),v.streaming=!1,(Rt||wt)&&d(v)}else if(f!==null){let v=f;V.delete(v.id),re.delete(v.id),v.streaming!==!1&&(v.streaming=!1,d(v))}t({type:"status",status:"idle"})}else if(De==="agent_start")fe={executionId:b.executionId,agentId:(ln=b.agentId)!=null?ln:"virtual",agentName:(le=b.agentName)!=null?le:"",status:"running",currentIteration:0,maxTurns:(Cn=b.maxTurns)!=null?Cn:1,startedAt:Z(b.startedAt)};else if(De==="agent_iteration_start"){if(fe&&(fe.currentIteration=b.iteration),pe==="separate"&&b.iteration>1){let k=f;k&&(k.streaming=!1,d(k),te.set(b.iteration-1,k),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let k=Q();k.content+=(Qn=b.delta)!=null?Qn:"",k.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:fe==null?void 0:fe.agentName},d(k)}else if(b.contentType==="thinking"){let k=(es=b.turnId)!=null?es:`agent-think-${b.iteration}`,v=oe(k);v.reasoning=(yo=v.reasoning)!=null?yo:{id:k,status:"streaming",chunks:[]},v.reasoning.chunks.push((ts=b.delta)!=null?ts:""),v.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(v)}else if(b.contentType==="tool_input"){let k=(Yr=b.toolCallId)!=null?Yr:H.lastId;if(k){let v=S.get(k);v!=null&&v.toolCall&&(v.toolCall.chunks=(et=v.toolCall.chunks)!=null?et:[],v.toolCall.chunks.push((bo=b.delta)!=null?bo:""),d(v))}}}else if(De==="agent_turn_complete"){let k=b.turnId;if(k){let v=C.get(k);if(v!=null&&v.reasoning){v.reasoning.status="complete",v.reasoning.completedAt=Z(b.completedAt);let ee=(kn=v.reasoning.startedAt)!=null?kn:Date.now();v.reasoning.durationMs=Math.max(0,((cn=v.reasoning.completedAt)!=null?cn:Date.now())-ee),v.streaming=!1,d(v)}}}else if(De==="agent_tool_start"){let k=(ns=b.toolCallId)!=null?ns:`agent-tool-${c()}`;Ee(W(b),k);let v=ie(k),ee=(rs=v.toolCall)!=null?rs:{id:k,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};ee.name=(er=(xo=b.toolName)!=null?xo:b.name)!=null?er:ee.name,ee.status="running",b.parameters!==void 0&&(ee.args=b.parameters),ee.startedAt=Z((os=b.startedAt)!=null?os:b.timestamp),v.toolCall=ee,v.streaming=!0,v.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(v)}else if(De==="agent_tool_delta"){let k=(Tr=b.toolCallId)!=null?Tr:H.lastId;if(k){let v=(vo=S.get(k))!=null?vo:ie(k);v.toolCall&&(v.toolCall.chunks=(tr=v.toolCall.chunks)!=null?tr:[],v.toolCall.chunks.push((Co=b.delta)!=null?Co:""),v.toolCall.status="running",v.streaming=!0,d(v))}}else if(De==="agent_tool_complete"){let k=(fr=b.toolCallId)!=null?fr:H.lastId;if(k){let v=(hr=S.get(k))!=null?hr:ie(k);if(v.toolCall){v.toolCall.status="complete",b.result!==void 0&&(v.toolCall.result=b.result),typeof b.executionTime=="number"&&(v.toolCall.durationMs=b.executionTime),v.toolCall.completedAt=Z((ss=b.completedAt)!=null?ss:b.timestamp),v.streaming=!1,d(v);let ee=W(b);ee&&H.byCall.delete(ee)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let k=`agent-reflection-${b.executionId}-${b.iteration}`,v={id:k,role:"assistant",content:(as=b.reflection)!=null?as:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:k,status:"complete",chunks:[(ca=b.reflection)!=null?ca:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(v)}else if(De==="agent_complete"){fe&&(fe.status=b.success?"complete":"error",fe.completedAt=Z(b.completedAt),fe.stopReason=b.stopReason);let k=f;k&&(k.streaming=!1,d(k)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let k=typeof b.error=="string"?b.error:(kr=(Mr=b.error)==null?void 0:Mr.message)!=null?kr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",k):t({type:"error",error:new Error(k)})}else if(De!=="agent_ping"){if(De==="agent_approval_start"){let k=(Pt=b.approvalId)!=null?Pt:`approval-${c()}`,v={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:(Kr=fe==null?void 0:fe.agentId)!=null?Kr:"virtual",executionId:(wo=(Xr=b.executionId)!=null?Xr:fe==null?void 0:fe.executionId)!=null?wo:"",toolName:(Jn=b.toolName)!=null?Jn:"",toolType:b.toolType,description:(So=b.description)!=null?So:`Execute ${(is=b.toolName)!=null?is:"tool"}`,parameters:b.parameters}};d(v)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let k=(Ao=b.approvalId)!=null?Ao:`approval-${c()}`,v={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:"pending",agentId:(Eo=fe==null?void 0:fe.agentId)!=null?Eo:"virtual",executionId:(wn=(on=b.executionId)!=null?on:fe==null?void 0:fe.executionId)!=null?wn:"",toolName:(nr=b.toolName)!=null?nr:"",toolType:b.toolType,description:(To=b.description)!=null?To:`Execute ${(Je=b.toolName)!=null?Je:"tool"}`,parameters:b.parameters}};d(v)}else if(De==="agent_approval_complete"){let k=b.approvalId;if(k){let ee={id:`approval-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:k,status:(Lr=b.decision)!=null?Lr:"approved",agentId:(Nn=fe==null?void 0:fe.agentId)!=null?Nn:"virtual",executionId:(Zr=(ls=b.executionId)!=null?ls:fe==null?void 0:fe.executionId)!=null?Zr:"",toolName:(Qr=b.toolName)!=null?Qr:"",description:(Ir=b.description)!=null?Ir:"",resolvedAt:Date.now()}};d(ee)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let k=b.artifactType,v=String(b.id),ee=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:v,artifactType:k,title:ee,component:typeof b.component=="string"?b.component:void 0}),he.set(v,{markdown:"",title:ee}),!$e.has(v)){$e.add(v);let q={id:`artifact-ref-${v}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:v,title:ee,artifactType:k,status:"streaming"}})};we.set(v,q),d(q)}}else if(De==="artifact_delta"){let k=String(b.id),v=typeof b.delta=="string"?b.delta:String((yr=b.delta)!=null?yr:"");t({type:"artifact_delta",id:k,artDelta:v});let ee=he.get(k);ee&&(ee.markdown+=v)}else if(De==="artifact_update"){let k=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:k,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let k=String(b.id);t({type:"artifact_complete",id:k});let v=we.get(k);if(v){v.streaming=!1;try{let ee=JSON.parse((cs=v.rawContent)!=null?cs:"{}");if(ee.props){ee.props.status="complete";let q=he.get(k);q!=null&&q.markdown&&(ee.props.markdown=q.markdown)}v.rawContent=JSON.stringify(ee)}catch{}he.delete(k),d(v),we.delete(k)}}}else if(De==="transcript_insert"){let k=b.message;if(!k||typeof k!="object")continue;let v=String((ds=k.id)!=null?ds:`msg-${c()}`),ee=k.role,Le={id:v,role:ee==="user"?"user":ee==="system"?"system":"assistant",content:typeof k.content=="string"?k.content:"",rawContent:typeof k.rawContent=="string"?k.rawContent:void 0,createdAt:typeof k.createdAt=="string"?k.createdAt:new Date().toISOString(),streaming:k.streaming===!0,...typeof k.variant=="string"?{variant:k.variant}:{},sequence:c()};if(d(Le),Le.rawContent)try{let Xe=JSON.parse(Le.rawContent),Rt=(Fn=Xe==null?void 0:Xe.props)==null?void 0:Fn.artifactId;typeof Rt=="string"&&$e.add(Rt)}catch{}f=null,g.current=null,V.delete(v),re.delete(v)}else if(De==="error"||De==="step_error"||De==="dispatch_error"||De==="flow_error"){let k=null;if(b.error instanceof Error)k=b.error;else if(De==="dispatch_error"){let v=(Pr=b.message)!=null?Pr:b.error;v!=null&&v!==""&&(k=new Error(String(v)))}else if(De==="step_error"||De==="flow_error"){let v=b.error;typeof v=="string"&&v!==""?k=new Error(v):v!=null&&typeof v=="object"&&"message"in v&&(k=new Error(String((ps=v.message)!=null?ps:v)))}else De==="error"&&b.error!=null&&b.error!==""&&(k=new Error(String(b.error)));if(k){t({type:"error",error:k});let v=f;v&&v.streaming&&(v.streaming=!1,d(v)),t({type:"status",status:"idle"})}}}}}}U.length=0};;){let{done:P,value:$}=await s.read();if(P)break;a+=o.decode($,{stream:!0});let ne=a.split(`
|
|
1
|
+
"use strict";var su=Object.create;var Bs=Object.defineProperty;var au=Object.getOwnPropertyDescriptor;var iu=Object.getOwnPropertyNames;var lu=Object.getPrototypeOf,cu=Object.prototype.hasOwnProperty;var du=(e,n)=>{for(var t in n)Bs(e,t,{get:n[t],enumerable:!0})},nd=(e,n,t,r)=>{if(n&&typeof n=="object"||typeof n=="function")for(let s of iu(n))!cu.call(e,s)&&s!==t&&Bs(e,s,{get:()=>n[s],enumerable:!(r=au(n,s))||r.enumerable});return e};var rd=(e,n,t)=>(t=e!=null?su(lu(e)):{},nd(n||!e||!e.__esModule?Bs(t,"default",{value:e,enumerable:!0}):t,e)),pu=e=>nd(Bs({},"__esModule",{value:!0}),e);var wg={};du(wg,{AgentWidgetClient:()=>Kr,AgentWidgetSession:()=>ho,AttachmentManager:()=>Zr,DEFAULT_COMPONENTS:()=>Fa,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH:()=>Xs,DEFAULT_FLOATING_LAUNCHER_WIDTH:()=>Pn,DEFAULT_PALETTE:()=>Da,DEFAULT_SEMANTIC:()=>Na,DEFAULT_WIDGET_CONFIG:()=>Wt,PRESETS:()=>Si,PRESET_FULLSCREEN:()=>wi,PRESET_MINIMAL:()=>Ci,PRESET_SHOP:()=>vi,THEME_ZONES:()=>Id,VERSION:()=>no,accessibilityPlugin:()=>Gp,animationsPlugin:()=>Yp,applyThemeVariables:()=>kr,attachHeaderToContainer:()=>Qr,brandPlugin:()=>Xp,buildComposer:()=>xo,buildDefaultHeader:()=>Ja,buildHeader:()=>ur,buildHeaderWithLayout:()=>bo,buildMinimalHeader:()=>Ka,collectEnrichedPageContext:()=>Rp,componentRegistry:()=>mr,createActionManager:()=>fs,createAgentExperience:()=>xa,createBestAvailableVoiceProvider:()=>Gs,createBubbleWithLayout:()=>Zd,createCSATFeedback:()=>ha,createComboButton:()=>ia,createComponentMiddleware:()=>fp,createComponentStreamParser:()=>ua,createDefaultSanitizer:()=>Wa,createDemoCarousel:()=>Kp,createDirectivePostprocessor:()=>ld,createDropdownMenu:()=>Pr,createFlexibleJsonStreamParser:()=>md,createIconButton:()=>Ht,createImagePart:()=>vd,createJsonStreamParser:()=>js,createLabelButton:()=>cs,createLocalStorageAdapter:()=>pa,createMarkdownProcessor:()=>Jo,createMarkdownProcessorFromConfig:()=>Ur,createMessageActions:()=>Xa,createNPSFeedback:()=>ya,createPlainTextParser:()=>$s,createPlugin:()=>eu,createRegexJsonParser:()=>_s,createStandardBubble:()=>vo,createTextPart:()=>Yo,createTheme:()=>yo,createThemeObserver:()=>ta,createToggleGroup:()=>ds,createTypingIndicator:()=>eo,createVoiceProvider:()=>Xr,createWidgetHostLayout:()=>hs,createXmlParser:()=>zs,default:()=>Cg,defaultActionHandlers:()=>to,defaultJsonActionParser:()=>gs,defaultParseRules:()=>hi,detectColorScheme:()=>ts,directivePostprocessor:()=>cd,escapeHtml:()=>uo,extractComponentDirectiveFromMessage:()=>fa,fileToImagePart:()=>Cd,formatEnrichedContext:()=>Hp,generateAssistantMessageId:()=>Gr,generateCodeSnippet:()=>_p,generateMessageId:()=>fd,generateStableSelector:()=>yi,generateUserMessageId:()=>fo,getActiveTheme:()=>ns,getColorScheme:()=>$a,getDisplayText:()=>yd,getHeaderLayout:()=>Ga,getImageParts:()=>xd,getPreset:()=>nu,hasComponentDirective:()=>ga,hasImages:()=>bd,headerLayouts:()=>la,highContrastPlugin:()=>Qp,initAgentWidget:()=>ui,isComponentDirectiveType:()=>gp,isDockedMountMode:()=>Jt,isVoiceSupported:()=>Zo,listRegisteredStreamAnimations:()=>qd,markdownPostprocessor:()=>Pa,mergeWithDefaults:()=>Zs,normalizeContent:()=>hd,pluginRegistry:()=>ms,reducedMotionPlugin:()=>Zp,registerStreamAnimationPlugin:()=>jd,renderComponentDirective:()=>ma,renderLoadingIndicatorWithFallback:()=>Ya,resolveDockConfig:()=>$n,resolveSanitizer:()=>mo,resolveTokens:()=>Qs,themeToCssVariables:()=>ea,unregisterStreamAnimationPlugin:()=>zd,validateImageFile:()=>wd,validateTheme:()=>Oa});module.exports=pu(wg);var sd=require("marked"),uu=e=>{if(e)return e},Jo=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new sd.Marked({gfm:(s=n==null?void 0:n.gfm)!=null?s:!0,breaks:(o=n==null?void 0:n.breaks)!=null?o:!0,pedantic:n==null?void 0:n.pedantic,silent:n==null?void 0:n.silent}),r=uu(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},Ur=e=>e?Jo({markedOptions:e.options,renderer:e.renderer}):Jo(),mu=Jo(),Pa=e=>mu(e),uo=e=>e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'"),ad=e=>e.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">"),od=e=>`%%FORM_PLACEHOLDER_${e}%%`,id=(e,n)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(r,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=od(n.length);return n.push({token:a,type:String(o.type)}),a}}catch{return r}return r}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(r,s)=>{let o=od(n.length);return n.push({token:o,type:s}),o}),t},ld=e=>{let n=Ur(e);return t=>{let r=[],s=id(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let u=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${ad(i)}"></div>`;o=o.replace(u,p)}),o}},cd=e=>{let n=[],t=id(e,n),r=Pa(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${ad(o)}"></div>`;r=r.replace(a,u)}),r};var dd=rd(require("dompurify"),1),gu={ALLOWED_TAGS:["h1","h2","h3","h4","h5","h6","p","br","hr","div","span","ul","ol","li","dl","dt","dd","strong","em","b","i","u","s","del","ins","mark","small","sub","sup","abbr","kbd","var","samp","code","a","img","blockquote","pre","details","summary","table","thead","tbody","tfoot","tr","th","td","caption","colgroup","col","input","label","select","option","textarea","button"],ALLOWED_ATTR:["href","src","alt","title","target","rel","loading","width","height","colspan","rowspan","scope","class","id","type","name","value","placeholder","disabled","checked","for","aria-label","aria-hidden","aria-expanded","role","tabindex","data-tv-form","data-message-id","data-persona-component-directive","data-preserve-animation","data-persona-instance"]},fu=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Wa=()=>{let e=(0,dd.default)(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(n,t)=>{if(t.attrName==="src"||t.attrName==="href"){let r=t.attrValue;r.toLowerCase().startsWith("data:")&&!fu.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,gu)},mo=e=>e===!1?null:typeof e=="function"?e:Wa();var dr=require("partial-json"),Ds=e=>e.replace(/\\n/g,`
|
|
2
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),go=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},hu=e=>{var a,i;let n=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:n,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,n-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},pd=e=>e.status==="complete"?hu(e):e.status==="pending"?"Waiting":"",yu=e=>{var s,o,a;let t=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ud=e=>e.status==="complete"?yu(e):"Using tool...",Ns=e=>{let n=e/1e3;return n<.1?"<0.1s":n>=10?`${Math.round(n)}s`:`${n.toFixed(1).replace(/\.0$/,"")}s`},Go=e=>{var t,r,s;let n=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ns(n)},Fs=e=>{var t,r,s;let n=e.durationMs!==void 0?e.durationMs:Math.max(0,((t=e.completedAt)!=null?t:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return Ns(n)},Ra=(e,n,t)=>{var o;if(!n)return t;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Go(e);return n.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},Os=(e,n)=>{let t=e.replace(/\{toolName\}/g,n),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(t))!==null;)a.index>o&&Ko(r,t.slice(o,a.index),[]),a[1]!==void 0?Ko(r,a[1],["bold"]):a[2]!==void 0?Ko(r,a[2],["italic"]):a[3]!==void 0&&Ko(r,a[3],["dim"]),o=a.index+a[0].length;return o<t.length&&Ko(r,t.slice(o),[]),r},Ko=(e,n,t)=>{let r=n.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:t}),s<r.length-1&&e.push({text:"{duration}",styles:t,isDuration:!0})},bu=()=>{let e=null,n=0,t=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
|
|
3
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
4
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=n)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=t(r);return o!==null&&(e=o),n=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Jr=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},$s=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},_s=()=>{var n;let e=bu();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(n=e.close)==null?void 0:n.bind(e)}},js=()=>{let e=null,n=0;return{getExtractedText:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=(0,dr.parse)(t,dr.STR|dr.OBJ);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ds(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ds(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},md=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ds(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ds(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:()=>n,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=t)return n!==null?{text:n,raw:o}:null;try{let i=(0,dr.parse)(o,dr.STR|dr.OBJ),u=s(i);u!==null&&(n=u)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},zs=()=>{let e=null;return{processChunk:n=>{if(!n.trim().startsWith("<"))return null;let r=n.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:n}):null},getExtractedText:()=>e}};var qs=class{constructor(n,t=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=n,this.gapTimeoutMs=t}push(n,t){var o,a,i;let r=(i=(o=t==null?void 0:t.seq)!=null?o:t==null?void 0:t.sequenceIndex)!=null?i:(a=t==null?void 0:t.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(n,t);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(n,t),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(n,t);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${n}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:n,payload:t,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let n=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(n.payloadType,n.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let n=[...this.buffer.entries()].sort((t,r)=>t[0]-r[0]);for(let[t,r]of n)this.buffer.delete(t),this.emitter(r.payloadType,r.payload);n.length>0&&(this.nextExpectedSeq=n[n.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var xu="https://api.runtype.com/v1/dispatch",Ha="https://api.runtype.com",Ba=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 vu(e){switch(e){case"json":return js;case"regex-json":return _s;case"xml":return zs;default:return $s}}var gd=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Cu(e,n){if(!e)return n;let t=e.trim(),r=n.trim();if(t.length===0)return n;if(r.length===0)return e;let s=gd(t);if(!gd(r))return e;if(!s||r===t||r.startsWith(t))return n;let a=Jr(e);return Jr(n)!==null&&a===null?n:e}var Kr=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:xu,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:vu(n.parserType),this.contextProviders=(s=n.contextProviders)!=null?s:[],this.requestMiddleware=n.requestMiddleware,this.customFetch=n.customFetch,this.parseSSEEvent=n.parseSSEEvent,this.getHeaders=n.getHeaders}setSSEEventCallback(n){this.onSSEEvent=n}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(n){var r;let t=((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha;return n==="init"?`${t}/v1/client/init`:`${t}/v1/client/chat`}getClientSession(){return this.clientSession}async initSession(){var n,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,(t=(n=this.config).onSessionInit)==null||t.call(n,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let n=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,t={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...n&&{sessionId:n}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.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$/,""))||Ha}/v1/client/feedback`}async sendFeedback(n){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(n.type)&&!n.messageId)throw new Error(`messageId is required for ${n.type} feedback type`);if(n.type==="csat"&&(n.rating===void 0||n.rating<1||n.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(n.type==="nps"&&(n.rating===void 0||n.rating<0||n.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",n);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});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(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:n,type:t})}async submitCSATFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:n,comment:t})}async submitNPSFeedback(n,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:n,comment:t})}async dispatch(n,t){return this.isAgentMode()?this.dispatchAgent(n,t):this.isClientTokenMode()?this.dispatchClientToken(n,t):this.dispatchProxy(n,t)}async dispatchClientToken(n,t){var s,o,a,i;let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let u=await this.initSession();if(new Date>=new Date(u.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let g=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:g}),g}let c=await this.buildPayload(n.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([g])=>g!=="sessionId"&&g!=="session_id")):void 0,d={sessionId:u.sessionId,messages:n.messages.filter(Ba).map(g=>{var x,E,v;return{id:g.id,role:g.role,content:(v=(E=(x=g.contentParts)!=null?x:g.llmContent)!=null?E:g.rawContent)!=null?v:g.content}}),...n.assistantMessageId&&{assistantMessageId:n.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",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:r.signal});if(!f.ok){let g=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 E=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:E}),E}if(f.status===429){let E=new Error(g.hint||"Message limit reached for this session.");throw t({type:"error",error:E}),E}let x=new Error(g.error||"Failed to send message");throw t({type:"error",error:x}),x}if(!f.body){let g=new Error("No response body received");throw t({type:"error",error:g}),g}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(u){let c=u instanceof Error?u:new Error(String(u));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(n.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:r.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(n.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:r.signal},s)}catch(i){let u=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:u}),u}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(n,t,r){t({type:"status",status:"connected"});try{await this.streamResponse(n,t,r)}finally{t({type:"status",status:"idle"})}}async resolveApproval(n,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/agents/${n.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:n.executionId,approvalId:n.approvalId,decision:t,streamResponse:!0})})}async buildAgentPayload(n){if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let t=n.slice().filter(Ba).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}}),r={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:n,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&&(r.context=s)}return r}async buildPayload(n){let r={messages:n.slice().filter(Ba).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:n,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&&(r.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...r},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return r}async handleCustomSSEEvent(n,t,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(n);if(i===null)return!1;let u=p=>{let d={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 r.current=d,s(d),d},c=p=>r.current?r.current:u(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),u(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&&(r.current&&(r.current.streaming=!1,s(r.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(n,t,r){var fe,Ke,Bt,Dt;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),u=0,c=()=>i+u++,p=W=>{let re=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,Ie=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Oe=W.tools?W.tools.map(Je=>({...Je,chunks:Je.chunks?[...Je.chunks]:void 0})):void 0;return{...W,reasoning:re,toolCall:Ie,tools:Oe}},d=W=>{t({type:"message",message:p(W)})},f=null,g={current:null},x={current:null},E=!1,v=new Map,w=new Map,I=new Map,j=new Map,A={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},T=(W,re,Ie="")=>`${W}::${re}::${Ie}`,P=(W,re)=>`${W}::${re}::`,H=(W,re,Ie,Oe)=>{let Je=T(W,re,Ie),Ye=I.get(Je);if(Ye)return Ye;let L=Ie?`-${Ie}`:"",ve={id:`nested-${W}-${re}${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),...Ie?{partId:Ie}:{},agentMetadata:{executionId:Oe,parentToolId:W,parentStepId:re}};return I.set(Je,ve),d(ve),ve},J=W=>{if(W==null)return null;try{return String(W)}catch{return null}},U=W=>{var re,Ie,Oe,Je,Ye;return J((Ye=(Je=(Oe=(Ie=(re=W.stepId)!=null?re:W.step_id)!=null?Ie:W.step)!=null?Oe:W.parentId)!=null?Je:W.flowStepId)!=null?Ye:W.flow_step_id)},$=W=>{var re,Ie,Oe,Je,Ye,L,ve;return J((ve=(L=(Ye=(Je=(Oe=(Ie=(re=W.callId)!=null?re:W.call_id)!=null?Ie:W.requestId)!=null?Oe:W.request_id)!=null?Je:W.toolCallId)!=null?Ye:W.tool_call_id)!=null?L:W.stepId)!=null?ve:W.step_id)},ie=r,be=!1,pe=()=>{if(f)return f;let W;return!be&&ie?(W=ie,be=!0):ie&&x.current?W=`${ie}_${x.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},d(f),f},Ne=(W,re)=>{A.lastId=re,W&&A.byStep.set(W,re)},me=(W,re)=>{var Ye;let Ie=(Ye=W.reasoningId)!=null?Ye:W.id,Oe=U(W);if(Ie){let L=String(Ie);return Ne(Oe,L),L}if(Oe){let L=A.byStep.get(Oe);if(L)return A.lastId=L,L}if(A.lastId&&!re)return A.lastId;if(!re)return null;let Je=`reason-${c()}`;return Ne(Oe,Je),Je},Re=W=>{let re=v.get(W);if(re)return re;let Ie={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:W,status:"streaming",chunks:[]}};return v.set(W,Ie),d(Ie),Ie},Ee=(W,re)=>{R.lastId=re,W&&R.byCall.set(W,re)},He=new Set,de=new Map,Q=new Set,he=new Map,X=W=>{if(!W)return!1;let re=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return re==="emit_artifact_markdown"||re==="emit_artifact_component"},ge=(W,re)=>{var Ye;let Ie=(Ye=W.toolId)!=null?Ye:W.id,Oe=$(W);if(Ie){let L=String(Ie);return Ee(Oe,L),L}if(Oe){let L=R.byCall.get(Oe);if(L)return R.lastId=L,L}if(R.lastId&&!re)return R.lastId;if(!re)return null;let Je=`tool-${c()}`;return Ee(Oe,Je),Je},ue=W=>{let re=w.get(W);if(re)return re;let Ie={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:W,status:"pending"}};return w.set(W,Ie),d(Ie),Ie},oe=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let re=Number(W);if(!Number.isNaN(re)&&Number.isFinite(re))return re;let Ie=Date.parse(W);if(!Number.isNaN(Ie))return Ie}return Date.now()},Te=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Me=new Map,k=new Map,V=new Map,ae=new Map,D=null,q=(W,re,Ie)=>{var ve;let Oe=V.get(W);Oe||(Oe=[],V.set(W,Oe));let Je=0,Ye=Oe.length;for(;Je<Ye;){let De=Je+Ye>>>1;Oe[De].seq<re?Je=De+1:Ye=De}((ve=Oe[Je])==null?void 0:ve.seq)===re?Oe[Je]={seq:re,text:Ie}:Oe.splice(Je,0,{seq:re,text:Ie});let L="";for(let De=0;De<Oe.length;De++)L+=Oe[De].text;return L},le=(W,re)=>{let Ie=Te(re),Oe=k.get(W.id),Je=Cu(Oe,Ie);W.rawContent=Je;let Ye=Me.get(W.id),L=ne=>{var lt;let _e=(lt=W.content)!=null?lt:"";ne.trim()!==""&&(_e.trim().length===0||ne.startsWith(_e)||ne.trimStart().startsWith(_e.trim()))&&(W.content=ne)},ve=()=>{var ne;if(Ye){let _e=(ne=Ye.close)==null?void 0:ne.call(Ye);_e instanceof Promise&&_e.catch(()=>{})}Me.delete(W.id),k.delete(W.id),W.streaming=!1,d(W)};if(!Ye){L(Ie),ve();return}let De=Jr(Je);if(De!==null&&De.trim()!==""){L(De),ve();return}let it=ne=>{var Rt;let _e=typeof ne=="string"?ne:(Rt=ne==null?void 0:ne.text)!=null?Rt:null;if(_e!==null&&_e.trim()!=="")return _e;let lt=Ye.getExtractedText();return lt!==null&<.trim()!==""?lt:Ie},Z;try{Z=Ye.processChunk(Je)}catch{L(Ie),ve();return}if(Z instanceof Promise){Z.then(ne=>{L(it(ne)),ve()}).catch(()=>{L(Ie),ve()});return}L(it(Z)),ve()},xe=[],ee=!1,se,Et=()=>{ee||(ee=!0,queueMicrotask(()=>{ee=!1,se()}))},ht=new qs((W,re)=>{xe.push({payloadType:W,payload:re}),Et()}),Ve=null,Xt=new Map,Qe=(fe=this.config.iterationDisplay)!=null?fe:"separate";for(se=()=>{var W,re,Ie,Oe,Je,Ye,L,ve,De,it,Z,ne,_e,lt,Rt,Zt,mt,pt,at,Ce,rt,je,Qt,en,Wn,tn,et,fr,wn,Rr,Rn,ro,hr,nr,gt,Sn,jn,dn,yr,An,Mt,pn,Hn,br,rr,xr,Xn,En,Zn,wt,$t,_t,Tn,vr,Bn,zn,Mn,O,qn,Dn,Cr,ce,un,kn,or,Hr,ys,To,bs,oo,ct,Mo,Nn,fn,xs,vs,ko,sr,Cs,Br,Lo,ar,Io,wr,Sr,ws,Ss,Ma,Dr,Nr,Nt,so,ao,Po,Qn,As,Wo,Ro,Ho,mn,Ln,ir,tt,Bo,Fr,Vn,Es,io,lo,Or,Ar,Ts,Ms,Un,$r,ks,Ls,lr,Ft,Ot,Er,Do,No,Fo,Oo,$o,ka,_o,Tr,co;for(let Jn=0;Jn<xe.length;Jn++){let ze=xe[Jn].payloadType,b=xe[Jn].payload;if(ze==="reason_start"){let N=(W=me(b,!0))!=null?W:`reason-${c()}`,C=Re(N);C.reasoning=(re=C.reasoning)!=null?re:{id:N,status:"streaming",chunks:[]},C.reasoning.startedAt=(Oe=C.reasoning.startedAt)!=null?Oe:oe((Ie=b.startedAt)!=null?Ie:b.timestamp),C.reasoning.completedAt=void 0,C.reasoning.durationMs=void 0,C.streaming=!0,C.reasoning.status="streaming",d(C)}else if(ze==="reason_delta"||ze==="reason_chunk"){let N=(Ye=(Je=me(b,!1))!=null?Je:me(b,!0))!=null?Ye:`reason-${c()}`,C=Re(N);C.reasoning=(L=C.reasoning)!=null?L:{id:N,status:"streaming",chunks:[]},C.reasoning.startedAt=(De=C.reasoning.startedAt)!=null?De:oe((ve=b.startedAt)!=null?ve:b.timestamp);let Y=(ne=(Z=(it=b.reasoningText)!=null?it:b.text)!=null?Z:b.delta)!=null?ne:"";if(Y&&b.hidden!==!0){let Ae=typeof b.sequenceIndex=="number"?b.sequenceIndex:void 0;if(Ae!==void 0){let te=q(N,Ae,String(Y));C.reasoning.chunks=[te]}else C.reasoning.chunks.push(String(Y))}if(C.reasoning.status=b.done?"complete":"streaming",b.done){C.reasoning.completedAt=oe((_e=b.completedAt)!=null?_e:b.timestamp);let Ae=(lt=C.reasoning.startedAt)!=null?lt:Date.now();C.reasoning.durationMs=Math.max(0,((Rt=C.reasoning.completedAt)!=null?Rt:Date.now())-Ae)}C.streaming=C.reasoning.status!=="complete",d(C)}else if(ze==="reason_complete"){let N=(mt=(Zt=me(b,!1))!=null?Zt:me(b,!0))!=null?mt:`reason-${c()}`,C=v.get(N);if(C!=null&&C.reasoning){C.reasoning.status="complete",C.reasoning.completedAt=oe((pt=b.completedAt)!=null?pt:b.timestamp);let Ae=(at=C.reasoning.startedAt)!=null?at:Date.now();C.reasoning.durationMs=Math.max(0,((Ce=C.reasoning.completedAt)!=null?Ce:Date.now())-Ae),C.streaming=!1,d(C)}let Y=U(b);Y&&A.byStep.delete(Y)}else if(ze==="tool_start"){let N=(rt=ge(b,!0))!=null?rt:`tool-${c()}`,C=(je=b.toolName)!=null?je:b.name;if(X(C)){He.add(N);continue}let Y=ue(N),Ae=(Qt=Y.toolCall)!=null?Qt:{id:N,status:"pending"};Ae.name=C!=null?C:Ae.name,Ae.status="running",b.args!==void 0?Ae.args=b.args:b.parameters!==void 0&&(Ae.args=b.parameters),Ae.startedAt=(Wn=Ae.startedAt)!=null?Wn:oe((en=b.startedAt)!=null?en:b.timestamp),Ae.completedAt=void 0,Ae.durationMs=void 0,Y.toolCall=Ae,Y.streaming=!0;let te=b.agentContext;(te||b.executionId)&&(Y.agentMetadata={executionId:(tn=te==null?void 0:te.executionId)!=null?tn:b.executionId,iteration:(et=te==null?void 0:te.iteration)!=null?et:b.iteration}),d(Y)}else if(ze==="tool_chunk"||ze==="tool_delta"){let N=(wn=(fr=ge(b,!1))!=null?fr:ge(b,!0))!=null?wn:`tool-${c()}`;if(He.has(N))continue;let C=ue(N),Y=(Rr=C.toolCall)!=null?Rr:{id:N,status:"running"};Y.startedAt=(ro=Y.startedAt)!=null?ro:oe((Rn=b.startedAt)!=null?Rn:b.timestamp);let Ae=(gt=(nr=(hr=b.text)!=null?hr:b.delta)!=null?nr:b.message)!=null?gt:"";Ae&&(Y.chunks=(Sn=Y.chunks)!=null?Sn:[],Y.chunks.push(String(Ae))),Y.status="running",C.toolCall=Y,C.streaming=!0;let te=b.agentContext;(te||b.executionId)&&(C.agentMetadata=(yr=C.agentMetadata)!=null?yr:{executionId:(jn=te==null?void 0:te.executionId)!=null?jn:b.executionId,iteration:(dn=te==null?void 0:te.iteration)!=null?dn:b.iteration}),d(C)}else if(ze==="tool_complete"){let N=(Mt=(An=ge(b,!1))!=null?An:ge(b,!0))!=null?Mt:`tool-${c()}`;if(He.has(N)){He.delete(N);continue}let C=ue(N),Y=(pn=C.toolCall)!=null?pn:{id:N,status:"running"};Y.status="complete",b.result!==void 0&&(Y.result=b.result),typeof b.duration=="number"&&(Y.duration=b.duration),Y.completedAt=oe((Hn=b.completedAt)!=null?Hn:b.timestamp);let Ae=(br=b.duration)!=null?br:b.executionTime;if(typeof Ae=="number")Y.durationMs=Ae;else{let we=(rr=Y.startedAt)!=null?rr:Date.now();Y.durationMs=Math.max(0,((xr=Y.completedAt)!=null?xr:Date.now())-we)}C.toolCall=Y,C.streaming=!1;let te=b.agentContext;(te||b.executionId)&&(C.agentMetadata=(Zn=C.agentMetadata)!=null?Zn:{executionId:(Xn=te==null?void 0:te.executionId)!=null?Xn:b.executionId,iteration:(En=te==null?void 0:te.iteration)!=null?En:b.iteration}),d(C);let Ze=$(b);Ze&&R.byCall.delete(Ze)}else if(ze==="text_start"){if((wt=b.toolContext)!=null&&wt.toolId)continue;let N=b.partId;if(N!==void 0&&x.current!==null&&N!==x.current){let C=f;C&&(C.streaming=!1,d(C),D=C,f=null,E=!0)}N!==void 0&&(x.current=N)}else if(ze==="text_end"){if(($t=b.toolContext)!=null&&$t.toolId)continue;let N=f;N&&(N.streaming=!1,d(N),D=N,f=null,E=!0)}else if(ze==="step_chunk"||ze==="step_delta"){let N=b.stepType,C=b.executionType;if(N==="tool"||C==="context")continue;let Y=b.toolContext;if(Y!=null&&Y.toolId){let we=String((Tn=(_t=b.id)!=null?_t:Y.stepId)!=null?Tn:`step-${c()}`),Lt=b.partId!==void 0&&b.partId!==null?String(b.partId):"",Xe=`${Y.toolId}::${we}`,St=j.get(Xe);if(Lt!==""&&St!==void 0&&St!==""&&St!==Lt){let bt=I.get(T(Y.toolId,we,St));bt&&bt.streaming!==!1&&(bt.streaming=!1,d(bt))}Lt!==""&&j.set(Xe,Lt);let It=H(Y.toolId,we,Lt,Y.executionId),Kt=(Mn=(zn=(Bn=(vr=b.text)!=null?vr:b.delta)!=null?Bn:b.content)!=null?zn:b.chunk)!=null?Mn:"";Kt&&(It.content+=String(Kt),It.streaming=!0,d(It)),b.isComplete&&(It.streaming=!1,d(It));continue}let Ae=b.partId;if(Ae!==void 0&&x.current!==null&&Ae!==x.current){let we=f;we&&(we.streaming=!1,d(we),D=we,f=null,E=!0)}Ae!==void 0&&(x.current=Ae);let te=Ae!==void 0&&(O=ae.get(Ae))!=null?O:pe();Ae!==void 0&&(te.partId||(te.partId=Ae),ae.set(Ae,te));let Ze=(ce=(Cr=(Dn=(qn=b.text)!=null?qn:b.delta)!=null?Dn:b.content)!=null?Cr:b.chunk)!=null?ce:"";if(Ze){let we=typeof b.seq=="number"?b.seq:void 0,Lt=Ae!=null?Ae:te.id,Xe=we!==void 0?q(Lt,we,String(Ze)):((un=k.get(te.id))!=null?un:"")+Ze;te.rawContent=Xe,Me.has(te.id)||Me.set(te.id,this.createStreamParser());let St=Me.get(te.id),It=Xe.trim().startsWith("{")||Xe.trim().startsWith("[");if(It&&k.set(te.id,Xe),St.__isPlainTextParser===!0){te.content=we!==void 0?Xe:te.content+Ze,k.delete(te.id),Me.delete(te.id),te.rawContent=void 0,d(te);continue}let bt=St.processChunk(Xe);if(bt instanceof Promise)bt.then(At=>{var sn;let Gt=typeof At=="string"?At:(sn=At==null?void 0:At.text)!=null?sn:null;if(Gt!==null&&Gt.trim()!=="")te.content=Gt,d(te);else if(!It&&!Xe.trim().startsWith("<")){let nn=f,jt=nn&&nn.id===te.id?nn:te;jt.id===te.id&&(jt.content=we!==void 0?Xe:jt.content+Ze,k.delete(jt.id),Me.delete(jt.id),jt.rawContent=void 0,d(jt))}}).catch(()=>{te.content=we!==void 0?Xe:te.content+Ze,k.delete(te.id),Me.delete(te.id),te.rawContent=void 0,d(te)});else{let At=typeof bt=="string"?bt:(kn=bt==null?void 0:bt.text)!=null?kn:null;At!==null&&At.trim()!==""?(te.content=At,d(te)):!It&&!Xe.trim().startsWith("<")&&(te.content=we!==void 0?Xe:te.content+Ze,k.delete(te.id),Me.delete(te.id),te.rawContent=void 0,d(te))}}if(b.isComplete){let we=(Hr=(or=b.result)==null?void 0:or.response)!=null?Hr:te.content;if(we){let Lt=k.get(te.id),Xe=Lt!=null?Lt:Te(we);te.rawContent=Xe;let St=Me.get(te.id),It=null,Kt=!1;if(St&&(It=St.getExtractedText(),It===null&&(It=Jr(Xe)),It===null)){let bt=St.processChunk(Xe);bt instanceof Promise?(Kt=!0,bt.then(At=>{var sn;let Gt=typeof At=="string"?At:(sn=At==null?void 0:At.text)!=null?sn:null;if(Gt!==null){let nn=f;nn&&nn.id===te.id&&(nn.content=Gt,nn.streaming=!1,Me.delete(nn.id),k.delete(nn.id),d(nn))}})):It=typeof bt=="string"?bt:(ys=bt==null?void 0:bt.text)!=null?ys:null}if(!Kt){It!==null&&It.trim()!==""?te.content=It:k.has(te.id)||(te.content=Te(we));let bt=Me.get(te.id);if(bt){let At=(To=bt.close)==null?void 0:To.call(bt);At instanceof Promise&&At.catch(()=>{}),Me.delete(te.id)}k.delete(te.id),te.streaming=!1,d(te)}}}}else if(ze==="step_complete"){let N=b.stepType,C=b.executionType;if(N==="tool"||C==="context")continue;let Y=b.toolContext;if(Y!=null&&Y.toolId){let we=String((oo=(bs=b.id)!=null?bs:Y.stepId)!=null?oo:"");if(we){let Lt=P(Y.toolId,we);for(let[Xe,St]of I)Xe.startsWith(Lt)&&St.streaming!==!1&&(St.streaming=!1,d(St));j.delete(`${Y.toolId}::${we}`)}continue}let Ae=b.stopReason;if(E){if(f!==null){let Xe=f;Ae&&(Xe.stopReason=Ae),Me.delete(Xe.id),k.delete(Xe.id),Xe.streaming!==!1&&(Xe.streaming=!1,d(Xe))}let we=(ct=b.result)==null?void 0:ct.response,Lt=D;Lt&&(Ae&&(Lt.stopReason=Ae),we!=null?le(Lt,we):(Me.delete(Lt.id),k.delete(Lt.id))),D=null;continue}let te=(Mo=b.result)==null?void 0:Mo.response,Ze=pe();if(Ae&&(Ze.stopReason=Ae),te!=null){let we=Me.get(Ze.id),Lt=!1,Xe=!1;if(we){let St=we.getExtractedText(),It=k.get(Ze.id),Kt=It!=null?It:Te(te);if(Ze.rawContent=Kt,St!==null&&St.trim()!=="")Ze.content=St,Lt=!0;else{let bt=Jr(Kt);if(bt!==null)Ze.content=bt,Lt=!0;else{let At=we.processChunk(Kt);if(At instanceof Promise)Xe=!0,At.then(Gt=>{var nn;let sn=typeof Gt=="string"?Gt:(nn=Gt==null?void 0:Gt.text)!=null?nn:null;if(sn!==null&&sn.trim()!==""){let jt=f;jt&&jt.id===Ze.id&&(jt.content=sn,jt.streaming=!1,Me.delete(jt.id),k.delete(jt.id),d(jt))}else{let jt=we.getExtractedText(),Fn=f;Fn&&Fn.id===Ze.id&&(jt!==null&&jt.trim()!==""?Fn.content=jt:k.has(Fn.id)||(Fn.content=Te(te)),Fn.streaming=!1,Me.delete(Fn.id),k.delete(Fn.id),d(Fn))}});else{let Gt=typeof At=="string"?At:(Nn=At==null?void 0:At.text)!=null?Nn:null;if(Gt!==null&&Gt.trim()!=="")Ze.content=Gt,Lt=!0;else{let sn=we.getExtractedText();sn!==null&&sn.trim()!==""&&(Ze.content=sn,Lt=!0)}}}}}if(!Xe){if(!Ze.rawContent){let St=k.get(Ze.id);Ze.rawContent=St!=null?St:Te(te)}if(!Lt&&!k.has(Ze.id)&&(Ze.content=Te(te)),we){let St=(fn=we.close)==null?void 0:fn.call(we);St instanceof Promise&&St.catch(()=>{})}Me.delete(Ze.id),k.delete(Ze.id),Ze.streaming=!1,d(Ze)}}else Me.delete(Ze.id),k.delete(Ze.id),Ze.streaming=!1,d(Ze)}else if(ze==="flow_complete"){let N=(xs=b.result)==null?void 0:xs.response;if(E){if(f!==null){let C=f;Me.delete(C.id),k.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}}else if(N!=null){let C=pe(),Y=k.get(C.id),Ae=Y!=null?Y:Te(N);C.rawContent=Ae;let te=Te(N),Ze=Me.get(C.id);if(Ze){let Xe=Jr(Ae);if(Xe!==null)te=Xe;else{let St=Ze.processChunk(Ae);St instanceof Promise&&St.then(Kt=>{var At;let bt=typeof Kt=="string"?Kt:(At=Kt==null?void 0:Kt.text)!=null?At:null;bt!==null&&(C.content=bt,C.streaming=!1,d(C))});let It=Ze.getExtractedText();It!==null&&(te=It)}}Me.delete(C.id),k.delete(C.id);let we=te!==C.content,Lt=C.streaming!==!1;we&&(C.content=te),C.streaming=!1,(we||Lt)&&d(C)}else if(f!==null){let C=f;Me.delete(C.id),k.delete(C.id),C.streaming!==!1&&(C.streaming=!1,d(C))}t({type:"status",status:"idle"})}else if(ze==="agent_start")Ve={executionId:b.executionId,agentId:(vs=b.agentId)!=null?vs:"virtual",agentName:(ko=b.agentName)!=null?ko:"",status:"running",currentIteration:0,maxTurns:(sr=b.maxTurns)!=null?sr:1,startedAt:oe(b.startedAt)};else if(ze==="agent_iteration_start"){if(Ve&&(Ve.currentIteration=b.iteration),Qe==="separate"&&b.iteration>1){let N=f;N&&(N.streaming=!1,d(N),Xt.set(b.iteration-1,N),f=null)}}else if(ze!=="agent_turn_start"){if(ze==="agent_turn_delta"){if(b.contentType==="text"){let N=pe();N.content+=(Cs=b.delta)!=null?Cs:"",N.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:Ve==null?void 0:Ve.agentName},d(N)}else if(b.contentType==="thinking"){let N=(Br=b.turnId)!=null?Br:`agent-think-${b.iteration}`,C=Re(N);C.reasoning=(Lo=C.reasoning)!=null?Lo:{id:N,status:"streaming",chunks:[]},C.reasoning.chunks.push((ar=b.delta)!=null?ar:""),C.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},d(C)}else if(b.contentType==="tool_input"){let N=(Io=b.toolCallId)!=null?Io:R.lastId;if(N){let C=w.get(N);C!=null&&C.toolCall&&(C.toolCall.chunks=(wr=C.toolCall.chunks)!=null?wr:[],C.toolCall.chunks.push((Sr=b.delta)!=null?Sr:""),d(C))}}}else if(ze==="agent_turn_complete"){let N=b.turnId;if(N){let Y=v.get(N);if(Y!=null&&Y.reasoning){Y.reasoning.status="complete",Y.reasoning.completedAt=oe(b.completedAt);let Ae=(ws=Y.reasoning.startedAt)!=null?ws:Date.now();Y.reasoning.durationMs=Math.max(0,((Ss=Y.reasoning.completedAt)!=null?Ss:Date.now())-Ae),Y.streaming=!1,d(Y)}}let C=b.stopReason;if(C&&f!==null){let Y=b.turnId;(!Y||((Ma=f.agentMetadata)==null?void 0:Ma.turnId)===Y)&&(f.stopReason=C,d(f))}}else if(ze==="agent_tool_start"){let N=(Dr=b.toolCallId)!=null?Dr:`agent-tool-${c()}`;Ee($(b),N);let C=ue(N),Y=(Nr=C.toolCall)!=null?Nr:{id:N,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};Y.name=(so=(Nt=b.toolName)!=null?Nt:b.name)!=null?so:Y.name,Y.status="running",b.parameters!==void 0&&(Y.args=b.parameters),Y.startedAt=oe((ao=b.startedAt)!=null?ao:b.timestamp),C.toolCall=Y,C.streaming=!0,C.agentMetadata={executionId:b.executionId,iteration:b.iteration},d(C)}else if(ze==="agent_tool_delta"){let N=(Po=b.toolCallId)!=null?Po:R.lastId;if(N){let C=(Qn=w.get(N))!=null?Qn:ue(N);C.toolCall&&(C.toolCall.chunks=(As=C.toolCall.chunks)!=null?As:[],C.toolCall.chunks.push((Wo=b.delta)!=null?Wo:""),C.toolCall.status="running",C.streaming=!0,d(C))}}else if(ze==="agent_tool_complete"){let N=(Ro=b.toolCallId)!=null?Ro:R.lastId;if(N){let C=(Ho=w.get(N))!=null?Ho:ue(N);if(C.toolCall){C.toolCall.status="complete",b.result!==void 0&&(C.toolCall.result=b.result),typeof b.executionTime=="number"&&(C.toolCall.durationMs=b.executionTime),C.toolCall.completedAt=oe((mn=b.completedAt)!=null?mn:b.timestamp),C.streaming=!1,d(C);let Y=$(b);Y&&R.byCall.delete(Y)}}}else if(ze!=="agent_iteration_complete"){if(ze==="agent_reflection"||ze==="agent_reflect"){let N=`agent-reflection-${b.executionId}-${b.iteration}`,C={id:N,role:"assistant",content:(Ln=b.reflection)!=null?Ln:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:N,status:"complete",chunks:[(ir=b.reflection)!=null?ir:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};d(C)}else if(ze==="agent_complete"){Ve&&(Ve.status=b.success?"complete":"error",Ve.completedAt=oe(b.completedAt),Ve.stopReason=b.stopReason);let N=f;N&&(N.streaming=!1,d(N)),t({type:"status",status:"idle"})}else if(ze==="agent_error"){let N=typeof b.error=="string"?b.error:(Bo=(tt=b.error)==null?void 0:tt.message)!=null?Bo:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",N):t({type:"error",error:new Error(N)})}else if(ze!=="agent_ping"){if(ze==="agent_approval_start"){let N=(Fr=b.approvalId)!=null?Fr:`approval-${c()}`,C={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:N,status:"pending",agentId:(Vn=Ve==null?void 0:Ve.agentId)!=null?Vn:"virtual",executionId:(io=(Es=b.executionId)!=null?Es:Ve==null?void 0:Ve.executionId)!=null?io:"",toolName:(lo=b.toolName)!=null?lo:"",toolType:b.toolType,description:(Ar=b.description)!=null?Ar:`Execute ${(Or=b.toolName)!=null?Or:"tool"}`,parameters:b.parameters}};d(C)}else if(ze==="step_await"&&b.awaitReason==="approval_required"){let N=(Ts=b.approvalId)!=null?Ts:`approval-${c()}`,C={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:N,status:"pending",agentId:(Ms=Ve==null?void 0:Ve.agentId)!=null?Ms:"virtual",executionId:($r=(Un=b.executionId)!=null?Un:Ve==null?void 0:Ve.executionId)!=null?$r:"",toolName:(ks=b.toolName)!=null?ks:"",toolType:b.toolType,description:(lr=b.description)!=null?lr:`Execute ${(Ls=b.toolName)!=null?Ls:"tool"}`,parameters:b.parameters}};d(C)}else if(ze==="agent_approval_complete"){let N=b.approvalId;if(N){let Y={id:`approval-${N}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:N,status:(Ft=b.decision)!=null?Ft:"approved",agentId:(Ot=Ve==null?void 0:Ve.agentId)!=null?Ot:"virtual",executionId:(Do=(Er=b.executionId)!=null?Er:Ve==null?void 0:Ve.executionId)!=null?Do:"",toolName:(No=b.toolName)!=null?No:"",description:(Fo=b.description)!=null?Fo:"",resolvedAt:Date.now()}};d(Y)}}else if(ze==="artifact_start"||ze==="artifact_delta"||ze==="artifact_update"||ze==="artifact_complete"){if(ze==="artifact_start"){let N=b.artifactType,C=String(b.id),Y=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:C,artifactType:N,title:Y,component:typeof b.component=="string"?b.component:void 0}),he.set(C,{markdown:"",title:Y}),!Q.has(C)){Q.add(C);let Ae={id:`artifact-ref-${C}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:C,title:Y,artifactType:N,status:"streaming"}})};de.set(C,Ae),d(Ae)}}else if(ze==="artifact_delta"){let N=String(b.id),C=typeof b.delta=="string"?b.delta:String((Oo=b.delta)!=null?Oo:"");t({type:"artifact_delta",id:N,artDelta:C});let Y=he.get(N);Y&&(Y.markdown+=C)}else if(ze==="artifact_update"){let N=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:N,component:typeof b.component=="string"?b.component:void 0})}else if(ze==="artifact_complete"){let N=String(b.id);t({type:"artifact_complete",id:N});let C=de.get(N);if(C){C.streaming=!1;try{let Y=JSON.parse(($o=C.rawContent)!=null?$o:"{}");if(Y.props){Y.props.status="complete";let Ae=he.get(N);Ae!=null&&Ae.markdown&&(Y.props.markdown=Ae.markdown)}C.rawContent=JSON.stringify(Y)}catch{}he.delete(N),d(C),de.delete(N)}}}else if(ze==="transcript_insert"){let N=b.message;if(!N||typeof N!="object")continue;let C=String((ka=N.id)!=null?ka:`msg-${c()}`),Y=N.role,te={id:C,role:Y==="user"?"user":Y==="system"?"system":"assistant",content:typeof N.content=="string"?N.content:"",rawContent:typeof N.rawContent=="string"?N.rawContent:void 0,createdAt:typeof N.createdAt=="string"?N.createdAt:new Date().toISOString(),streaming:N.streaming===!0,...typeof N.variant=="string"?{variant:N.variant}:{},sequence:c()};if(d(te),te.rawContent)try{let Ze=JSON.parse(te.rawContent),we=(_o=Ze==null?void 0:Ze.props)==null?void 0:_o.artifactId;typeof we=="string"&&Q.add(we)}catch{}f=null,g.current=null,Me.delete(C),k.delete(C)}else if(ze==="error"||ze==="step_error"||ze==="dispatch_error"||ze==="flow_error"){let N=null;if(b.error instanceof Error)N=b.error;else if(ze==="dispatch_error"){let C=(Tr=b.message)!=null?Tr:b.error;C!=null&&C!==""&&(N=new Error(String(C)))}else if(ze==="step_error"||ze==="flow_error"){let C=b.error;typeof C=="string"&&C!==""?N=new Error(C):C!=null&&typeof C=="object"&&"message"in C&&(N=new Error(String((co=C.message)!=null?co:C)))}else ze==="error"&&b.error!=null&&b.error!==""&&(N=new Error(String(b.error)));if(N){t({type:"error",error:N});let C=f;C&&C.streaming&&(C.streaming=!1,d(C)),t({type:"status",status:"idle"})}}}}}}xe.length=0};;){let{done:W,value:re}=await s.read();if(W)break;a+=o.decode(re,{stream:!0});let Ie=a.split(`
|
|
5
5
|
|
|
6
|
-
`);a=(
|
|
7
|
-
`),Ce="message",be="";for(let At of Fe)At.startsWith("event:")?Ce=At.replace("event:","").trim():At.startsWith("data:")&&(be+=At.replace("data:","").trim());if(!be)continue;let at;try{at=JSON.parse(be)}catch(At){t({type:"error",error:At instanceof Error?At:new Error("Failed to parse chat stream payload")});continue}let mt=Ce!=="message"?Ce:(Wt=at.type)!=null?Wt:"message";if((Gt=this.onSSEEvent)==null||Gt.call(this,mt,at),this.parseSSEEvent){g.current=f;let At=await this.handleCustomSSEEvent(at,t,g,d,c,x);if(g.current&&g.current!==f&&(f=g.current),At)continue}ce.push(mt,at),N()}}ce.flushPending(),N(),ce.destroy()}};function rd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function so(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function $r(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var ks="[Image]";function od(e){return typeof e=="string"?[{type:"text",text:e}]:e}function sd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function ad(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function id(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function Bo(e){return{type:"text",text:e}}function ld(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 cd(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 dd(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 pd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],eu=["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"],sr=[...pd,...eu];function tu(e){return pd.includes(e)||e.startsWith("image/")}function Ls(e){return tu(e.type)}async function ud(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ls(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 md(e,r=sr,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 nu(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function gd(e,r){let t=nu(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 Is=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 u=new Uint8Array(this.remainder.length+r.length);u.set(this.remainder),u.set(r,this.remainder.length),t=u,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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,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 Ps=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 u=Math.sqrt(i/a.length);(n==="silence"?u<s.threshold:u>=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 Do=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 Ps;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,u=(n=this.config)==null?void 0:n.clientToken;if(!i||!u)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=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,T=S=>{x||(x=!0,clearTimeout(C),g(new Error(S)))},C=setTimeout(()=>T("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(C),f())},{once:!0}),this.ws.addEventListener("error",()=>{T("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",S=>{if(!S.wasClean&&!x){let M=S.code!==1006?` (code ${S.code})`:"";T("WebSocket connection failed"+M+"."+d)}},{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 Is(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,u=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,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",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),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),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.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 _r=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(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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 jr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Do(e.runtype);case"browser":if(!_r.isSupported())throw new Error("Browser speech recognition not supported");return new _r(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function Ws(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jr({type:"runtype",runtype:e.runtype});if(_r.isSupported())return jr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function No(e){try{return Ws(e),!0}catch{return!1}}var ao=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,u;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"),(u=(i=this.callbacks).onError)==null||u.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 Or(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 No((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=jr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",u=(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,d,f,g,x,T;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}):(d=c.transcript)!=null&&d.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}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let C=(T=this.pendingVoiceAssistantMessageId)!=null?T:(x=[...this.messages].reverse().find(S=>S.role==="assistant"))==null?void 0:x.id;C&&this.ttsSpokenMessageIds.add(C)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.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,u,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:(u=r.runtype)==null?void 0:u.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 Or(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:u,streaming:c=!1,voiceProcessing:p}=r,f={id:a!=null?a:t==="user"?so():t==="assistant"?$r():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u: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:u,createdAt:c,sequence:p,streaming:d=!1}=n,g={id:u!=null?u:s==="user"?so():s==="assistant"?$r():`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:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,p,d,f,g;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=so(),o=$r(),a={id:s,role:"user",content:n||ks,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let T=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!T){let C={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(C)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,T||(x instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=$r();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):(u=(i=this.callbacks).onError)==null||u.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 u,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 d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);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(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}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 u,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=(u=t.sequence)!=null?u: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},Gn=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};var ru=Uc(require("lucide"),1),ye=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=ru[s];return o?ou(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 ou(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 u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var Rs={allowedTypes:sr,maxFileSize:10*1024*1024,maxFiles:4};function su(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function au(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 zr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Rs.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Rs.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Rs.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:Rs.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,u;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=md(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await ud(c),f=Ls(c)?URL.createObjectURL(c):null,g={id:su(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(u=>u.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=Ls(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=au(r.file.type),u=ye(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=gd(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=ye("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 fd=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Fo(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];fd(o)&&fd(s)?t[n]=Fo(o,s):t[n]=s}return t}var An="min(440px, calc(100vw - 24px))",Hs="440px",kt={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:An,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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"}},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 hd(e,r){if(!(!e&&!r))return e?r?Fo(e,r):e:r}function Bs(e){var r,t,n,s,o,a,i,u,c,p,d,f,g,x,T,C,S,M,H,w,L;return e?{...kt,...e,theme:hd(kt.theme,e.theme),darkTheme:hd(kt.darkTheme,e.darkTheme),launcher:{...kt.launcher,...e.launcher,dock:{...(r=kt.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=kt.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...kt.copy,...e.copy},sendButton:{...kt.sendButton,...e.sendButton},statusIndicator:{...kt.statusIndicator,...e.statusIndicator},voiceRecognition:{...kt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,Ee,ae,we;let W=(oe=kt.features)==null?void 0:oe.artifacts,E=(Ee=e.features)==null?void 0:Ee.artifacts,K=(ae=kt.features)==null?void 0:ae.scrollToBottom,Q=(we=e.features)==null?void 0:we.scrollToBottom,X=W===void 0&&E===void 0?void 0:{...W,...E,layout:{...W==null?void 0:W.layout,...E==null?void 0:E.layout}},O=K===void 0&&Q===void 0?void 0:{...K,...Q};return{...kt.features,...e.features,...O!==void 0?{scrollToBottom:O}:{},...X!==void 0?{artifacts:X}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:kt.suggestionChips,suggestionChipsConfig:{...kt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...kt.layout,...e.layout,header:{...(a=kt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=kt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=kt.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(T=(x=kt.layout)==null?void 0:x.messages)==null?void 0:T.timestamp,...(S=(C=e.layout)==null?void 0:C.messages)==null?void 0:S.timestamp}},slots:{...(M=kt.layout)==null?void 0:M.slots,...(H=e.layout)==null?void 0:H.slots}},markdown:{...kt.markdown,...e.markdown,options:{...(w=kt.markdown)==null?void 0:w.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...kt.messageActions,...e.messageActions}}:kt}var ya={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"}},ba={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"}},xa={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:An,maxWidth:Hs,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 Oo(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."))?Oo(e,n):n}function Ds(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let u=Oo(e,a);u!==void 0&&(r[i]={path:i,value:u,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 va(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 yd(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]=yd(o,s):t[n]=s}return t}function iu(e,r){return r?yd(e,r):e}function io(e,r={}){var s,o,a,i,u,c,p,d,f,g,x,T,C;let t={palette:ya,semantic:ba,components:xa},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,...(u=e==null?void 0:e.palette)==null?void 0:u.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=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(T=e==null?void 0:e.semantic)==null?void 0:T.spacing},typography:{...t.semantic.typography,...(C=e==null?void 0:e.semantic)==null?void 0:C.typography}},components:iu(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let S=va(n);if(!S.valid)throw new Error(`Theme validation failed: ${S.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let S of r.plugins)n=S.transform(n);return n}function Ns(e){var x,T,C,S,M,H,w,L,W,E,K,Q,X,O,oe,Ee,ae,we,$e,he,We,Re,ie,Z,me,V,re,He,ge,Be,st,z,U,se,N,J,ce,fe,te,pe,Lt,dt,Wt,Gt,P,$,ne,Pe,Fe,Ce,be,at,mt,At,j,xe,ue,Ze,qe,de,Te,Ve,vt,Ot,pt,$t,ht,Qe,yt,je,_t,zn,Kn,Rn,tt,Ar,qn,Er,En,Gr,cr,Xn,it,hn,Hn,nn,dr,yn,Et,rn,Tn,pr,Zn,ur,Un,bn,Vn,Ct,Bt,Dt,xn,mr,Bn,vn,D,Dn,Mn,gr,an,ln;let r=Ds(e),t={};for(let[le,Cn]of Object.entries(r)){let Qn=le.replace(/\./g,"-");t[`--persona-${Qn}`]=Cn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(C=t["--persona-semantic-colors-accent"])!=null?C:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(H=t["--persona-semantic-colors-container"])!=null?H: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"]=(W=t["--persona-semantic-colors-text-inverse"])!=null?W:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(E=t["--persona-semantic-colors-border"])!=null?E:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(K=t["--persona-semantic-colors-divider"])!=null?K:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(Q=t["--persona-components-voice-recording-indicator"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(X=t["--persona-components-voice-recording-background"])!=null?X:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(O=t["--persona-components-voice-processing-icon"])!=null?O:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(oe=t["--persona-components-voice-speaking-icon"])!=null?oe:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(ae=t["--persona-components-approval-requested-border"])!=null?ae:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(we=t["--persona-components-approval-requested-text"])!=null?we:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=($e=t["--persona-components-approval-approve-background"])!=null?$e: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"]=(We=t["--persona-components-attachment-image-background"])!=null?We:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(Re=t["--persona-components-attachment-image-border"])!=null?Re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ie=t["--persona-semantic-typography-fontFamily"])!=null?ie:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Z=t["--persona-semantic-typography-fontSize"])!=null?Z:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(me=t["--persona-semantic-typography-fontWeight"])!=null?me:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(V=t["--persona-semantic-typography-lineHeight"])!=null?V: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"]=(re=t["--persona-palette-radius-sm"])!=null?re:"0.125rem",t["--persona-radius-md"]=(He=t["--persona-palette-radius-md"])!=null?He:"0.375rem",t["--persona-radius-lg"]=(ge=t["--persona-palette-radius-lg"])!=null?ge:"0.5rem",t["--persona-radius-xl"]=(Be=t["--persona-palette-radius-xl"])!=null?Be:"0.75rem",t["--persona-radius-full"]=(st=t["--persona-palette-radius-full"])!=null?st:"9999px",t["--persona-launcher-radius"]=(U=(z=t["--persona-components-launcher-borderRadius"])!=null?z:t["--persona-palette-radius-full"])!=null?U:"9999px",t["--persona-launcher-bg"]=(se=t["--persona-components-launcher-background"])!=null?se:t["--persona-primary"],t["--persona-launcher-fg"]=(N=t["--persona-components-launcher-foreground"])!=null?N:t["--persona-text-inverse"],t["--persona-launcher-border"]=(J=t["--persona-components-launcher-border"])!=null?J:t["--persona-border"],t["--persona-button-primary-bg"]=(ce=t["--persona-components-button-primary-background"])!=null?ce: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"]=(pe=(te=t["--persona-components-button-primary-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?pe:"9999px",t["--persona-panel-radius"]=(dt=(Lt=t["--persona-components-panel-borderRadius"])!=null?Lt:t["--persona-radius-xl"])!=null?dt:"0.75rem",t["--persona-panel-border"]=(Wt=t["--persona-components-panel-border"])!=null?Wt:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(P=(Gt=t["--persona-components-panel-shadow"])!=null?Gt:t["--persona-palette-shadows-xl"])!=null?P:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(ne=($=t["--persona-components-input-borderRadius"])!=null?$:t["--persona-radius-lg"])!=null?ne:"0.5rem",t["--persona-message-user-radius"]=(Fe=(Pe=t["--persona-components-message-user-borderRadius"])!=null?Pe:t["--persona-radius-lg"])!=null?Fe:"0.5rem",t["--persona-message-assistant-radius"]=(be=(Ce=t["--persona-components-message-assistant-borderRadius"])!=null?Ce:t["--persona-radius-lg"])!=null?be:"0.5rem",t["--persona-header-bg"]=(at=t["--persona-components-header-background"])!=null?at:t["--persona-surface"],t["--persona-header-border"]=(mt=t["--persona-components-header-border"])!=null?mt:t["--persona-divider"],t["--persona-header-icon-bg"]=(At=t["--persona-components-header-iconBackground"])!=null?At:t["--persona-primary"],t["--persona-header-icon-fg"]=(j=t["--persona-components-header-iconForeground"])!=null?j:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(xe=t["--persona-components-header-titleForeground"])!=null?xe: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"]=(Ze=t["--persona-components-header-actionIconForeground"])!=null?Ze:t["--persona-muted"];let n=(qe=e.components)==null?void 0:qe.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"]=(de=t["--persona-components-input-background"])!=null?de:t["--persona-surface"],t["--persona-input-placeholder"]=(Te=t["--persona-components-input-placeholder"])!=null?Te:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Ve=t["--persona-components-message-user-background"])!=null?Ve:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt: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"]=(pt=t["--persona-components-message-assistant-background"])!=null?pt: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"]=(ht=t["--persona-components-message-assistant-border"])!=null?ht: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"]=(je=(yt=t["--persona-components-scrollToBottom-background"])!=null?yt:t["--persona-button-primary-bg"])!=null?je:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(zn=(_t=t["--persona-components-scrollToBottom-foreground"])!=null?_t:t["--persona-button-primary-fg"])!=null?zn:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Kn=t["--persona-components-scrollToBottom-border"])!=null?Kn:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Rn=t["--persona-components-scrollToBottom-size"])!=null?Rn:"40px",t["--persona-scroll-to-bottom-radius"]=(qn=(Ar=(tt=t["--persona-components-scrollToBottom-borderRadius"])!=null?tt:t["--persona-button-radius"])!=null?Ar:t["--persona-radius-full"])!=null?qn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(En=(Er=t["--persona-components-scrollToBottom-shadow"])!=null?Er:t["--persona-palette-shadows-sm"])!=null?En:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Gr=t["--persona-components-scrollToBottom-padding"])!=null?Gr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(cr=t["--persona-components-scrollToBottom-gap"])!=null?cr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(it=(Xn=t["--persona-components-scrollToBottom-fontSize"])!=null?Xn:t["--persona-palette-typography-fontSize-sm"])!=null?it:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(hn=t["--persona-components-scrollToBottom-iconSize"])!=null?hn:"14px",t["--persona-tool-bubble-shadow"]=(Hn=t["--persona-components-toolBubble-shadow"])!=null?Hn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(nn=t["--persona-components-reasoningBubble-shadow"])!=null?nn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(dr=t["--persona-components-composer-shadow"])!=null?dr:"none",t["--persona-md-inline-code-bg"]=(yn=t["--persona-components-markdown-inlineCode-background"])!=null?yn:t["--persona-container"],t["--persona-md-inline-code-color"]=(Et=t["--persona-components-markdown-inlineCode-foreground"])!=null?Et:t["--persona-text"],t["--persona-md-link-color"]=(Tn=(rn=t["--persona-components-markdown-link-foreground"])!=null?rn:t["--persona-accent"])!=null?Tn:"#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 u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(pr=t["--persona-components-markdown-codeBlock-background"])!=null?pr: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"]=(ur=t["--persona-components-markdown-codeBlock-textColor"])!=null?ur:"inherit",t["--persona-md-table-header-bg"]=(Un=t["--persona-components-markdown-table-headerBackground"])!=null?Un:t["--persona-container"],t["--persona-md-table-border-color"]=(bn=t["--persona-components-markdown-table-borderColor"])!=null?bn:t["--persona-border"],t["--persona-md-hr-color"]=(Vn=t["--persona-components-markdown-hr-color"])!=null?Vn:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Ct=t["--persona-components-markdown-blockquote-borderColor"])!=null?Ct:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Bt=t["--persona-components-markdown-blockquote-background"])!=null?Bt:"transparent",t["--persona-md-blockquote-text-color"]=(Dt=t["--persona-components-markdown-blockquote-textColor"])!=null?Dt:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(xn=t["--persona-components-collapsibleWidget-container"])!=null?xn:t["--persona-surface"],t["--cw-surface"]=(mr=t["--persona-components-collapsibleWidget-surface"])!=null?mr:t["--persona-surface"],t["--cw-border"]=(Bn=t["--persona-components-collapsibleWidget-border"])!=null?Bn:t["--persona-border"],t["--persona-message-border"]=(vn=t["--persona-components-message-border"])!=null?vn: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 d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.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 g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let le=g.toolbar;le.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=le.iconHoverColor),le.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=le.iconHoverBackground),le.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=le.iconPadding),le.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=le.iconBorderRadius),le.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=le.iconBorder),le.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=le.toggleGroupGap),le.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=le.toggleBorderRadius),le.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=le.copyBackground),le.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=le.copyBorder),le.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=le.copyColor),le.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=le.copyBorderRadius),le.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=le.copyPadding),le.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=le.copyMenuBackground,t["--persona-dropdown-bg"]=(D=t["--persona-dropdown-bg"])!=null?D:le.copyMenuBackground),le.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=le.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:le.copyMenuBorder),le.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=le.copyMenuShadow,t["--persona-dropdown-shadow"]=(Mn=t["--persona-dropdown-shadow"])!=null?Mn:le.copyMenuShadow),le.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=le.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(gr=t["--persona-dropdown-radius"])!=null?gr:le.copyMenuBorderRadius),le.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=le.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(an=t["--persona-dropdown-item-hover-bg"])!=null?an:le.copyMenuItemHoverBackground),le.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=le.iconBackground),le.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=le.toolbarBorder)}if(g!=null&&g.tab){let le=g.tab;le.background&&(t["--persona-artifact-tab-bg"]=le.background),le.activeBackground&&(t["--persona-artifact-tab-active-bg"]=le.activeBackground),le.activeBorder&&(t["--persona-artifact-tab-active-border"]=le.activeBorder),le.borderRadius&&(t["--persona-artifact-tab-radius"]=le.borderRadius),le.textColor&&(t["--persona-artifact-tab-color"]=le.textColor),le.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=le.hoverBackground),le.listBackground&&(t["--persona-artifact-tab-list-bg"]=le.listBackground),le.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=le.listBorderColor),le.listPadding&&(t["--persona-artifact-tab-list-padding"]=le.listPadding)}if(g!=null&&g.pane){let le=g.pane;if(le.toolbarBackground){let Cn=(ln=Oo(e,le.toolbarBackground))!=null?ln:le.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Cn}}return t}var bd={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 lu={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"}}},xd=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$o=()=>{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"},cu=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":$o()},Ca=e=>cu(e),du=e=>io(e),pu=e=>{var t;let r=io(void 0,{validate:!1});return io({...e,palette:{...r.palette,colors:{...lu.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},_o=e=>{let r=Ca(e),t=xd(e==null?void 0:e.theme),n=xd(e==null?void 0:e.darkTheme);return r==="dark"?pu(Fo(t!=null?t:{},n!=null?n:{})):du(t)},uu=e=>Ns(e),xr=(e,r)=>{var o;let t=_o(r),n=uu(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)},Fs=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e($o())});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($o());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 vd=require("idiomorph"),Cd=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;vd.Idiomorph.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&n){if(s.classList.contains("persona-animate-typing"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function wd(e,r){var t,n,s,o,a,i,u,c,p,d,f,g,x,T,C,S,M,H,w,L,W,E,K,Q,X,O,oe,Ee,ae;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:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(C=(T=e.toolCall)==null?void 0:T.name)!=null?C:"",(H=(M=(S=e.toolCall)==null?void 0:S.chunks)==null?void 0:M.length)!=null?H:0,(E=(W=(L=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:W.slice(-32))!=null?E:"",typeof((K=e.toolCall)==null?void 0:K.args)=="string"?e.toolCall.args.length:(Q=e.toolCall)!=null&&Q.args?JSON.stringify(e.toolCall.args).length:0,(oe=(O=(X=e.reasoning)==null?void 0:X.chunks)==null?void 0:O.length)!=null?oe:0,(ae=(Ee=e.contentParts)==null?void 0:Ee.length)!=null?ae:0,r].join("\0")}function Sd(){return new Map}function Ad(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Ed(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Td(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}function Os(e=!0){let r=e;return{isFollowing:()=>r,pause:()=>r?(r=!1,!0):!1,resume:()=>r?!1:(r=!0,!0)}}function jo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zo(e,r){return jo(e)-e.scrollTop<=r}function $s(e){let{following:r,currentScrollTop:t,lastScrollTop:n,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!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&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function _s(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 tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},gn=1e5,vr=gn+1;function wa(e,r=gn){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 qo=0,Cr=null;function Sa(e=document){var t;if(qo++,qo===1){let n=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Cr={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,qo=Math.max(0,qo-1),qo===0&&Cr)){let s=e.body,o=(n=e.defaultView)!=null?n:window;s.style.overflow=Cr.originalOverflow,s.style.position=Cr.originalPosition,s.style.top=Cr.originalTop,s.style.width=Cr.originalWidth,o.scrollTo(0,Cr.scrollY),Cr=null}}}var js={side:"right",width:"420px",animate:!0,reveal:"resize"},Jt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Pn=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:js.side,width:(s=r==null?void 0:r.width)!=null?s:js.width,animate:(o=r==null?void 0:r.animate)!=null?o:js.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:js.reveal}};var jn={"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 Uo=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
6
|
+
`);a=(Ke=Ie.pop())!=null?Ke:"";for(let Oe of Ie){let Je=Oe.split(`
|
|
7
|
+
`),Ye="message",L="";for(let it of Je)it.startsWith("event:")?Ye=it.replace("event:","").trim():it.startsWith("data:")&&(L+=it.replace("data:","").trim());if(!L)continue;let ve;try{ve=JSON.parse(L)}catch(it){t({type:"error",error:it instanceof Error?it:new Error("Failed to parse chat stream payload")});continue}let De=Ye!=="message"?Ye:(Bt=ve.type)!=null?Bt:"message";if((Dt=this.onSSEEvent)==null||Dt.call(this,De,ve),this.parseSSEEvent){g.current=f;let it=await this.handleCustomSSEEvent(ve,t,g,d,c,x);if(g.current&&g.current!==f&&(f=g.current),it)continue}ht.push(De,ve),se()}}ht.flushPending(),se(),ht.destroy()}};function fd(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function fo(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function Gr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Vs="[Image]";function hd(e){return typeof e=="string"?[{type:"text",text:e}]:e}function yd(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function bd(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function xd(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function Yo(e){return{type:"text",text:e}}function vd(e,n){return{type:"image",image:e,...(n==null?void 0:n.mimeType)&&{mimeType:n.mimeType},...(n==null?void 0:n.alt)&&{alt:n.alt}}}async function Cd(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;n({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function wd(e,n=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${n.join(", ")}`}}var Sd=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],wu=["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"],pr=[...Sd,...wu];function Su(e){return Sd.includes(e)||e.startsWith("image/")}function Us(e){return Su(e.type)}async function Ad(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Us(e)?n({type:"image",image:s,mimeType:e.type,alt:e.name}):n({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ed(e,n=pr,t=10*1024*1024){return n.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${n.join(", ")}`}}function Au(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function Td(e,n){let t=Au(n).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||t||"FILE"}var Js=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let u=new Uint8Array(this.remainder.length+n.length);u.set(this.remainder),u.set(n,this.remainder.length),t=u,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(t),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.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 u=this.activeSources.indexOf(a);u!==-1&&this.activeSources.splice(u,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),s=new DataView(n.buffer,n.byteOffset,n.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ks=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(n,t,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=n.createMediaStreamSource(t),this.analyserNode=n.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let u=Math.sqrt(i/a.length);(r==="silence"?u<s.threshold:u>=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 Xo=class{constructor(n){this.config=n;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ks;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var n,t,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let 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=(n=this.config)==null?void 0:n.host,i=(t=this.config)==null?void 0:t.agentId,u=(r=this.config)==null?void 0:r.clientToken;if(!i||!u)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=${u}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let x=!1,E=w=>{x||(x=!0,clearTimeout(v),g(new Error(w)))},v=setTimeout(()=>E("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(v),f())},{once:!0}),this.ws.addEventListener("error",()=>{E("WebSocket connection failed to "+p+"."+d)},{once:!0}),this.ws.addEventListener("close",w=>{if(!w.wasClean&&!x){let I=w.code!==1006?` (code ${w.code})`:"";E("WebSocket connection failed"+I+"."+d)}},{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(n=>n("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(n=>n("disconnected"))},this.ws.onerror=n=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=n=>{if(n.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(n.data));return}try{let t=JSON.parse(n.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(n){var t,r;switch(n.type){case"session_config":n.interruptionMode&&(this.interruptionMode=n.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:n.response.agentResponseText||n.response.transcript,transcript:n.response.transcript,audio:n.response.audio,confidence:.95,provider:"runtype"})),(t=n.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(n.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=n.response.audio)!=null&&r.base64;break;case"audio_end":if(n.requestId&&n.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(n.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(n){n.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Js(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(n))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(n=>n("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var n,t,r,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=(n=this.config)==null?void 0:n.pauseDuration)!=null?t:2e3,u=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:u,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",d=new Blob(this.audioChunks,{type:p});await this.sendAudio(d),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(n=>n.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(n=>n("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let n=this.w;if(!this.mediaStream&&n&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&n&&(this.audioContext=new(n.AudioContext||n.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(n=>{this.errorCallbacks.forEach(t=>t(n instanceof Error?n:new Error(String(n))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(n){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(n),s=this.getFormatFromMimeType(n.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(n){return n.includes("wav")?"wav":n.includes("mpeg")||n.includes("mp3")?"mp3":"webm"}blobToBase64(n){return new Promise((t,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=r,s.readAsDataURL(n)})}async playAudio(n){if(!n.base64)return;let t=atob(n.base64),r=new Uint8Array(t.length);for(let c=0;c<t.length;c++)r[c]=t.charCodeAt(c);let s=n.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),u=new Audio(i);this.currentAudio=u,this.currentAudioUrl=i,u.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===u&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await u.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Yr=class{constructor(n={}){this.config=n;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(n=>n("connected"))}async startListening(){var n,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((n=this.config)==null?void 0:n.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(u=>u[0]).map(u=>u.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(u=>u({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(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(n=>n("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Xr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xo(e.runtype);case"browser":if(!Yr.isSupported())throw new Error("Browser speech recognition not supported");return new Yr(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 Xr({type:"runtype",runtype:e.runtype});if(Yr.isSupported())return Xr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Zo(e){try{return Gs(e),!0}catch{return!1}}var ho=class e{constructor(n={},t){this.config=n;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=n=>{var t,r,s,o,a,i,u;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(s=n.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):n.type==="status"?(this.setStatus(n.status),n.status==="connecting"?this.setStreaming(!0):(n.status==="idle"||n.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=n.status==="error"?"error":"complete"))):n.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(u=(i=this.callbacks).onError)==null||u.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Kr(n),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(n){this.client.setSSEEventCallback(n)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var n;return((n=this.agentExecution)==null?void 0:n.status)==="running"}isVoiceSupported(){var n;return Zo((n=this.config.voiceRecognition)==null?void 0:n.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var n;return(n=this.voiceProvider)!=null&&n.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var n;(n=this.voiceProvider)!=null&&n.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var n,t,r;return(r=(t=(n=this.voiceProvider)==null?void 0:n.isBargeInActive)==null?void 0:t.call(n))!=null?r:!1}async deactivateBargeIn(){var n;(n=this.voiceProvider)!=null&&n.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(n){var t,r,s;try{let o=n||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Xr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",u=(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,d,f,g,x,E;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}):(d=c.transcript)!=null&&d.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}):(g=c.text)!=null&&g.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let v=(E=this.pendingVoiceAssistantMessageId)!=null?E:(x=[...this.messages].reverse().find(w=>w.role==="assistant"))==null?void 0:x.id;v&&this.ttsSpokenMessageIds.add(v)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:u,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var p,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(p=this.callbacks).onVoiceStatusChanged)==null||d.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(n){console.error("Failed to start voice:",n)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,s,o,a,i,u,c,p;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((s=n.runtype)==null?void 0:s.clientToken)||"",host:(o=n.runtype)==null?void 0:o.host,voiceId:(a=n.runtype)==null?void 0:a.voiceId,pauseDuration:(i=n.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(u=n.runtype)==null?void 0:u.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(p=n.browser)==null?void 0:p.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new Kr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(n){this.handleEvent(n)}injectMessage(n){let{role:t,content:r,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:u,streaming:c=!1,voiceProcessing:p}=n,f={id:a!=null?a:t==="user"?fo():t==="assistant"?Gr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:u!=null?u: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(n){return this.injectMessage({...n,role:"assistant"})}injectUserMessage(n){return this.injectMessage({...n,role:"user"})}injectSystemMessage(n){return this.injectMessage({...n,role:"system"})}injectMessageBatch(n){let t=[];for(let r of n){let{role:s,content:o,llmContent:a,contentParts:i,id:u,createdAt:c,sequence:p,streaming:d=!1}=r,g={id:u!=null?u:s==="user"?fo():s==="assistant"?Gr():`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:d,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(g)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(n,t){var c,p,d,f,g;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=fo(),o=Gr(),a={id:s,role:"user",content:r||Vs,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 u=[...this.messages];try{await this.client.dispatch({messages:u,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!E){let v={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(v)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,E||(x instanceof Error?(d=(p=this.callbacks).onError)==null||d.call(p,x):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,u;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=Gr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let p={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(p),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(u=(i=this.callbacks).onError)==null||u.call(i,new Error(String(c)))}}async connectStream(n,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(n,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(n,t){var u,c,p;let r=`approval-${n.id}`,s={...n,status:t,resolvedAt:Date.now()},o={id:r,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 d;if(i?d=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):d=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let g=await d.json().catch(()=>null);throw new Error((u=g==null?void 0:g.error)!=null?u:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${n.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(p=(c=this.callbacks).onError)==null||p.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var s;let t=n.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(n.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:n.title,status:"complete",markdown:n.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let r={id:t,artifactType:"component",title:n.title,status:"complete",component:n.component,props:(s=n.props)!=null?s:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var n,t;(t=(n=this.callbacks).onArtifactsState)==null||t.call(n,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(n){var t,r;switch(n.type){case"artifact_start":{n.artifactType==="markdown"?this.artifacts.set(n.id,{id:n.id,artifactType:"markdown",title:n.title,status:"streaming",markdown:""}):this.artifacts.set(n.id,{id:n.id,artifactType:"component",title:n.title,status:"streaming",component:(t=n.component)!=null?t:"",props:{}}),this.selectedArtifactId=n.id;break}case"artifact_delta":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((r=s.markdown)!=null?r:"")+n.artDelta);break}case"artifact_update":{let s=this.artifacts.get(n.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...n.props},n.component&&(s.component=n.component));break}case"artifact_complete":{let s=this.artifacts.get(n.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(n){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(n.map(r=>{var s;return{...r,streaming:!1,sequence:(s=r.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(n){this.status!==n&&(this.status=n,this.callbacks.onStatusChanged(n))}setStreaming(n){if(this.streaming===n)return;let t=this.streaming;this.streaming=n,this.callbacks.onStreamingChanged(n),t&&!n&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let n=this.config.textToSpeech;if(!(n!=null&&n.enabled)||!(!n.provider||n.provider==="browser"||n.provider==="runtype"&&n.browserFallback))return;let r=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let s=r.content;s.trim()&&this.speak(s,n)}speak(n,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let r=window.speechSynthesis;r.cancel();let s=new SpeechSynthesisUtterance(n),o=r.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(()=>r.speak(s),50)}static pickBestVoice(n){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=n.find(a=>a.name===s);if(o)return o}return(r=n.find(s=>s.lang.startsWith("en")))!=null?r:n[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(n){let t=this.ensureSequence(n);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(n){let t=this.ensureSequence(n),r=this.messages.findIndex(s=>s.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===r?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(n){return n.sequence!==void 0?{...n}:{...n,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(n){return[...n].sort((t,r)=>{var u,c;let s=new Date(t.createdAt).getTime(),o=new Date(r.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(u=t.sequence)!=null?u:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var h=(e,n)=>{let t=document.createElement(e);return n&&(t.className=n),t},er=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};var Eu=rd(require("lucide"),1),ye=(e,n=24,t="currentColor",r=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Eu[s];return o?Tu(o,n,t,r):(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 Tu(e,n,t,r){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(n)),s.setAttribute("height",String(n)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(r)),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 u=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&u.setAttribute(c,String(p))}),s.appendChild(u)}}}),s}var Ys={allowedTypes:pr,maxFileSize:10*1024*1024,maxFiles:4};function Mu(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function ku(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 Zr=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Ys.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Ys.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Ys.maxFiles,onFileRejected:n.onFileRejected,onAttachmentsChange:n.onAttachmentsChange}}setPreviewsContainer(n){this.previewsContainer=n}updateConfig(n){n.allowedTypes!==void 0&&(this.config.allowedTypes=n.allowedTypes.length>0?n.allowedTypes:Ys.allowedTypes),n.maxFileSize!==void 0&&(this.config.maxFileSize=n.maxFileSize),n.maxFiles!==void 0&&(this.config.maxFiles=n.maxFiles),n.onFileRejected!==void 0&&(this.config.onFileRejected=n.onFileRejected),n.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=n.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(n=>n.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(n){!n||n.length===0||await this.handleFiles(Array.from(n))}async handleFiles(n){var t,r,s,o,a,i,u;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let p=Ed(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let d=(s=p.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await Ad(c),f=Us(c)?URL.createObjectURL(c):null,g={id:Mu(),file:c,previewUrl:f,contentPart:d};this.attachments.push(g),this.renderPreview(g)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(u=(i=this.config).onAttachmentsChange)==null||u.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(u=>u.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${n}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var n,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(n=this.config).onAttachmentsChange)==null||t.call(n,this.getAttachments())}renderPreview(n){if(!this.previewsContainer)return;let t=Us(n.file),r=h("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",n.id),r.style.width="48px",r.style.height="48px",t&&n.previewUrl){let a=h("img");a.src=n.previewUrl,a.alt=n.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=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=ku(n.file.type),u=ye(i,20,"var(--persona-muted, #6b7280)",1.5);u&&a.appendChild(u);let c=h("span");c.textContent=Td(n.file.type,n.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let 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=ye("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(n.id)}),r.appendChild(s),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(n,t){return new e({allowedTypes:n==null?void 0:n.allowedTypes,maxFileSize:n==null?void 0:n.maxFileSize,maxFiles:n==null?void 0:n.maxFiles,onFileRejected:n==null?void 0:n.onFileRejected,onAttachmentsChange:t})}};var Md=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Qo(e,n){if(!e)return n;if(!n)return e;let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];Md(o)&&Md(s)?t[r]=Qo(o,s):t[r]=s}return t}var Pn="min(440px, calc(100vw - 24px))",Xs="440px",Wt={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:Pn,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",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:""},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800}},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 kd(e,n){if(!(!e&&!n))return e?n?Qo(e,n):e:n}function Zs(e){var n,t,r,s,o,a,i,u,c,p,d,f,g,x,E,v,w,I,j,A,R;return e?{...Wt,...e,theme:kd(Wt.theme,e.theme),darkTheme:kd(Wt.darkTheme,e.darkTheme),launcher:{...Wt.launcher,...e.launcher,dock:{...(n=Wt.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=Wt.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Wt.copy,...e.copy},sendButton:{...Wt.sendButton,...e.sendButton},statusIndicator:{...Wt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Wt.voiceRecognition,...e.voiceRecognition},features:(()=>{var Ne,me,Re,Ee,He,de;let T=(Ne=Wt.features)==null?void 0:Ne.artifacts,P=(me=e.features)==null?void 0:me.artifacts,H=(Re=Wt.features)==null?void 0:Re.scrollToBottom,J=(Ee=e.features)==null?void 0:Ee.scrollToBottom,U=(He=Wt.features)==null?void 0:He.streamAnimation,$=(de=e.features)==null?void 0:de.streamAnimation,ie=T===void 0&&P===void 0?void 0:{...T,...P,layout:{...T==null?void 0:T.layout,...P==null?void 0:P.layout}},be=H===void 0&&J===void 0?void 0:{...H,...J},pe=U===void 0&&$===void 0?void 0:{...U,...$};return{...Wt.features,...e.features,...be!==void 0?{scrollToBottom:be}:{},...ie!==void 0?{artifacts:ie}:{},...pe!==void 0?{streamAnimation:pe}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Wt.suggestionChips,suggestionChipsConfig:{...Wt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Wt.layout,...e.layout,header:{...(a=Wt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(u=Wt.layout)==null?void 0:u.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(p=Wt.layout)==null?void 0:p.messages)==null?void 0:d.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(E=(x=Wt.layout)==null?void 0:x.messages)==null?void 0:E.timestamp,...(w=(v=e.layout)==null?void 0:v.messages)==null?void 0:w.timestamp}},slots:{...(I=Wt.layout)==null?void 0:I.slots,...(j=e.layout)==null?void 0:j.slots}},markdown:{...Wt.markdown,...e.markdown,options:{...(A=Wt.markdown)==null?void 0:A.options,...(R=e.markdown)==null?void 0:R.options}},messageActions:{...Wt.messageActions,...e.messageActions}}:Wt}var Da={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"}},Na={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"}},Fa={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:Pn,maxWidth:Xs,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 es(e,n){if(!n.startsWith("palette.")&&!n.startsWith("semantic.")&&!n.startsWith("components."))return n;let t=n.split("."),r=e;for(let s of t){if(r==null)return;r=r[s]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?es(e,r):r}function Qs(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let u=es(e,a);u!==void 0&&(n[i]={path:i,value:u,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"),n}function Oa(e){let n=[],t=[];return e.palette||n.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:n.length===0,errors:n,warnings:t}}function Ld(e,n){let t={...e};for(let[r,s]of Object.entries(n)){let o=t[r];o&&typeof o=="object"&&!Array.isArray(o)&&s&&typeof s=="object"&&!Array.isArray(s)?t[r]=Ld(o,s):t[r]=s}return t}function Lu(e,n){return n?Ld(e,n):e}function yo(e,n={}){var s,o,a,i,u,c,p,d,f,g,x,E,v;let t={palette:Da,semantic:Na,components:Fa},r={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,...(u=e==null?void 0:e.palette)==null?void 0:u.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=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(E=e==null?void 0:e.semantic)==null?void 0:E.spacing},typography:{...t.semantic.typography,...(v=e==null?void 0:e.semantic)==null?void 0:v.typography}},components:Lu(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let w=Oa(r);if(!w.valid)throw new Error(`Theme validation failed: ${w.errors.map(I=>I.message).join(", ")}`)}if(n.plugins)for(let w of n.plugins)r=w.transform(r);return r}function ea(e){var x,E,v,w,I,j,A,R,T,P,H,J,U,$,ie,be,pe,Ne,me,Re,Ee,He,de,Q,he,X,ge,ue,oe,Te,Me,k,V,ae,D,q,le,xe,ee,se,Et,ht,Ve,Xt,Qe,fe,Ke,Bt,Dt,W,re,Ie,Oe,Je,Ye,L,ve,De,it,Z,ne,_e,lt,Rt,Zt,mt,pt,at,Ce,rt,je,Qt,en,Wn,tn,et,fr,wn,Rr,Rn,ro,hr,nr,gt,Sn,jn,dn,yr,An,Mt,pn,Hn,br,rr,xr,Xn,En,Zn,wt,$t,_t,Tn,vr,Bn,zn,Mn,O,qn,Dn,Cr;let n=Qs(e),t={};for(let[ce,un]of Object.entries(n)){let kn=ce.replace(/\./g,"-");t[`--persona-${kn}`]=un.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(v=t["--persona-semantic-colors-accent"])!=null?v:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(w=t["--persona-semantic-colors-surface"])!=null?w:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(j=t["--persona-semantic-colors-container"])!=null?j:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(A=t["--persona-semantic-colors-text"])!=null?A:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(R=t["--persona-semantic-colors-text-muted"])!=null?R:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(T=t["--persona-semantic-colors-text-inverse"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(P=t["--persona-semantic-colors-border"])!=null?P:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(H=t["--persona-semantic-colors-divider"])!=null?H:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(J=t["--persona-components-voice-recording-indicator"])!=null?J:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(U=t["--persona-components-voice-recording-background"])!=null?U: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"]=(ie=t["--persona-components-voice-speaking-icon"])!=null?ie:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(be=t["--persona-components-approval-requested-background"])!=null?be:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(pe=t["--persona-components-approval-requested-border"])!=null?pe:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Ne=t["--persona-components-approval-requested-text"])!=null?Ne:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(me=t["--persona-components-approval-approve-background"])!=null?me:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Re=t["--persona-components-approval-deny-background"])!=null?Re:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Ee=t["--persona-components-attachment-image-background"])!=null?Ee:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(He=t["--persona-components-attachment-image-border"])!=null?He:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(de=t["--persona-semantic-typography-fontFamily"])!=null?de:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Q=t["--persona-semantic-typography-fontSize"])!=null?Q:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(he=t["--persona-semantic-typography-fontWeight"])!=null?he:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(X=t["--persona-semantic-typography-lineHeight"])!=null?X: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"]=(ge=t["--persona-palette-radius-sm"])!=null?ge:"0.125rem",t["--persona-radius-md"]=(ue=t["--persona-palette-radius-md"])!=null?ue:"0.375rem",t["--persona-radius-lg"]=(oe=t["--persona-palette-radius-lg"])!=null?oe:"0.5rem",t["--persona-radius-xl"]=(Te=t["--persona-palette-radius-xl"])!=null?Te:"0.75rem",t["--persona-radius-full"]=(Me=t["--persona-palette-radius-full"])!=null?Me:"9999px",t["--persona-launcher-radius"]=(V=(k=t["--persona-components-launcher-borderRadius"])!=null?k:t["--persona-palette-radius-full"])!=null?V:"9999px",t["--persona-launcher-bg"]=(ae=t["--persona-components-launcher-background"])!=null?ae:t["--persona-primary"],t["--persona-launcher-fg"]=(D=t["--persona-components-launcher-foreground"])!=null?D:t["--persona-text-inverse"],t["--persona-launcher-border"]=(q=t["--persona-components-launcher-border"])!=null?q:t["--persona-border"],t["--persona-button-primary-bg"]=(le=t["--persona-components-button-primary-background"])!=null?le:t["--persona-primary"],t["--persona-button-primary-fg"]=(xe=t["--persona-components-button-primary-foreground"])!=null?xe:t["--persona-text-inverse"],t["--persona-button-radius"]=(se=(ee=t["--persona-components-button-primary-borderRadius"])!=null?ee:t["--persona-palette-radius-full"])!=null?se:"9999px",t["--persona-panel-radius"]=(ht=(Et=t["--persona-components-panel-borderRadius"])!=null?Et:t["--persona-radius-xl"])!=null?ht:"0.75rem",t["--persona-panel-border"]=(Ve=t["--persona-components-panel-border"])!=null?Ve:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Qe=(Xt=t["--persona-components-panel-shadow"])!=null?Xt:t["--persona-palette-shadows-xl"])!=null?Qe:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ke=(fe=t["--persona-components-input-borderRadius"])!=null?fe:t["--persona-radius-lg"])!=null?Ke:"0.5rem",t["--persona-message-user-radius"]=(Dt=(Bt=t["--persona-components-message-user-borderRadius"])!=null?Bt:t["--persona-radius-lg"])!=null?Dt:"0.5rem",t["--persona-message-assistant-radius"]=(re=(W=t["--persona-components-message-assistant-borderRadius"])!=null?W:t["--persona-radius-lg"])!=null?re:"0.5rem",t["--persona-header-bg"]=(Ie=t["--persona-components-header-background"])!=null?Ie:t["--persona-surface"],t["--persona-header-border"]=(Oe=t["--persona-components-header-border"])!=null?Oe:t["--persona-divider"],t["--persona-header-icon-bg"]=(Je=t["--persona-components-header-iconBackground"])!=null?Je:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ye=t["--persona-components-header-iconForeground"])!=null?Ye:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(L=t["--persona-components-header-titleForeground"])!=null?L:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(ve=t["--persona-components-header-subtitleForeground"])!=null?ve:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(De=t["--persona-components-header-actionIconForeground"])!=null?De:t["--persona-muted"];let r=(it=e.components)==null?void 0:it.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom),t["--persona-input-background"]=(Z=t["--persona-components-input-background"])!=null?Z:t["--persona-surface"],t["--persona-input-placeholder"]=(ne=t["--persona-components-input-placeholder"])!=null?ne:t["--persona-text-muted"],t["--persona-message-user-bg"]=(_e=t["--persona-components-message-user-background"])!=null?_e:t["--persona-accent"],t["--persona-message-user-text"]=(lt=t["--persona-components-message-user-text"])!=null?lt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Rt=t["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Zt=t["--persona-components-message-assistant-background"])!=null?Zt:t["--persona-surface"],t["--persona-message-assistant-text"]=(mt=t["--persona-components-message-assistant-text"])!=null?mt:t["--persona-text"],t["--persona-message-assistant-border"]=(pt=t["--persona-components-message-assistant-border"])!=null?pt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(at=t["--persona-components-message-assistant-shadow"])!=null?at:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(rt=(Ce=t["--persona-components-scrollToBottom-background"])!=null?Ce:t["--persona-button-primary-bg"])!=null?rt:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Qt=(je=t["--persona-components-scrollToBottom-foreground"])!=null?je:t["--persona-button-primary-fg"])!=null?Qt:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(en=t["--persona-components-scrollToBottom-border"])!=null?en:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(Wn=t["--persona-components-scrollToBottom-size"])!=null?Wn:"40px",t["--persona-scroll-to-bottom-radius"]=(fr=(et=(tn=t["--persona-components-scrollToBottom-borderRadius"])!=null?tn:t["--persona-button-radius"])!=null?et:t["--persona-radius-full"])!=null?fr:"9999px",t["--persona-scroll-to-bottom-shadow"]=(Rr=(wn=t["--persona-components-scrollToBottom-shadow"])!=null?wn:t["--persona-palette-shadows-sm"])!=null?Rr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(Rn=t["--persona-components-scrollToBottom-padding"])!=null?Rn:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(ro=t["--persona-components-scrollToBottom-gap"])!=null?ro:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(nr=(hr=t["--persona-components-scrollToBottom-fontSize"])!=null?hr:t["--persona-palette-typography-fontSize-sm"])!=null?nr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(gt=t["--persona-components-scrollToBottom-iconSize"])!=null?gt:"14px",t["--persona-tool-bubble-shadow"]=(Sn=t["--persona-components-toolBubble-shadow"])!=null?Sn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(jn=t["--persona-components-reasoningBubble-shadow"])!=null?jn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(dn=t["--persona-components-composer-shadow"])!=null?dn:"none",t["--persona-md-inline-code-bg"]=(yr=t["--persona-components-markdown-inlineCode-background"])!=null?yr:t["--persona-container"],t["--persona-md-inline-code-color"]=(An=t["--persona-components-markdown-inlineCode-foreground"])!=null?An:t["--persona-text"],t["--persona-md-link-color"]=(pn=(Mt=t["--persona-components-markdown-link-foreground"])!=null?Mt:t["--persona-accent"])!=null?pn:"#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 u=t["--persona-components-markdown-prose-fontFamily"];u&&u!=="inherit"&&(t["--persona-md-prose-font-family"]=u),t["--persona-md-code-block-bg"]=(Hn=t["--persona-components-markdown-codeBlock-background"])!=null?Hn:t["--persona-container"],t["--persona-md-code-block-border-color"]=(br=t["--persona-components-markdown-codeBlock-borderColor"])!=null?br:t["--persona-border"],t["--persona-md-code-block-text-color"]=(rr=t["--persona-components-markdown-codeBlock-textColor"])!=null?rr:"inherit",t["--persona-md-table-header-bg"]=(xr=t["--persona-components-markdown-table-headerBackground"])!=null?xr:t["--persona-container"],t["--persona-md-table-border-color"]=(Xn=t["--persona-components-markdown-table-borderColor"])!=null?Xn:t["--persona-border"],t["--persona-md-hr-color"]=(En=t["--persona-components-markdown-hr-color"])!=null?En:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Zn=t["--persona-components-markdown-blockquote-borderColor"])!=null?Zn: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"]=($t=t["--persona-components-markdown-blockquote-textColor"])!=null?$t:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(_t=t["--persona-components-collapsibleWidget-container"])!=null?_t:t["--persona-surface"],t["--cw-surface"]=(Tn=t["--persona-components-collapsibleWidget-surface"])!=null?Tn:t["--persona-surface"],t["--cw-border"]=(vr=t["--persona-components-collapsibleWidget-border"])!=null?vr:t["--persona-border"],t["--persona-message-border"]=(Bn=t["--persona-components-message-border"])!=null?Bn: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 d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.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 g=c==null?void 0:c.artifact;if(g!=null&&g.toolbar){let ce=g.toolbar;ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=ce.iconHoverColor),ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=ce.iconHoverBackground),ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=ce.iconPadding),ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=ce.iconBorderRadius),ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=ce.iconBorder),ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=ce.toggleGroupGap),ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=ce.toggleBorderRadius),ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=ce.copyBackground),ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=ce.copyBorder),ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=ce.copyColor),ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=ce.copyBorderRadius),ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=ce.copyPadding),ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=ce.copyMenuBackground,t["--persona-dropdown-bg"]=(zn=t["--persona-dropdown-bg"])!=null?zn:ce.copyMenuBackground),ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=ce.copyMenuBorder,t["--persona-dropdown-border"]=(Mn=t["--persona-dropdown-border"])!=null?Mn:ce.copyMenuBorder),ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(O=t["--persona-dropdown-shadow"])!=null?O:ce.copyMenuShadow),ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(qn=t["--persona-dropdown-radius"])!=null?qn:ce.copyMenuBorderRadius),ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Dn=t["--persona-dropdown-item-hover-bg"])!=null?Dn:ce.copyMenuItemHoverBackground),ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=ce.iconBackground),ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=ce.toolbarBorder)}if(g!=null&&g.tab){let ce=g.tab;ce.background&&(t["--persona-artifact-tab-bg"]=ce.background),ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=ce.activeBackground),ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=ce.activeBorder),ce.borderRadius&&(t["--persona-artifact-tab-radius"]=ce.borderRadius),ce.textColor&&(t["--persona-artifact-tab-color"]=ce.textColor),ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=ce.hoverBackground),ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=ce.listBackground),ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=ce.listBorderColor),ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=ce.listPadding)}if(g!=null&&g.pane){let ce=g.pane;if(ce.toolbarBackground){let un=(Cr=es(e,ce.toolbarBackground))!=null?Cr:ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=un}}return t}var Id={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 Iu={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"}}},Pd=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},ts=()=>{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"},Pu=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":ts()},$a=e=>Pu(e),Wu=e=>yo(e),Ru=e=>{var t;let n=yo(void 0,{validate:!1});return yo({...e,palette:{...n.palette,colors:{...Iu.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},ns=e=>{let n=$a(e),t=Pd(e==null?void 0:e.theme),r=Pd(e==null?void 0:e.darkTheme);return n==="dark"?Ru(Qo(t!=null?t:{},r!=null?r:{})):Wu(t)},Hu=e=>ea(e),kr=(e,n)=>{var o;let t=ns(n),r=Hu(t);for(let[a,i]of Object.entries(r))e.style.setProperty(a,i);let s=(o=n==null?void 0:n.toolCall)==null?void 0:o.shadow;s!==void 0&&e.style.setProperty("--persona-tool-bubble-shadow",s.trim()===""?"none":s)},ta=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(ts())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),n.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(ts());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};var Wd=require("idiomorph"),Rd=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;Wd.Idiomorph.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){var a,i;if(s instanceof HTMLElement&&r){if(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-runtime"))return!1;if(s.hasAttribute("data-preserve-animation")){if(o instanceof HTMLElement&&!o.hasAttribute("data-preserve-animation"))return;if(o instanceof HTMLElement&&o.hasAttribute("data-preserve-animation")){let u=(a=s.textContent)!=null?a:"",c=(i=o.textContent)!=null?i:"";if(u!==c)return}return!1}}}}})};function Hd(e,n){var t,r,s,o,a,i,u,c,p,d,f,g,x,E,v,w,I,j,A,R,T,P,H,J,U,$,ie,be,pe,Ne;return[e.id,e.role,(r=(t=e.content)==null?void 0:t.length)!=null?r:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(u=(i=e.rawContent)==null?void 0:i.length)!=null?u:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(x=(g=e.toolCall)==null?void 0:g.status)!=null?x:"",(v=(E=e.toolCall)==null?void 0:E.name)!=null?v:"",(j=(I=(w=e.toolCall)==null?void 0:w.chunks)==null?void 0:I.length)!=null?j:0,(P=(T=(R=(A=e.toolCall)==null?void 0:A.chunks)==null?void 0:R[e.toolCall.chunks.length-1])==null?void 0:T.slice(-32))!=null?P:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(J=e.toolCall)!=null&&J.args?JSON.stringify(e.toolCall.args).length:0,(ie=($=(U=e.reasoning)==null?void 0:U.chunks)==null?void 0:$.length)!=null?ie:0,(pe=(be=e.contentParts)==null?void 0:be.length)!=null?pe:0,(Ne=e.stopReason)!=null?Ne:"",n].join("\0")}function Bd(){return new Map}function Dd(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Nd(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function Fd(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}function na(e=!0){let n=e;return{isFollowing:()=>n,pause:()=>n?(n=!1,!0):!1,resume:()=>n?!1:(n=!0,!0)}}function rs(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function os(e,n){return rs(e)-e.scrollTop<=n}function ra(e){let{following:n,currentScrollTop:t,lastScrollTop:r,nearBottom:s,userScrollThreshold:o,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:u=!0,resumeRequiresDownwardScroll:c=!1}=e,p=t-r;return a||Math.abs(p)<o?{action:"none",delta:p,nextLastScrollTop:t}:!n&&s&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:n&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:n&&u&&!s?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function oa(e){let{following:n,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:s=!1}=e;return n&&t<0?"pause":!n&&s&&t>0&&r?"resume":"none"}var cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},vn=1e5,Lr=vn+1;var ss={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Bu=["pre","code","a","script","style"],$d=e=>{var n,t,r,s,o;return{type:(n=e==null?void 0:e.type)!=null?n:ss.type,placeholder:(t=e==null?void 0:e.placeholder)!=null?t:ss.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ss.speed,duration:(s=e==null?void 0:e.duration)!=null?s:ss.duration,buffer:(o=e==null?void 0:e.buffer)!=null?o:ss.buffer}},_d=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],as=new Map;for(let e of _d)as.set(e.name,e);var jd=e=>{as.set(e.name,e)},zd=e=>{_d.some(n=>n.name===e)||as.delete(e)},qd=()=>Array.from(as.keys()),sa=(e,n)=>{var t,r;return e==="none"?null:n&&Object.prototype.hasOwnProperty.call(n,e)?(t=n[e])!=null?t:null:(r=as.get(e))!=null?r:null},Vd=(e,n,t,r,s)=>{if(!s)return e;if(t!=null&&t.bufferContent)return t.bufferContent(e,r);if(!e)return e;if(n==="word"){let o=e.search(/\s(?=\S*$)/);return o<0?"":e.slice(0,o)}if(n==="line"){let o=e.lastIndexOf(`
|
|
8
|
+
`);return o<0?"":e.slice(0,o)}return e},Du=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-char",s.id=`stream-c-${t}-${r}`,s.style.setProperty("--char-index",String(r)),s.textContent=n,s},Nu=(e,n,t,r)=>{let s=e.createElement("span");return s.className="persona-stream-word",s.id=`stream-w-${t}-${r}`,s.style.setProperty("--word-index",String(r)),s.textContent=n,s},_a=/\s/,Fu=(e,n)=>{let t=e.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(n.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Ou=(e,n,t)=>{var u;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(u=e.nodeValue)!=null?u:"";if(!o)return;let a=r.createDocumentFragment(),i=0;for(;i<o.length;)if(_a.test(o[i])){let c=i;for(;c<o.length&&_a.test(o[c]);)c+=1;a.appendChild(r.createTextNode(o.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<o.length&&!_a.test(o[p]);)c.appendChild(Du(r,o[p],n,t.value)),t.value+=1,p+=1;a.appendChild(c),i=p}s.replaceChild(a,e)},$u=(e,n,t)=>{var u;let r=e.ownerDocument,s=e.parentNode;if(!r||!s)return;let o=(u=e.nodeValue)!=null?u:"";if(!o)return;let a=r.createDocumentFragment(),i=o.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Nu(r,c,n,t.value)),t.value+=1));s.replaceChild(a,e)},za=(e,n,t,r)=>{var d;if(!e||typeof document=="undefined")return e;let s=document.createElement("div");s.innerHTML=e;let o=new Set(((d=r==null?void 0:r.skipTags)!=null?d:Bu).map(f=>f.toLowerCase())),a=document.createTreeWalker(s,NodeFilter.SHOW_TEXT,null),i=[],u=a.nextNode();for(;u;)Fu(u,o)||i.push(u),u=a.nextNode();let c={value:0},p=n==="char"?Ou:$u;for(let f of i)p(f,t,c);return s.innerHTML},Ud=(e=document)=>{let n=e.createElement("span");return n.className="persona-stream-caret",n.setAttribute("aria-hidden","true"),n.setAttribute("data-preserve-animation","stream-caret"),n},qa=(e=document)=>{let n=e.createElement("div");n.className="persona-stream-skeleton",n.setAttribute("data-preserve-animation","stream-skeleton"),n.setAttribute("aria-hidden","true");let t=e.createElement("div");return t.className="persona-stream-skeleton-line",n.appendChild(t),n},Od=new WeakMap,_u=(e,n)=>{var o;if(!e.styles)return;let t=Od.get(n);if(t||(t=new Set,Od.set(n,t)),t.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(n.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(e.name)}t.add(e.name);let s=(n instanceof ShadowRoot?n.ownerDocument:(o=n.ownerDocument)!=null?o:document).createElement("style");s.setAttribute("data-persona-animation",e.name),s.textContent=e.styles,n.appendChild(s)},ja=new WeakMap,ju=(e,n)=>{if(!e.onAttach)return;let t=ja.get(n);if(t||(t=new Map,ja.set(n,t)),t.has(e.name))return;let r=e.onAttach(n);t.set(e.name,r)},Jd=e=>{let n=ja.get(e);if(n){for(let t of n.values())typeof t=="function"&&t();n.clear()}},Kd=(e,n)=>{_u(e,n),ju(e,n)};function Va(e,n=vn){let t=e.style.position,r=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(n),e.style.isolation="isolate",()=>{a&&(e.style.position=t),e.style.zIndex=r,e.style.isolation=s}}var is=0,Ir=null;function Ua(e=document){var t;if(is++,is===1){let r=e.body,o=((t=e.defaultView)!=null?t:window).scrollY||e.documentElement.scrollTop;Ir={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:o},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${o}px`,r.style.width="100%"}let n=!1;return()=>{var r;if(!n&&(n=!0,is=Math.max(0,is-1),is===0&&Ir)){let s=e.body,o=(r=e.defaultView)!=null?r:window;s.style.overflow=Ir.originalOverflow,s.style.position=Ir.originalPosition,s.style.top=Ir.originalTop,s.style.width=Ir.originalWidth,o.scrollTo(0,Ir.scrollY),Ir=null}}}var aa={side:"right",width:"420px",animate:!0,reveal:"resize"},Jt=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},$n=e=>{var t,r,s,o,a;let n=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(r=n==null?void 0:n.side)!=null?r:aa.side,width:(s=n==null?void 0:n.width)!=null?s:aa.width,animate:(o=n==null?void 0:n.animate)!=null?o:aa.animate,reveal:(a=n==null?void 0:n.reveal)!=null?a:aa.reveal}};var Yn={"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 ls=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
|
|
8
9
|
<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
10
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|
|
10
11
|
<span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
|
|
@@ -12,14 +13,14 @@
|
|
|
12
13
|
<span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
|
|
13
14
|
</span>
|
|
14
15
|
<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 H,w,L,W,E,K,Q,X,O,oe,Ee,ae,we,$e;let a=(H=o.launcher)!=null?H:{},i=Jt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let he=(w=a.title)!=null?w:"Chat Assistant";u.textContent=he,u.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 d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let he=(W=a.agentIconSize)!=null?W:"40px";if(d.style.height=he,d.style.width=he,d.innerHTML="",a.agentIconName){let We=parseFloat(he)||24,Re=ye(a.agentIconName,We*.6,"var(--persona-text-inverse, #ffffff)",2);Re?(d.appendChild(Re),d.style.display=""):(d.textContent=(E=a.agentIconText)!=null?E:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(K=a.agentIconText)!=null?K:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let he=(Q=a.agentIconSize)!=null?Q:"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 g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let he=(X=a.callToActionIconSize)!=null?X:"32px";g.style.height=he,g.style.width=he,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let We=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,We=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let Re=parseFloat(he)||24,ie=Math.max(Re-We,8),Z=ye(a.callToActionIconName,ie,"currentColor",2);Z?g.appendChild(Z):g.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else g.textContent=(oe=a.callToActionIconText)!=null?oe:"\u2197"}let x=a.position&&jn[a.position]?jn[a.position]:jn["bottom-right"],T="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",C="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?C:`${T} ${x}`,i||(t.style.zIndex=String((Ee=a.zIndex)!=null?Ee:gn));let S="1px solid var(--persona-border, #e5e7eb)",M="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=(ae=a.border)!=null?ae:S,t.style.boxShadow=(we=a.shadow)!=null?we:M,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=($e=a.collapsedMaxWidth)!=null?$e:"",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 fn={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))"},ar=e=>{var X,O,oe,Ee,ae,we,$e,he,We,Re,ie,Z,me,V,re,He,ge,Be,st,z,U,se,N,J,ce,fe,te,pe,Lt,dt,Wt,Gt;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=(X=r==null?void 0:r.launcher)!=null?X:{},o=(O=s.headerIconSize)!=null?O:"48px",a=(oe=s.closeButtonSize)!=null?oe:"32px",i=(Ee=s.closeButtonPlacement)!=null?Ee:"inline",u=(ae=s.headerIconHidden)!=null?ae:!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))",!u)if(c){let P=parseFloat(o)||24,$=ye(c,P*.6,"currentColor",1);$?p.replaceChildren($):p.textContent=($e=(we=r==null?void 0:r.launcher)==null?void 0:we.agentIconText)!=null?$e:"\u{1F4AC}"}else if((he=r==null?void 0:r.launcher)!=null&&he.iconUrl){let P=h("img");P.src=r.launcher.iconUrl,P.alt="",P.className="persona-rounded-xl persona-object-cover",P.style.height=o,P.style.width=o,p.replaceChildren(P)}else p.textContent=(Re=(We=r==null?void 0:r.launcher)==null?void 0:We.agentIconText)!=null?Re:"\u{1F4AC}";let d=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=fn.titleColor,f.textContent=(Z=(ie=r==null?void 0:r.launcher)==null?void 0:ie.title)!=null?Z:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=fn.subtitleColor,g.textContent=(V=(me=r==null?void 0:r.launcher)==null?void 0:me.subtitle)!=null?V:"Here to help you get answers fast",d.append(f,g),u?n.append(d):n.append(p,d);let x=(re=s.clearChat)!=null?re:{},T=(He=x.enabled)!=null?He:!0,C=(ge=x.placement)!=null?ge:"inline",S=null,M=null;if(T){let P=(Be=x.size)!=null?Be:"32px",$=(st=x.iconName)!=null?st:"refresh-cw",ne=(z=x.iconColor)!=null?z:"",Pe=(U=x.backgroundColor)!=null?U:"",Fe=(se=x.borderWidth)!=null?se:"",Ce=(N=x.borderColor)!=null?N:"",be=(J=x.borderRadius)!=null?J:"",at=(ce=x.paddingX)!=null?ce:"",mt=(fe=x.paddingY)!=null?fe:"",At=(te=x.tooltipText)!=null?te:"Clear chat",j=(pe=x.showTooltip)!=null?pe:!0;M=h("div",C==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),C==="top-right"&&(M.style.right="48px"),S=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"),S.style.height=P,S.style.width=P,S.type="button",S.setAttribute("aria-label",At),S.style.color=ne||fn.actionIconColor;let xe=ye($,"20px","currentColor",1);if(xe&&S.appendChild(xe),Pe&&(S.style.backgroundColor=Pe,S.classList.remove("hover:persona-bg-gray-100")),Fe||Ce){let ue=Fe||"0px",Ze=Ce||"transparent";S.style.border=`${ue} solid ${Ze}`,S.classList.remove("persona-border-none")}if(be&&(S.style.borderRadius=be,S.classList.remove("persona-rounded-full")),at?(S.style.paddingLeft=at,S.style.paddingRight=at):(S.style.paddingLeft="",S.style.paddingRight=""),mt?(S.style.paddingTop=mt,S.style.paddingBottom=mt):(S.style.paddingTop="",S.style.paddingBottom=""),M.appendChild(S),j&&At&&S&&M){let ue=null,Ze=()=>{if(ue||!S)return;let de=S.ownerDocument,Te=de.body;if(!Te)return;ue=Gn(de,"div","persona-clear-chat-tooltip"),ue.textContent=At;let Ve=Gn(de,"div");Ve.className="persona-clear-chat-tooltip-arrow",ue.appendChild(Ve);let vt=S.getBoundingClientRect();ue.style.position="fixed",ue.style.zIndex=String(vr),ue.style.left=`${vt.left+vt.width/2}px`,ue.style.top=`${vt.top-8}px`,ue.style.transform="translate(-50%, -100%)",Te.appendChild(ue)},qe=()=>{ue&&ue.parentNode&&(ue.parentNode.removeChild(ue),ue=null)};M.addEventListener("mouseenter",Ze),M.addEventListener("mouseleave",qe),S.addEventListener("focus",Ze),S.addEventListener("blur",qe),M._cleanupTooltip=()=>{qe(),M&&(M.removeEventListener("mouseenter",Ze),M.removeEventListener("mouseleave",qe)),S&&(S.removeEventListener("focus",Ze),S.removeEventListener("blur",qe))}}C==="inline"&&n.appendChild(M)}let H=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":T&&C==="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=(Lt=s.closeButtonTooltipText)!=null?Lt:"Close chat",W=(dt=s.closeButtonShowTooltip)!=null?dt:!0;w.setAttribute("aria-label",L),w.style.display=t?"":"none";let E=(Wt=s.closeButtonIconName)!=null?Wt:"x",K=(Gt=s.closeButtonIconText)!=null?Gt:"\xD7";w.style.color=s.closeButtonColor||fn.actionIconColor;let Q=ye(E,"20px","currentColor",1);if(Q?w.appendChild(Q):w.textContent=K,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 P=s.closeButtonBorderWidth||"0px",$=s.closeButtonBorderColor||"transparent";w.style.border=`${P} solid ${$}`,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=""),H.appendChild(w),W&&L){let P=null,$=()=>{if(P)return;let Pe=w.ownerDocument,Fe=Pe.body;if(!Fe)return;P=Gn(Pe,"div","persona-clear-chat-tooltip"),P.textContent=L;let Ce=Gn(Pe,"div");Ce.className="persona-clear-chat-tooltip-arrow",P.appendChild(Ce);let be=w.getBoundingClientRect();P.style.position="fixed",P.style.zIndex=String(vr),P.style.left=`${be.left+be.width/2}px`,P.style.top=`${be.top-8}px`,P.style.transform="translate(-50%, -100%)",Fe.appendChild(P)},ne=()=>{P&&P.parentNode&&(P.parentNode.removeChild(P),P=null)};H.addEventListener("mouseenter",$),H.addEventListener("mouseleave",ne),w.addEventListener("focus",$),w.addEventListener("blur",ne),H._cleanupTooltip=()=>{ne(),H.removeEventListener("mouseenter",$),H.removeEventListener("mouseleave",ne),w.removeEventListener("focus",$),w.removeEventListener("blur",ne)}}return i!=="top-right"&&n.appendChild(H),{header:n,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:w,closeButtonWrapper:H,clearChatButton:S,clearChatButtonWrapper:M}},qr=(e,r,t)=>{var a,i,u,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(u=n.clearChat)==null?void 0:u.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 wr(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(vr)):(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 g of r){if(g.dividerBefore){let C=document.createElement("hr");a.appendChild(C)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let C=ye(g.icon,16,"currentColor",1.5);C&&x.appendChild(C)}let T=document.createElement("span");T.textContent=g.label,x.appendChild(T),x.addEventListener("click",C=>{C.stopPropagation(),p(),t(g.id)}),a.appendChild(x)}let i=null;function u(){if(!o)return;let g=n.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!n.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function It(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=ye(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function Vo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=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=ye(r,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function Jo(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 u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of r){let d;p.icon?d=It({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),n(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),n(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function zs(e){var g,x;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=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 d=ye(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(x=u.padding)!=null?x:"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 T,C;c.style.backgroundColor=(T=u.background)!=null?T:"",c.style.borderColor=(C=u.border)!=null?C:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=wr({items:n,onSelect:T=>{c.setAttribute("aria-expanded","false"),s(T)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",T=>{T.stopPropagation();let C=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",C?"false":"true"),f.toggle()}),c.addEventListener("keydown",T=>{(T.key==="Enter"||T.key===" ")&&(T.preventDefault(),c.click())}),{element:c,setLabel:T=>{p.textContent=T,c.setAttribute("aria-label",T)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Aa=e=>{var n;let r=ar({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 mu(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 u=ye(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=wr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Ea=e=>{var M,H,w,L,W,E,K,Q,X;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=zs({label:(H=a.title)!=null?H:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=fn.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=fn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),mu(c,s==null?void 0:s.trailingActions,(W=s==null?void 0:s.onAction)!=null?W:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let oe=s.onTitleClick;c.addEventListener("click",Ee=>{Ee.target.closest("button")||oe()}),c.addEventListener("keydown",Ee=>{(Ee.key==="Enter"||Ee.key===" ")&&(Ee.preventDefault(),oe())})}let O=s==null?void 0:s.titleRowHover;O&&(c.style.borderRadius=(E=O.borderRadius)!=null?E:"10px",c.style.padding=(K=O.padding)!=null?K:"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 oe,Ee;c.style.backgroundColor=(oe=O.background)!=null?oe:"",c.style.borderColor=(Ee=O.border)!=null?Ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(Q=a.closeButtonSize)!=null?Q:"32px",f=h("div",""),g=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");g.style.height=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||fn.actionIconColor;let x=(X=a.closeButtonIconName)!=null?X:"x",T=ye(x,"20px","currentColor",2);T?g.appendChild(T):g.textContent="\xD7",n&&g.addEventListener("click",n),f.appendChild(g),i.appendChild(f);let C=h("div");C.style.display="none";let S=h("span");return S.style.display="none",{header:i,iconHolder:C,headerTitle:p,headerSubtitle:S,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},qs={default:Aa,minimal:Ea},Ta=e=>{var r;return(r=qs[e])!=null?r:qs.default},lo=(e,r,t)=>{var a,i,u;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 d=h("span"),f=h("span"),g=h("button");g.style.display="none";let x=h("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Ta(n)({config:e,showClose:(u=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!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 co=e=>{var ge,Be,st,z,U,se,N,J,ce,fe,te,pe,Lt,dt,Wt,Gt,P,$,ne,Pe,Fe,Ce,be,at,mt,At,j;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=(Be=(ge=r==null?void 0:r.copy)==null?void 0:ge.inputPlaceholder)!=null?Be:"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 u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let xe=Math.min(o.scrollHeight,u);o.style.height=`${xe}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:{},d=(z=p.useIcon)!=null?z:!1,f=(U=p.iconText)!=null?U:"\u2191",g=p.iconName,x=(se=p.tooltipText)!=null?se:"Send message",T=(N=p.showTooltip)!=null?N:!1,C=(J=p.size)!=null?J:"40px",S=p.backgroundColor,M=p.textColor,H=h("div","persona-send-button-wrapper"),w=h("button",d?"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",""),d){if(w.style.width=C,w.style.height=C,w.style.minWidth=C,w.style.minHeight=C,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",M?w.style.color=M:w.style.color="var(--persona-button-primary-fg, #ffffff)",g){let xe=parseFloat(C)||24,ue=(M==null?void 0:M.trim())||"currentColor",Ze=ye(g,xe,ue,2);Ze?w.appendChild(Ze):w.textContent=f}else w.textContent=f;S?w.style.backgroundColor=S:w.classList.add("persona-bg-persona-primary")}else w.textContent=(fe=(ce=r==null?void 0:r.copy)==null?void 0:ce.sendButtonLabel)!=null?fe:"Send",M?w.style.color=M: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=""),T&&x){let xe=h("div","persona-send-button-tooltip");xe.textContent=x,H.appendChild(xe)}H.appendChild(w);let L=(te=r==null?void 0:r.voiceRecognition)!=null?te:{},W=L.enabled===!0,E=null,K=null,Q=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),X=((pe=L.provider)==null?void 0:pe.type)==="runtype";if(W&&(Q||X)){K=h("div","persona-send-button-wrapper"),E=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),E.type="button",E.setAttribute("data-persona-composer-mic",""),E.setAttribute("aria-label","Start voice recognition");let xe=(Lt=L.iconName)!=null?Lt:"mic",ue=(dt=L.iconSize)!=null?dt:C,Ze=parseFloat(ue)||24,qe=(Wt=L.backgroundColor)!=null?Wt:S,de=(Gt=L.iconColor)!=null?Gt:M;E.style.width=ue,E.style.height=ue,E.style.minWidth=ue,E.style.minHeight=ue,E.style.fontSize="18px",E.style.lineHeight="1",de?E.style.color=de:E.style.color="var(--persona-text, #111827)";let Ve=ye(xe,Ze,de||"currentColor",1.5);Ve?E.appendChild(Ve):E.textContent="\u{1F3A4}",qe&&(E.style.backgroundColor=qe),L.borderWidth&&(E.style.borderWidth=L.borderWidth,E.style.borderStyle="solid"),L.borderColor&&(E.style.borderColor=L.borderColor),L.paddingX&&(E.style.paddingLeft=L.paddingX,E.style.paddingRight=L.paddingX),L.paddingY&&(E.style.paddingTop=L.paddingY,E.style.paddingBottom=L.paddingY),K.appendChild(E);let vt=(P=L.tooltipText)!=null?P:"Start voice recognition";if((($=L.showTooltip)!=null?$:!1)&&vt){let pt=h("div","persona-send-button-tooltip");pt.textContent=vt,K.appendChild(pt)}}let oe=(ne=r==null?void 0:r.attachments)!=null?ne:{},Ee=oe.enabled===!0,ae=null,we=null,$e=null,he=null;if(Ee){he=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),he.style.display="none",$e=h("input"),$e.type="file",$e.accept=((Pe=oe.allowedTypes)!=null?Pe:sr).join(","),$e.multiple=((Fe=oe.maxFiles)!=null?Fe:4)>1,$e.style.display="none",$e.setAttribute("aria-label","Attach files"),we=h("div","persona-send-button-wrapper"),ae=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ae.type="button",ae.setAttribute("aria-label",(Ce=oe.buttonTooltipText)!=null?Ce:"Attach file");let xe=(be=oe.buttonIconName)!=null?be:"paperclip",ue=C,Ze=parseFloat(ue)||40,qe=Math.round(Ze*.6);ae.style.width=ue,ae.style.height=ue,ae.style.minWidth=ue,ae.style.minHeight=ue,ae.style.fontSize="18px",ae.style.lineHeight="1",ae.style.backgroundColor="transparent",ae.style.color="var(--persona-primary, #111827)",ae.style.border="none",ae.style.borderRadius="6px",ae.style.transition="background-color 0.15s ease",ae.addEventListener("mouseenter",()=>{ae.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ae.addEventListener("mouseleave",()=>{ae.style.backgroundColor="transparent"});let de=ye(xe,qe,"currentColor",1.5);de?ae.appendChild(de):ae.textContent="\u{1F4CE}",ae.addEventListener("click",vt=>{vt.preventDefault(),$e==null||$e.click()}),we.appendChild(ae);let Te=(at=oe.buttonTooltipText)!=null?at:"Attach file",Ve=h("div","persona-send-button-tooltip");Ve.textContent=Te,we.appendChild(Ve)}s.addEventListener("click",xe=>{xe.target!==w&&xe.target!==H&&xe.target!==E&&xe.target!==K&&xe.target!==ae&&xe.target!==we&&o.focus()}),he&&(he.style.gap="8px",s.append(he)),$e&&s.append($e),s.append(o);let We=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Re=h("div","persona-flex persona-items-center persona-gap-2");we&&Re.append(we);let ie=h("div","persona-flex persona-items-center persona-gap-1");K&&ie.append(K),ie.append(H),We.append(Re,ie),s.append(We);let Z=(mt=r==null?void 0:r.statusIndicator)!=null?mt:{},me=Z.align==="left"?"persona-text-left":Z.align==="center"?"persona-text-center":"persona-text-right",V=h("div",`persona-mt-2 ${me} persona-text-xs persona-text-persona-muted`);V.setAttribute("data-persona-composer-status","");let re=(At=Z.visible)!=null?At:!0;V.style.display=re?"":"none";let He=(j=Z.idleText)!=null?j:"Online";if(Z.idleLink){let xe=h("a");xe.href=Z.idleLink,xe.target="_blank",xe.rel="noopener noreferrer",xe.textContent=He,xe.style.color="inherit",xe.style.textDecoration="none",V.appendChild(xe)}else V.textContent=He;return t.append(n,s,V),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:H,micButton:E,micButtonWrapper:K,statusText:V,attachmentButton:ae,attachmentButtonWrapper:we,attachmentInput:$e,attachmentPreviewsContainer:he,actionsRow:We,leftActions:Re,rightActions:ie}};var Md=e=>{var c,p,d,f,g,x,T,C,S;let r=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Jt(e)){let M=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),H=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return M.appendChild(H),{wrapper:M,panel:H}}if(!r){let M=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),H=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),w=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return M.style.width=w,H.style.width="100%",M.appendChild(H),{wrapper:M,panel:H}}let n=(g=e==null?void 0:e.launcher)!=null?g:{},s=n.position&&jn[n.position]?jn[n.position]:jn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((T=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?T:gn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(S=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?S:e==null?void 0:e.launcherWidth,u=i!=null?i:An;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},kd=(e,r=!0)=>{var C,S,M,H,w,L,W,E,K;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=(C=e==null?void 0:e.layout)==null?void 0:C.header,s=((S=e==null?void 0:e.layout)==null?void 0:S.showHeader)!==!1,o=n?lo(e,n,{showClose:r}):ar({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=Jt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(H=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?H:"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.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((E=e==null?void 0:e.copy)==null?void 0:E.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let x=co({config:e}),T=((K=e==null?void 0:e.layout)==null?void 0:K.showFooter)!==!1;return s?qr(t,o,e):(o.header.style.display="none",qr(t,o,e)),t.append(a),T||(x.footer.style.display="none"),t.append(x.footer),{container:t,body:a,messagesWrapper:d,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions}};var gu=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},fu=320,hu=320,yu=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),bu=(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,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${fu}px`,c.style.maxHeight=`${hu}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}),gu(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}},Ur=()=>{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},Ma=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Ur};if(r){let s=r(n);if(s!==null)return s}return Ur()},xu=(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},Ld=(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},vu=(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},ka=(e,r,t)=>{var g,x,T,C,S,M;let n=(g=r.showCopy)!=null?g:!0,s=(x=r.showUpvote)!=null?x:!0,o=(T=r.showDownvote)!=null?T:!0;if(!n&&!s&&!o){let H=h("div");return H.style.display="none",H.id=`actions-${e.id}`,H.setAttribute("data-actions-for",e.id),H}let a=(C=r.visibility)!=null?C:"hover",i=(S=r.align)!=null?S:"right",u=(M=r.layout)!=null?M:"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"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(H,w,L)=>{let W=It({icon:H,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",L),W};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},po=(e,r,t,n,s,o)=>{var X,O,oe,Ee,ae,we,$e;let a=t!=null?t:{},i=(X=a.layout)!=null?X:"bubble",u=a.avatar,c=a.timestamp,p=(O=u==null?void 0:u.show)!=null?O:!1,d=(oe=c==null?void 0:c.show)!=null?oe:!1,f=(Ee=u==null?void 0:u.position)!=null?Ee:"left",g=(ae=c==null?void 0:c.position)!=null?ae:"below",x=vu(e.role,i),T=h("div",x.join(" "));T.id=`bubble-${e.id}`,T.setAttribute("data-message-id",e.id),T.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(T.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",T.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(T.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",T.style.color="var(--persona-message-assistant-text, var(--persona-text))");let C=yu(e),S=($e=(we=e.content)==null?void 0:we.trim())!=null?$e:"",H=C.length>0&&S===ks,w=document.createElement("div");w.classList.add("persona-message-content");let L=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(H?(W=document.createElement("div"),W.innerHTML=L,W.style.display="none",w.appendChild(W)):w.innerHTML=L,d&&g==="inline"&&e.createdAt){let he=Ld(e,c);he.classList.add("persona-ml-2","persona-inline"),w.appendChild(he)}if(C.length>0){let he=bu(C,!H&&!!S,()=>{H&&W&&(W.style.display="")});he?T.appendChild(he):H&&W&&(W.style.display="")}if(T.appendChild(w),d&&g==="below"&&e.createdAt){let he=Ld(e,c);he.classList.add("persona-mt-1"),T.appendChild(he)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let he=Ma("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);he&&T.appendChild(he)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let he=ka(e,n,s);T.appendChild(he)}if(!p||e.role==="system")return T;let K=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Q=xu(u,e.role);return f==="right"||f==="left"&&e.role==="user"?K.append(T,Q):K.append(Q,T),T.classList.remove("persona-max-w-[85%]"),T.classList.add("persona-max-w-[calc(85%-2.5rem)]"),K},Id=(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}):po(e,r,t,n,s,o)};var uo=new Set,Cu=(e,r)=>r==null?!1:typeof r=="string"?(e.textContent=r,!0):(e.appendChild(r),!0),wu=(e,r)=>{var n,s;let t=(s=(n=e.reasoning)==null?void 0:n.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,r).join(`
|
|
16
|
-
`):""},
|
|
17
|
-
`);let s=
|
|
18
|
-
`):""},Eu=(e,r)=>{var p,d,f,g,x;let t=e.toolCall,n=(p=r==null?void 0:r.features)==null?void 0:p.toolCallDisplay,s=(d=n==null?void 0:n.collapsedMode)!=null?d:"tool-call",o=Au(e,(f=n==null?void 0:n.previewMaxLines)!=null?f:3),a=t?ed(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=r==null?void 0:r.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=ga(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=ga(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},Wd=(e,r,t)=>{var p;let n=mo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t"),i=r.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=ye(n?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=n?"Hide":"Show"}a.style.display=n?"":"none",i&&(i.style.display=n?"none":i.textContent||i.childNodes.length?"":"none")},Ia=(e,r)=>{var oe,Ee,ae,we,$e,he,We,Re,ie;let t=e.toolCall,n=(oe=r==null?void 0:r.toolCall)!=null?oe:{},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=(ae=(Ee=r==null?void 0:r.features)==null?void 0:Ee.toolCallDisplay)!=null?ae:{},a=o.expandable!==!1,i=a&&mo.has(e.id),{summary:u,previewText:c,isActive:p}=Eu(e,r),d=h("button",a?"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":"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-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(d.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(d.style.paddingLeft=n.headerPaddingX,d.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(d.style.paddingTop=n.headerPaddingY,d.style.paddingBottom=n.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(g.style.color=n.headerTextColor);let x=String((we=t.startedAt)!=null?we:Date.now()),T=()=>{let Z=h("span","");return Z.setAttribute("data-tool-elapsed",x),Z.textContent=Ho(t),Z},C=(he=n.renderCollapsedSummary)==null?void 0:he.call(n,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:($e=o.collapsedMode)!=null?$e:"tool-call",isActive:p,config:r!=null?r:{},elapsed:Ho(t),createElapsedElement:T});typeof C=="string"&&C.trim()?(g.textContent=C,f.appendChild(g)):C instanceof HTMLElement?f.appendChild(C):(g.textContent=u,f.appendChild(g));let S=(We=o.loadingAnimation)!=null?We:"none",M=n.activeTextTemplate,H=n.completeTextTemplate,w=p?M:H,L=C instanceof HTMLElement,W=(Z,me,V)=>{let re=V;for(let He of me){let ge=h("span","persona-tool-char");ge.style.setProperty("--char-index",String(re)),ge.textContent=He===" "?"\xA0":He,Z.appendChild(ge),re++}return re},E=(Z,me)=>{var ge;g.textContent="";let V=((ge=t.name)==null?void 0:ge.trim())||"tool",re=ws(Z,V),He=0;for(let Be of re){let st=Be.styles.length>0?(()=>{let z=h("span",Be.styles.map(U=>`persona-tool-text-${U}`).join(" "));return g.appendChild(z),z})():g;if(Be.isDuration&&p)st.appendChild(T());else{let z=Be.isDuration?Ho(t):Be.text;me?He=W(st,z,He):st.appendChild(document.createTextNode(z))}}};if(!L)if(p&&S!=="none"){let Z=(Re=n.loadingAnimationDuration)!=null?Re:2e3;if(g.setAttribute("data-preserve-animation","true"),S==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),w&&E(w,!1);else if(g.classList.add(`persona-tool-loading-${S}`),g.style.setProperty("--persona-tool-anim-duration",`${Z}ms`),S==="shimmer-color"&&(n.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",n.loadingAnimationColor),n.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",n.loadingAnimationSecondaryColor)),w)E(w,!0);else{let me=g.textContent||u;g.textContent="",W(g,me,0)}}else w&&E(w,!1);let K=null;if(a){K=h("div","persona-flex persona-items-center");let Z=n.toggleTextColor||n.headerTextColor||"currentColor",me=ye(i?"chevron-up":"chevron-down",16,Z,2);me?K.appendChild(me):K.textContent=i?"Hide":"Show";let V=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");V.append(K),d.append(f,V)}else d.append(f);let Q=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(Q.setAttribute("data-persona-collapsed-preview","tool"),Q.style.display="none",Q.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let Z=(ie=n.renderCollapsedPreview)==null?void 0:ie.call(n,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:r!=null?r:{}});Su(Q,Z)||(Q.textContent=c),Q.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,Q),s;let X=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(X.style.display=i?"":"none",n.contentBackgroundColor&&(X.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(X.style.color=n.contentTextColor),n.contentPaddingX&&(X.style.paddingLeft=n.contentPaddingX,X.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(X.style.paddingTop=n.contentPaddingY,X.style.paddingBottom=n.contentPaddingY),t.name){let Z=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?Z.style.color=n.contentTextColor:n.headerTextColor&&(Z.style.color=n.headerTextColor),Z.textContent=t.name,X.appendChild(Z)}if(t.args!==void 0){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.textContent="Arguments";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=oo(t.args),Z.append(me,V),X.appendChild(Z)}if(t.chunks&&t.chunks.length){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.textContent="Activity";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=t.chunks.join(""),Z.append(me,V),X.appendChild(Z)}if(t.status==="complete"&&t.result!==void 0){let Z=h("div","persona-space-y-1"),me=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(me.style.color=n.labelTextColor),me.textContent="Result";let V=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");V.style.fontSize="0.75rem",V.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(V.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(V.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(V.style.color=n.codeBlockTextColor),V.textContent=oo(t.result),Z.append(me,V),X.appendChild(Z)}if(t.status==="complete"&&typeof t.duration=="number"){let Z=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(Z.style.color=n.contentTextColor),Z.textContent=`Duration: ${t.duration}ms`,X.appendChild(Z)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),K){K.innerHTML="";let Z=n.toggleTextColor||n.headerTextColor||"currentColor",me=ye(i?"chevron-up":"chevron-down",16,Z,2);me?K.appendChild(me):K.textContent=i?"Hide":"Show"}X.style.display=i?"":"none",Q.style.display=i?"none":Q.textContent||Q.childNodes.length?"":"none"})(),s.append(d,Q,X),s};var Pa=(e,r)=>{var T,C,S,M,H,w,L,W,E,K,Q,X;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=(T=n==null?void 0:n.backgroundColor)!=null?T:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(C=n==null?void 0:n.borderColor)!=null?C:"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 u=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)":(S=n==null?void 0:n.titleColor)!=null?S:"currentColor",p=ye(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(g.style.color=n.titleColor),g.textContent=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(g),!s){let O=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");O.setAttribute("data-approval-status",t.status),t.status==="approved"?(O.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",O.style.color="var(--persona-palette-colors-success-700, #15803d)",O.textContent="Approved"):t.status==="denied"?(O.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",O.style.color="var(--persona-palette-colors-error-700, #b91c1c)",O.textContent="Denied"):t.status==="timeout"&&(O.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",O.style.color="var(--persona-palette-colors-warning-700, #b45309)",O.textContent="Timeout"),f.appendChild(O)}d.appendChild(f);let x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(x.style.color=n.descriptionColor),x.textContent=t.description,d.appendChild(x),t.parameters){let O=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&&(O.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(O.style.color=n.parameterTextColor),O.style.fontSize="0.75rem",O.style.lineHeight="1rem",O.textContent=oo(t.parameters),d.appendChild(O)}if(s){let O=h("div","persona-flex persona-gap-2 persona-mt-2");O.setAttribute("data-approval-buttons","true");let oe=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");oe.type="button",oe.style.backgroundColor=(H=n==null?void 0:n.approveButtonColor)!=null?H:"var(--persona-approval-approve-bg, #22c55e)",oe.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",oe.setAttribute("data-approval-action","approve");let Ee=ye("shield-check",14,(L=n==null?void 0:n.approveButtonTextColor)!=null?L:"#ffffff",2);Ee&&(Ee.style.marginRight="4px",oe.appendChild(Ee));let ae=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");oe.appendChild(ae);let we=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");we.type="button",we.style.backgroundColor=(E=n==null?void 0:n.denyButtonColor)!=null?E:"transparent",we.style.color=(K=n==null?void 0:n.denyButtonTextColor)!=null?K:"var(--persona-feedback-error, #dc2626)",we.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,we.setAttribute("data-approval-action","deny");let $e=ye("shield-x",14,(Q=n==null?void 0:n.denyButtonTextColor)!=null?Q:"var(--persona-feedback-error, #dc2626)",2);$e&&($e.style.marginRight="4px",we.appendChild($e));let he=document.createTextNode((X=n==null?void 0:n.denyLabel)!=null?X:"Deny");we.appendChild(he),O.append(oe,we),d.appendChild(O)}return a.append(i,d),o.appendChild(a),o};var Rd=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(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){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(g=>{let x=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");x.type="button",x.textContent=g,x.disabled=d,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(x),r.push(x)}),e.appendChild(p)}}};var Go=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 Yo=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 go(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Tu={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)"}},Mu={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},ku=["flowName","stepName","reasoningText","text","name","tool","toolName"],Lu=100;function Iu(e,r){let t={...Tu,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Mu}function Pu(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Wu(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 Ru(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 Hu(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 Bu(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 Du(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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=n,i.appendChild(u),i}}function Wa(e,r,t,n,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");go(c,(f=n.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var oe,Ee;let g=h("div",""),x=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");x.setAttribute("data-event-id",e.id);let T=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),C=ye(u?"chevron-down":"chevron-right","14px","currentColor",2);C&&T.appendChild(C);let S=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(oe=n.timestampFormat)!=null?oe:"relative";S.textContent=M==="relative"?Pu(e.timestamp,t):Wu(e.timestamp);let H=null;n.showSequenceNumbers!==!1&&(H=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),H.textContent=String(r+1));let w=Iu(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 W=(Ee=n.descriptionFields)!=null?Ee:ku,E=Ru(e.payload,W),K=null;E&&(K=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),K.textContent=E);let Q=h("div","persona-flex-1 persona-min-w-0"),X=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"),O=ye("clipboard","12px","currentColor",1.5);return O&&X.appendChild(O),X.addEventListener("click",async ae=>{ae.stopPropagation(),await Hu(Bu(e)),X.innerHTML="";let we=ye("check","12px","currentColor",1.5);we&&X.appendChild(we),setTimeout(()=>{X.innerHTML="";let $e=ye("clipboard","12px","currentColor",1.5);$e&&X.appendChild($e)},1500)}),x.appendChild(T),x.appendChild(S),H&&x.appendChild(H),x.appendChild(L),K&&x.appendChild(K),x.appendChild(Q),x.appendChild(X),g.appendChild(x),u&&g.appendChild(Du(e,a,i)),g}}function Hd(e){var g,x,T,C,S;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(x=a==null?void 0:a.iconName)!=null?x:"arrow-down",c=(T=a==null?void 0:a.label)!=null?T:"",p=(S=(C=s==null?void 0:s.features)==null?void 0:C.eventStream)!=null?S:{},d=o.find(M=>M.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let M=d.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>f().element,onClose:n});if(M)return{element:M,update:()=>{},destroy:()=>{}}}return f();function f(){let M=p.classNames,H=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");go(H,M==null?void 0:M.panel);let w=[],L="",W="",E=null,K=[],Q={},X=0,O=Os(),oe=0,Ee=0,ae=!1,we=null,$e=!1,he=0,We=new Set,Re=new Map,ie="",Z="",me=null,V,re,He,ge,Be;function st(){let de=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),Te=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");go(Te,M==null?void 0:M.headerBar);let Ve=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ve.textContent="Events",V=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"),V.textContent="0";let vt=h("div","persona-flex-1");re=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",re.appendChild(Ot),He=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"),He.type="button",He.title="Copy All";let $t=ye("clipboard-copy","12px","currentColor",1.5);$t&&He.appendChild($t);let ht=h("span","persona-text-xs");ht.textContent="Copy All",He.appendChild(ht),Te.appendChild(Ve),Te.appendChild(V),Te.appendChild(vt),Te.appendChild(re),Te.appendChild(He);let Qe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");go(Qe,M==null?void 0:M.searchBar);let yt=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),je=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");yt&&je.appendChild(yt),ge=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"),go(ge,M==null?void 0:M.searchInput),ge.type="text",ge.placeholder="Search event payloads...",Be=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"),Be.type="button",Be.style.display="none";let _t=ye("x","12px","currentColor",2);return _t&&Be.appendChild(_t),Qe.appendChild(je),Qe.appendChild(ge),Qe.appendChild(Be),de.appendChild(Te),de.appendChild(Qe),de}let z,U=o.find(de=>de.renderEventStreamToolbar);if(U!=null&&U.renderEventStreamToolbar&&s){let de=U.renderEventStreamToolbar({config:s,defaultRenderer:()=>st(),eventCount:r.getSize(),filteredCount:0,onFilterChange:Te=>{L=Te,Gt(),ne()},onSearchChange:Te=>{W=Te,Gt(),ne()}});z=de!=null?de:st()}else z=st();let se=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");se.style.display="none";let N=h("div","persona-flex-1 persona-min-h-0 persona-relative"),J=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");J.style.height="100%";let ce=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");go(ce,M==null?void 0:M.scrollIndicator),ce.style.display="none",ce.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let fe=ye(u,"14px","currentColor",2);fe&&ce.appendChild(fe);let te=h("span","");te.textContent=c,ce.appendChild(te);let pe=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");pe.style.display="none",N.appendChild(J),N.appendChild(pe),N.appendChild(ce),H.setAttribute("tabindex","0"),H.appendChild(z),H.appendChild(se),H.appendChild(N);function Lt(){let de=r.getAll(),Te={};for(let ht of de)Te[ht.type]=(Te[ht.type]||0)+1;let Ve=Object.keys(Te).sort(),vt=Ve.length!==K.length||!Ve.every((ht,Qe)=>ht===K[Qe]),Ot=!vt&&Ve.some(ht=>Te[ht]!==Q[ht]),pt=de.length!==Object.values(Q).reduce((ht,Qe)=>ht+Qe,0);if(!vt&&!Ot&&!pt||(K=Ve,Q=Te,!re))return;let $t=re.value;if(re.options[0].textContent="All events",vt){for(;re.options.length>1;)re.remove(1);for(let ht of Ve){let Qe=h("option","");Qe.value=ht,Qe.textContent=`${ht} (${Te[ht]||0})`,re.appendChild(Qe)}$t&&Ve.includes($t)?re.value=$t:$t&&(re.value="",L="")}else for(let ht=1;ht<re.options.length;ht++){let Qe=re.options[ht];Qe.textContent=`${Qe.value} (${Te[Qe.value]||0})`}}function dt(){let de=r.getAll();if(L&&(de=de.filter(Te=>Te.type===L)),W){let Te=W.toLowerCase();de=de.filter(Ve=>Ve.type.toLowerCase().includes(Te)||Ve.payload.toLowerCase().includes(Te))}return de}function Wt(){return L!==""||W!==""}function Gt(){X=0,oe=0,O.resume(),ce.style.display="none"}function P(de){We.has(de)?We.delete(de):We.add(de),me=de;let Te=J.scrollTop,Ve=O.isFollowing();$e=!0,O.pause(),ne(),J.scrollTop=Te,Ve&&O.resume(),$e=!1}function $(){return zo(J,50)}function ne(){Ee=Date.now(),ae=!1,Lt();let de=r.getEvictedCount();de>0?(se.textContent=`${de.toLocaleString()} older events truncated`,se.style.display=""):se.style.display="none",w=dt();let Te=w.length,Ve=r.getSize()>0;V&&(V.textContent=String(r.getSize())),Te===0&&Ve&&Wt()?(pe.textContent=W?`No events matching '${W}'`:"No events matching filter",pe.style.display="",J.style.display="none"):(pe.style.display="none",J.style.display=""),He&&(He.title=Wt()?`Copy Filtered (${Te})`:"Copy All"),i&&!O.isFollowing()&&Te>X&&(oe+=Te-X,te.textContent=c?`${c}${oe>0?` (${oe})`:""}`:"",ce.style.display=""),X=Te;let vt=r.getAll(),Ot=vt.length>0?vt[0].timestamp:0,pt=new Set(w.map(Qe=>Qe.id));for(let Qe of We)pt.has(Qe)||We.delete(Qe);let $t=L!==ie||W!==Z,ht=Re.size===0&&w.length>0;if($t||ht||w.length===0){J.innerHTML="",Re.clear();let Qe=document.createDocumentFragment();for(let yt=0;yt<w.length;yt++){let je=Wa(w[yt],yt,Ot,p,We,P,o,s);Re.set(w[yt].id,je),Qe.appendChild(je)}J.appendChild(Qe),ie=L,Z=W,me=null}else{if(me!==null){let yt=Re.get(me);if(yt&&yt.parentNode===J){let je=w.findIndex(_t=>_t.id===me);if(je>=0){let _t=Wa(w[je],je,Ot,p,We,P,o,s);J.insertBefore(_t,yt),yt.remove(),Re.set(me,_t)}}me=null}let Qe=new Set(w.map(yt=>yt.id));for(let[yt,je]of Re)Qe.has(yt)||(je.remove(),Re.delete(yt));for(let yt=0;yt<w.length;yt++){let je=w[yt];if(!Re.has(je.id)){let _t=Wa(je,yt,Ot,p,We,P,o,s);Re.set(je.id,_t),J.appendChild(_t)}}}O.isFollowing()&&(J.scrollTop=J.scrollHeight)}function Pe(){if(Date.now()-Ee>=Lu){we!==null&&(cancelAnimationFrame(we),we=null),ne();return}ae||(ae=!0,we=requestAnimationFrame(()=>{we=null,ne()}))}let Fe=(de,Te)=>{if(!He)return;He.innerHTML="";let Ve=ye(de,"12px","currentColor",1.5);Ve&&He.appendChild(Ve);let vt=h("span","persona-text-xs");vt.textContent="Copy All",He.appendChild(vt),setTimeout(()=>{He.innerHTML="";let Ot=ye("clipboard-copy","12px","currentColor",1.5);Ot&&He.appendChild(Ot);let pt=h("span","persona-text-xs");pt.textContent="Copy All",He.appendChild(pt),He.disabled=!1},Te)},Ce=async()=>{if(He){He.disabled=!0;try{let de;Wt()?de=w:t?(de=await t(),de.length===0&&(de=r.getAll())):de=r.getAll();let Te=de.map(Ve=>{try{return JSON.parse(Ve.payload)}catch{return Ve.payload}});await navigator.clipboard.writeText(JSON.stringify(Te,null,2)),Fe("check",1500)}catch{Fe("x",1500)}}},be=()=>{re&&(L=re.value,Gt(),ne())},at=()=>{!ge||!Be||(Be.style.display=ge.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{W=ge.value,Gt(),ne()},150))},mt=()=>{!ge||!Be||(ge.value="",W="",Be.style.display="none",E&&clearTimeout(E),Gt(),ne())},At=()=>{if($e)return;let de=J.scrollTop,{action:Te,nextLastScrollTop:Ve}=$s({following:O.isFollowing(),currentScrollTop:de,lastScrollTop:he,nearBottom:$(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});he=Ve,Te==="resume"?(O.resume(),oe=0,ce.style.display="none"):Te==="pause"&&(O.pause(),i&&(te.textContent=c,ce.style.display=""))},j=de=>{let Te=_s({following:O.isFollowing(),deltaY:de.deltaY,nearBottom:$(),resumeWhenNearBottom:!0});Te==="pause"?(O.pause(),i&&(te.textContent=c,ce.style.display="")):Te==="resume"&&(O.resume(),oe=0,ce.style.display="none")},xe=()=>{i&&(J.scrollTop=J.scrollHeight,O.resume(),oe=0,ce.style.display="none")},ue=de=>{let Te=de.target;if(!Te||Te.closest("button"))return;let Ve=Te.closest("[data-event-id]");if(!Ve)return;let vt=Ve.getAttribute("data-event-id");vt&&P(vt)},Ze=de=>{if((de.metaKey||de.ctrlKey)&&de.key==="f"){de.preventDefault(),ge==null||ge.focus(),ge==null||ge.select();return}de.key==="Escape"&&(ge&&document.activeElement===ge?(mt(),ge.blur(),H.focus()):n&&n())};He&&He.addEventListener("click",Ce),re&&re.addEventListener("change",be),ge&&ge.addEventListener("input",at),Be&&Be.addEventListener("click",mt),J.addEventListener("scroll",At),J.addEventListener("wheel",j,{passive:!0}),J.addEventListener("click",ue),ce.addEventListener("click",xe),H.addEventListener("keydown",Ze);function qe(){E&&clearTimeout(E),we!==null&&(cancelAnimationFrame(we),we=null),ae=!1,Re.clear(),He&&He.removeEventListener("click",Ce),re&&re.removeEventListener("change",be),ge&&ge.removeEventListener("input",at),Be&&Be.removeEventListener("click",mt),J.removeEventListener("scroll",At),J.removeEventListener("wheel",j),J.removeEventListener("click",ue),ce.removeEventListener("click",xe),H.removeEventListener("keydown",Ze)}return{element:H,update:Pe,destroy:qe}}}function Bd(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 u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.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",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,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 Dd=(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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:r.config,defaultRenderer:()=>Bd(e,r)});if(p)return p}return Bd(e,r)};var Ra=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)})}},ir=new Ra;ir.register("PersonaArtifactCard",Dd);function Nu(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 Nd(e,r){var He,ge,Be,st;let t=(ge=(He=e.features)==null?void 0:He.artifacts)==null?void 0:ge.layout,s=((Be=t==null?void 0:t.toolbarPreset)!=null?Be:"default")==="document",o=(st=t==null?void 0:t.panePadding)==null?void 0:st.trim(),a=e.markdown?Nr(e.markdown):null,i=ro(e.sanitize),u=z=>{let U=a?a(z):no(z);return i?i(U):U},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"),d.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};c&&c.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.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 g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let T="rendered",C=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),S=s?It({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):It({icon:"eye",label:"Rendered view"}),M=s?It({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):It({icon:"code-2",label:"Source"}),H=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,W=t==null?void 0:t.documentToolbarCopyMenuItems,E=!!(L&&W&&W.length>0),K=null,Q,X=null,O=null;if(s&&(w||L)&&!E){if(Q=w?Vo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),L){let z=ye("chevron-down",14,"currentColor",2);z&&Q.appendChild(z)}}else s&&E?(K=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Q=w?Vo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):It({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),X=It({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"}}),K.append(Q,X)):s?Q=It({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):Q=It({icon:"copy",label:"Copy"});let oe=s?It({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):It({icon:"refresh-cw",label:"Refresh"}),Ee=s?It({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):It({icon:"x",label:"Close"}),ae=()=>{var J,ce,fe;let z=(J=ie.find(te=>te.id===Z))!=null?J:ie[ie.length-1],U=(ce=z==null?void 0:z.id)!=null?ce:null,se=(z==null?void 0:z.artifactType)==="markdown"&&(fe=z.markdown)!=null?fe:"",N=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:se,jsonPayload:N,id:U}},we=async()=>{var J;let{markdown:z,jsonPayload:U}=ae(),se=(J=ie.find(ce=>ce.id===Z))!=null?J:ie[ie.length-1],N=(se==null?void 0:se.artifactType)==="markdown"?z:se?U:"";try{await navigator.clipboard.writeText(N)}catch{}};if(Q.addEventListener("click",async()=>{let z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(z&&E){let{markdown:U,jsonPayload:se,id:N}=ae();try{await z({actionId:"primary",artifactId:N,markdown:U,jsonPayload:se})}catch{}return}await we()}),X&&(W!=null&&W.length)){let z=()=>{var se;return(se=d.closest("[data-persona-root]"))!=null?se:document.body},U=()=>{O=wr({items:W.map(se=>({id:se.id,label:se.label})),onSelect:async se=>{let{markdown:N,jsonPayload:J,id:ce}=ae(),fe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{fe?await fe({actionId:se,artifactId:ce,markdown:N,jsonPayload:J}):se==="markdown"||se==="md"?await navigator.clipboard.writeText(N):se==="json"||se==="source"?await navigator.clipboard.writeText(J):await navigator.clipboard.writeText(N||J)}catch{}},anchor:K!=null?K:X,position:"bottom-right",portal:z()})};d.isConnected?U():requestAnimationFrame(U),X.addEventListener("click",se=>{se.stopPropagation(),O==null||O.toggle()})}oe.addEventListener("click",async()=>{var z;try{await((z=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:z.call(t))}catch{}V()}),Ee.addEventListener("click",()=>{var z;p(),(z=r.onDismiss)==null||z.call(r)});let $e=()=>{s&&(S.setAttribute("aria-pressed",T==="rendered"?"true":"false"),M.setAttribute("aria-pressed",T==="source"?"true":"false"))};S.addEventListener("click",()=>{T="rendered",$e(),V()}),M.addEventListener("click",()=>{T="source",$e(),V()});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(),C.append(S,M),K?H.append(K,oe,Ee):H.append(Q,oe,Ee),f.append(C,he,H),$e()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let We=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"),Re=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(We.style.paddingLeft=o,We.style.paddingRight=o,Re.style.padding=o),d.appendChild(f),d.appendChild(We),d.appendChild(Re);let ie=[],Z=null,me=!1,V=()=>{var N,J,ce,fe;let z=s&&ie.length<=1;We.classList.toggle("persona-hidden",z),We.replaceChildren();for(let te of ie){let pe=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");pe.type="button",pe.textContent=te.title||te.id.slice(0,8),te.id===Z&&pe.classList.add("persona-bg-persona-container","persona-border-persona-border"),pe.addEventListener("click",()=>r.onSelect(te.id)),We.appendChild(pe)}Re.replaceChildren();let U=Z&&ie.find(te=>te.id===Z)||ie[ie.length-1];if(!U)return;if(s){let te=U.artifactType==="markdown"?"MD":(N=U.component)!=null?N:"Component",Lt=(U.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";he.textContent=`${Lt} \xB7 ${te}`}else g.textContent="Artifacts";if(U.artifactType==="markdown"){if(s&&T==="source"){let pe=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");pe.textContent=(J=U.markdown)!=null?J:"",Re.appendChild(pe);return}let te=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");te.innerHTML=u((ce=U.markdown)!=null?ce:""),Re.appendChild(te);return}let se=U.component?ir.get(U.component):void 0;if(se){let pe={message:{id:U.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Lt=se((fe=U.props)!=null?fe:{},pe);if(Lt){Re.appendChild(Lt);return}}catch{}}Re.appendChild(Nu(U))},re=()=>{var U;let z=ie.length>0;if(d.classList.toggle("persona-hidden",!z),c){let se=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,J=((U=se==null?void 0:se.classList.contains("persona-artifact-narrow-host"))!=null?U:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;z&&J&&me?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(z){var U,se,N;ie=z.artifacts,Z=(N=(se=z.selectedId)!=null?se:(U=z.artifacts[z.artifacts.length-1])==null?void 0:U.id)!=null?N:null,ie.length>0&&(me=!0),V(),re()},setMobileOpen(z){me=z,!z&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):re()}}}function Wn(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 Fd(e,r){var o,a,i,u;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"),!Wn(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=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.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 Fu(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 Us(e,r){var u,c,p,d,f,g,x,T,C,S;if(!Wn(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"),Fu(e),Fd(e,r);return}let t=(c=(u=r.features)==null?void 0:u.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",(d=t==null?void 0:t.paneWidth)!=null?d:"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=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(T=t==null?void 0:t.documentToolbarIconColor)==null?void 0:T.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(C=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:C.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(S=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:S.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Fd(e,r)}var Od=["panel","seamless"];function Vs(e,r){var i,u,c,p,d,f;for(let g of Od)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!Wn(r))return;let t=(u=(i=r.features)==null?void 0:i.artifacts)==null?void 0:u.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Od.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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function $d(e,r){var t,n,s;return!r||!Wn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Ou(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 $u(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 _u(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function ju(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function _d(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 jd(e,r,t,n,s,o){let a=Ou(s,200),i=ju(r,t,n,200);i=Math.max(a,i);let u=$u(o);return u!==null&&(i=Math.min(i,u)),_u(e,a,i)}var zd={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"}},Ha=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,T,C;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(T=zd[a])!=null?T:zd.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let S=h("p","persona-text-sm persona-text-persona-muted");S.textContent=i.description,u.appendChild(S)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(S=>{var W,E;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${S.name}`;let H=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");H.textContent=S.label,M.appendChild(H);let w=(W=S.type)!=null?W:"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}-${S.name}`,L.name=S.name,L.placeholder=(E=S.placeholder)!=null?E:"",S.required&&(L.required=!0),M.appendChild(L),p.appendChild(M)});let d=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]"),g=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");g.type="submit",g.textContent=(C=i.submitLabel)!=null?C:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async S=>{var L,W;S.preventDefault();let M=(L=t.formEndpoint)!=null?L:"/form",H=new FormData(p),w={};H.forEach((E,K)=>{w[K]=E}),w.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let E=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!E.ok)throw new Error(`Form submission failed (${E.status})`);let K=await E.json();f.textContent=(W=K.message)!=null?W:"Thanks! We'll be in touch soon.",K.success&&K.nextPrompt&&await n.sendMessage(String(K.nextPrompt))}catch(E){f.textContent=E instanceof Error?E.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var Ba=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,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Ko=new Ba;var qd=()=>{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(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var zu=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},qu=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},Xo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=zu(e),t=qu(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}},Da=e=>typeof e=="string"?e:e==null?"":String(e),Vr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Da(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Da(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:Da(t.text)}}},Ud=e=>Array.isArray(e)?e.map(r=>String(r)):[],Zo=e=>{let r=new Set(Ud(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Ud(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 u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Uu=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}},Vu=e=>e.map(r=>({...r,streaming:!1})),Js=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?Uu(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?Vu(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 fo=require("partial-json");function Ju(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Gu(e,r){if(!Ju(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 Gs(){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,fo.parse)(t,fo.STR|fo.OBJ),o=Gu(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Vd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ys(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=ir.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 Jd(){let e=Gs();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ks(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 Xs(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 Yu=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Zs(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:u=!0,ratingLabels:c=Yu}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,g.appendChild(x);let T=document.createElement("p");T.className="persona-feedback-subtitle",T.textContent=s,g.appendChild(T),f.appendChild(g);let C=document.createElement("div");C.className="persona-feedback-rating persona-feedback-rating-csat",C.setAttribute("role","radiogroup"),C.setAttribute("aria-label","Satisfaction rating from 1 to 5");let S=[];for(let W=1;W<=5;W++){let E=document.createElement("button");E.type="button",E.className="persona-feedback-rating-btn persona-feedback-star-btn",E.setAttribute("role","radio"),E.setAttribute("aria-checked","false"),E.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),E.title=c[W-1],E.dataset.rating=String(W),E.innerHTML=`
|
|
16
|
+
`,t.addEventListener("click",n);let r=o=>{var j,A,R,T,P,H,J,U,$,ie,be,pe,Ne,me;let a=(j=o.launcher)!=null?j:{},i=Jt(o),u=t.querySelector("[data-role='launcher-title']");if(u){let Re=(A=a.title)!=null?A:"Chat Assistant";u.textContent=Re,u.setAttribute("title",Re)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let Re=(R=a.subtitle)!=null?R:"Get answers fast";c.textContent=Re,c.setAttribute("title",Re)}let p=t.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let Re=(T=a.agentIconSize)!=null?T:"40px";if(d.style.height=Re,d.style.width=Re,d.innerHTML="",a.agentIconName){let Ee=parseFloat(Re)||24,He=ye(a.agentIconName,Ee*.6,"var(--persona-text-inverse, #ffffff)",2);He?(d.appendChild(He),d.style.display=""):(d.textContent=(P=a.agentIconText)!=null?P:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(H=a.agentIconText)!=null?H:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let Re=(J=a.agentIconSize)!=null?J:"40px";f.style.height=Re,f.style.width=Re,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let g=t.querySelector("[data-role='launcher-call-to-action-icon']");if(g){let Re=(U=a.callToActionIconSize)!=null?U:"32px";g.style.height=Re,g.style.width=Re,a.callToActionIconBackgroundColor?(g.style.backgroundColor=a.callToActionIconBackgroundColor,g.classList.remove("persona-bg-persona-primary")):(g.style.backgroundColor="",g.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(g.style.color=a.callToActionIconColor,g.classList.remove("persona-text-persona-call-to-action")):(g.style.color="",g.classList.add("persona-text-persona-call-to-action"));let Ee=0;if(a.callToActionIconPadding?(g.style.boxSizing="border-box",g.style.padding=a.callToActionIconPadding,Ee=(parseFloat(a.callToActionIconPadding)||0)*2):(g.style.boxSizing="",g.style.padding=""),a.callToActionIconHidden)g.style.display="none";else if(g.style.display=i?"none":"",g.innerHTML="",a.callToActionIconName){let He=parseFloat(Re)||24,de=Math.max(He-Ee,8),Q=ye(a.callToActionIconName,de,"currentColor",2);Q?g.appendChild(Q):g.textContent=($=a.callToActionIconText)!=null?$:"\u2197"}else g.textContent=(ie=a.callToActionIconText)!=null?ie:"\u2197"}let x=a.position&&Yn[a.position]?Yn[a.position]:Yn["bottom-right"],E="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",v="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?v:`${E} ${x}`,i||(t.style.zIndex=String((be=a.zIndex)!=null?be:vn));let w="1px solid var(--persona-border, #e5e7eb)",I="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=(pe=a.border)!=null?pe:w,t.style.boxShadow=(Ne=a.shadow)!=null?Ne:I,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=(me=a.collapsedMaxWidth)!=null?me:"",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Cn={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))"},ur=e=>{var U,$,ie,be,pe,Ne,me,Re,Ee,He,de,Q,he,X,ge,ue,oe,Te,Me,k,V,ae,D,q,le,xe,ee,se,Et,ht,Ve,Xt;let{config:n,showClose:t=!0}=e,r=h("div","persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5");r.setAttribute("data-persona-theme-zone","header"),r.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",r.style.boxShadow="var(--persona-header-shadow, none)",r.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let s=(U=n==null?void 0:n.launcher)!=null?U:{},o=($=s.headerIconSize)!=null?$:"48px",a=(ie=s.closeButtonSize)!=null?ie:"32px",i=(be=s.closeButtonPlacement)!=null?be:"inline",u=(pe=s.headerIconHidden)!=null?pe:!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))",!u)if(c){let Qe=parseFloat(o)||24,fe=ye(c,Qe*.6,"currentColor",1);fe?p.replaceChildren(fe):p.textContent=(me=(Ne=n==null?void 0:n.launcher)==null?void 0:Ne.agentIconText)!=null?me:"\u{1F4AC}"}else if((Re=n==null?void 0:n.launcher)!=null&&Re.iconUrl){let Qe=h("img");Qe.src=n.launcher.iconUrl,Qe.alt="",Qe.className="persona-rounded-xl persona-object-cover",Qe.style.height=o,Qe.style.width=o,p.replaceChildren(Qe)}else p.textContent=(He=(Ee=n==null?void 0:n.launcher)==null?void 0:Ee.agentIconText)!=null?He:"\u{1F4AC}";let d=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=Cn.titleColor,f.textContent=(Q=(de=n==null?void 0:n.launcher)==null?void 0:de.title)!=null?Q:"Chat Assistant";let g=h("span","persona-text-xs");g.style.color=Cn.subtitleColor,g.textContent=(X=(he=n==null?void 0:n.launcher)==null?void 0:he.subtitle)!=null?X:"Here to help you get answers fast",d.append(f,g),u?r.append(d):r.append(p,d);let x=(ge=s.clearChat)!=null?ge:{},E=(ue=x.enabled)!=null?ue:!0,v=(oe=x.placement)!=null?oe:"inline",w=null,I=null;if(E){let Qe=(Te=x.size)!=null?Te:"32px",fe=(Me=x.iconName)!=null?Me:"refresh-cw",Ke=(k=x.iconColor)!=null?k:"",Bt=(V=x.backgroundColor)!=null?V:"",Dt=(ae=x.borderWidth)!=null?ae:"",W=(D=x.borderColor)!=null?D:"",re=(q=x.borderRadius)!=null?q:"",Ie=(le=x.paddingX)!=null?le:"",Oe=(xe=x.paddingY)!=null?xe:"",Je=(ee=x.tooltipText)!=null?ee:"Clear chat",Ye=(se=x.showTooltip)!=null?se:!0;I=h("div",v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),v==="top-right"&&(I.style.right="48px"),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=Qe,w.style.width=Qe,w.type="button",w.setAttribute("aria-label",Je),w.style.color=Ke||Cn.actionIconColor;let L=ye(fe,"20px","currentColor",1);if(L&&(L.style.display="block",w.appendChild(L)),Bt&&(w.style.backgroundColor=Bt,w.classList.remove("hover:persona-bg-gray-100")),Dt||W){let ve=Dt||"0px",De=W||"transparent";w.style.border=`${ve} solid ${De}`,w.classList.remove("persona-border-none")}if(re&&(w.style.borderRadius=re,w.classList.remove("persona-rounded-full")),Ie?(w.style.paddingLeft=Ie,w.style.paddingRight=Ie):(w.style.paddingLeft="",w.style.paddingRight=""),Oe?(w.style.paddingTop=Oe,w.style.paddingBottom=Oe):(w.style.paddingTop="",w.style.paddingBottom=""),I.appendChild(w),Ye&&Je&&w&&I){let ve=null,De=()=>{if(ve||!w)return;let Z=w.ownerDocument,ne=Z.body;if(!ne)return;ve=er(Z,"div","persona-clear-chat-tooltip"),ve.textContent=Je;let _e=er(Z,"div");_e.className="persona-clear-chat-tooltip-arrow",ve.appendChild(_e);let lt=w.getBoundingClientRect();ve.style.position="fixed",ve.style.zIndex=String(Lr),ve.style.left=`${lt.left+lt.width/2}px`,ve.style.top=`${lt.top-8}px`,ve.style.transform="translate(-50%, -100%)",ne.appendChild(ve)},it=()=>{ve&&ve.parentNode&&(ve.parentNode.removeChild(ve),ve=null)};I.addEventListener("mouseenter",De),I.addEventListener("mouseleave",it),w.addEventListener("focus",De),w.addEventListener("blur",it),I._cleanupTooltip=()=>{it(),I&&(I.removeEventListener("mouseenter",De),I.removeEventListener("mouseleave",it)),w&&(w.removeEventListener("focus",De),w.removeEventListener("blur",it))}}v==="inline"&&r.appendChild(I)}let j=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":E&&v==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center"),A=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");A.style.height=a,A.style.width=a,A.type="button";let R=(Et=s.closeButtonTooltipText)!=null?Et:"Close chat",T=(ht=s.closeButtonShowTooltip)!=null?ht:!0;A.setAttribute("aria-label",R),A.style.display=t?"":"none";let P=(Ve=s.closeButtonIconName)!=null?Ve:"x",H=(Xt=s.closeButtonIconText)!=null?Xt:"\xD7";A.style.color=s.closeButtonColor||Cn.actionIconColor;let J=ye(P,"28px","currentColor",1);if(J?(J.style.display="block",A.appendChild(J)):A.textContent=H,s.closeButtonBackgroundColor?(A.style.backgroundColor=s.closeButtonBackgroundColor,A.classList.remove("hover:persona-bg-gray-100")):(A.style.backgroundColor="",A.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Qe=s.closeButtonBorderWidth||"0px",fe=s.closeButtonBorderColor||"transparent";A.style.border=`${Qe} solid ${fe}`,A.classList.remove("persona-border-none")}else A.style.border="",A.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(A.style.borderRadius=s.closeButtonBorderRadius,A.classList.remove("persona-rounded-full")):(A.style.borderRadius="",A.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(A.style.paddingLeft=s.closeButtonPaddingX,A.style.paddingRight=s.closeButtonPaddingX):(A.style.paddingLeft="",A.style.paddingRight=""),s.closeButtonPaddingY?(A.style.paddingTop=s.closeButtonPaddingY,A.style.paddingBottom=s.closeButtonPaddingY):(A.style.paddingTop="",A.style.paddingBottom=""),j.appendChild(A),T&&R){let Qe=null,fe=()=>{if(Qe)return;let Bt=A.ownerDocument,Dt=Bt.body;if(!Dt)return;Qe=er(Bt,"div","persona-clear-chat-tooltip"),Qe.textContent=R;let W=er(Bt,"div");W.className="persona-clear-chat-tooltip-arrow",Qe.appendChild(W);let re=A.getBoundingClientRect();Qe.style.position="fixed",Qe.style.zIndex=String(Lr),Qe.style.left=`${re.left+re.width/2}px`,Qe.style.top=`${re.top-8}px`,Qe.style.transform="translate(-50%, -100%)",Dt.appendChild(Qe)},Ke=()=>{Qe&&Qe.parentNode&&(Qe.parentNode.removeChild(Qe),Qe=null)};j.addEventListener("mouseenter",fe),j.addEventListener("mouseleave",Ke),A.addEventListener("focus",fe),A.addEventListener("blur",Ke),j._cleanupTooltip=()=>{Ke(),j.removeEventListener("mouseenter",fe),j.removeEventListener("mouseleave",Ke),A.removeEventListener("focus",fe),A.removeEventListener("blur",Ke)}}return i!=="top-right"&&r.appendChild(j),{header:r,iconHolder:p,headerTitle:f,headerSubtitle:g,closeButton:A,closeButtonWrapper:j,clearChatButton:w,clearChatButtonWrapper:I}},Qr=(e,n,t)=>{var a,i,u,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(u=r.clearChat)==null?void 0:u.placement)!=null?c:"inline";e.appendChild(n.header),s==="top-right"&&(e.style.position="relative",e.appendChild(n.closeButtonWrapper)),n.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(n.clearChatButtonWrapper))};function Pr(e){let{items:n,onSelect:t,anchor:r,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(Lr)):(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 g of n){if(g.dividerBefore){let v=document.createElement("hr");a.appendChild(v)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",g.id),g.destructive&&x.setAttribute("data-destructive",""),g.icon){let v=ye(g.icon,16,"currentColor",1.5);v&&x.appendChild(v)}let E=document.createElement("span");E.textContent=g.label,x.appendChild(E),x.addEventListener("click",v=>{v.stopPropagation(),p(),t(g.id)}),a.appendChild(x)}let i=null;function u(){if(!o)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){u(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=x=>{!a.contains(x.target)&&!r.contains(x.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function d(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:p,toggle:d,destroy:f}}function Ht(e){let{icon:n,label:t,size:r,strokeWidth:s,className:o,onClick:a,aria:i}=e,u=h("button","persona-icon-btn"+(o?" "+o:""));u.type="button",u.setAttribute("aria-label",t),u.title=t;let c=ye(n,r!=null?r:16,"currentColor",s!=null?s:2);if(c&&u.appendChild(c),a&&u.addEventListener("click",a),i)for(let[p,d]of Object.entries(i))u.setAttribute(p,d);return u}function cs(e){let{icon:n,label:t,variant:r="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:u}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let p=h("button",c);if(p.type="button",p.setAttribute("aria-label",t),n){let f=ye(n,o!=null?o:14,"currentColor",2);f&&p.appendChild(f)}let d=h("span");if(d.textContent=t,p.appendChild(d),i&&p.addEventListener("click",i),u)for(let[f,g]of Object.entries(u))p.setAttribute(f,g);return p}function ds(e){let{items:n,selectedId:t,onSelect:r,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function u(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of n){let d;p.icon?d=Ht({icon:p.icon,label:p.label,onClick:()=>{a=p.id,u(),r(p.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",p.label),d.title=p.label,d.textContent=p.label,d.addEventListener("click",()=>{a=p.id,u(),r(p.id)})),d.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:d}),o.appendChild(d)}function c(p){a=p,u()}return{element:o,setSelected:c}}function ia(e){var g,x;let{label:n,icon:t="chevron-down",menuItems:r,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:u}=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",n);let p=h("span","persona-combo-btn-label");p.textContent=n,c.appendChild(p);let d=ye(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),u&&(c.style.borderRadius=(g=u.borderRadius)!=null?g:"10px",c.style.padding=(x=u.padding)!=null?x:"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 E,v;c.style.backgroundColor=(E=u.background)!=null?E:"",c.style.borderColor=(v=u.border)!=null?v:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=Pr({items:r,onSelect:E=>{c.setAttribute("aria-expanded","false"),s(E)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",E=>{E.stopPropagation();let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()}),c.addEventListener("keydown",E=>{(E.key==="Enter"||E.key===" ")&&(E.preventDefault(),c.click())}),{element:c,setLabel:E=>{p.textContent=E,c.setAttribute("aria-label",E)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let E=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ja=e=>{var r;let n=ur({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),t=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let s=n.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 n};function zu(e,n,t){var r,s,o;if(n!=null&&n.length)for(let a of n){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=(r=a.ariaLabel)!=null?r:a.label)!=null?s:a.id),a.icon){let u=ye(a.icon,14,"currentColor",2);u&&i.appendChild(u)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let u=h("div","persona-relative");u.appendChild(i);let c=Pr({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:u,position:"bottom-left"});u.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(u)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Ka=e=>{var I,j,A,R,T,P,H,J,U;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(I=n==null?void 0:n.launcher)!=null?I:{},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 u=s==null?void 0:s.titleMenu,c,p;if(u)c=ia({label:(j=a.title)!=null?j:"Chat Assistant",menuItems:u.menuItems,onSelect:u.onSelect,hover:u.hover,className:""}).element,c.style.color=Cn.titleColor,p=(A=c.querySelector(".persona-combo-btn-label"))!=null?A: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=Cn.titleColor,p.textContent=(R=a.title)!=null?R:"Chat Assistant",c.appendChild(p),zu(c,s==null?void 0:s.trailingActions,(T=s==null?void 0:s.onAction)!=null?T:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ie=s.onTitleClick;c.addEventListener("click",be=>{be.target.closest("button")||ie()}),c.addEventListener("keydown",be=>{(be.key==="Enter"||be.key===" ")&&(be.preventDefault(),ie())})}let $=s==null?void 0:s.titleRowHover;$&&(c.style.borderRadius=(P=$.borderRadius)!=null?P:"10px",c.style.padding=(H=$.padding)!=null?H:"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 ie,be;c.style.backgroundColor=(ie=$.background)!=null?ie:"",c.style.borderColor=(be=$.border)!=null?be:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(J=a.closeButtonSize)!=null?J:"32px",f=h("div",""),g=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");g.style.height=d,g.style.width=d,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=t?"":"none",g.style.color=a.closeButtonColor||Cn.actionIconColor;let x=(U=a.closeButtonIconName)!=null?U:"x",E=ye(x,"28px","currentColor",1);E?g.appendChild(E):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let v=h("div");v.style.display="none";let w=h("span");return w.style.display="none",{header:i,iconHolder:v,headerTitle:p,headerSubtitle:w,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},la={default:Ja,minimal:Ka},Ga=e=>{var n;return(n=la[e])!=null?n:la.default},bo=(e,n,t)=>{var a,i,u;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),p=h("div");p.style.display="none";let d=h("span"),f=h("span"),g=h("button");g.style.display="none";let x=h("div");return x.style.display="none",{header:c,iconHolder:p,headerTitle:d,headerSubtitle:f,closeButton:g,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=Ga(r)({config:e,showClose:(u=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?u:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(o.iconHolder.style.display="none"),n.showTitle===!1&&(o.headerTitle.style.display="none"),n.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),n.showCloseButton===!1&&(o.closeButton.style.display="none"),n.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var xo=e=>{var xe,ee,se,Et,ht,Ve,Xt,Qe,fe,Ke,Bt,Dt,W,re,Ie,Oe,Je,Ye,L,ve,De,it,Z,ne,_e,lt,Rt,Zt,mt,pt,at;let{config:n}=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 r=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=(ee=(xe=n==null?void 0:n.copy)==null?void 0:xe.inputPlaceholder)!=null?ee:"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 u=3*20;o.style.maxHeight=`${u}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let Ce=Math.min(o.scrollHeight,u);o.style.height=`${Ce}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=(se=n==null?void 0:n.sendButton)!=null?se:{},d=(Et=p.useIcon)!=null?Et:!1,f=(ht=p.iconText)!=null?ht:"\u2191",g=p.iconName,x=(Ve=p.stopIconName)!=null?Ve:"square",E=(Xt=p.tooltipText)!=null?Xt:"Send message",v=(Qe=p.stopTooltipText)!=null?Qe:"Stop generating",w=(Ke=(fe=n==null?void 0:n.copy)==null?void 0:fe.sendButtonLabel)!=null?Ke:"Send",I=(Dt=(Bt=n==null?void 0:n.copy)==null?void 0:Bt.stopButtonLabel)!=null?Dt:"Stop",j=(W=p.showTooltip)!=null?W:!1,A=(re=p.size)!=null?re:"40px",R=p.backgroundColor,T=p.textColor,P=h("div","persona-send-button-wrapper"),H=h("button",d?"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");H.type="submit",H.setAttribute("data-persona-composer-submit","");let J=null,U=null;if(d){H.style.width=A,H.style.height=A,H.style.minWidth=A,H.style.minHeight=A,H.style.fontSize="18px",H.style.lineHeight="1",H.innerHTML="",T?H.style.color=T:H.style.color="var(--persona-button-primary-fg, #ffffff)";let Ce=parseFloat(A)||24,rt=(T==null?void 0:T.trim())||"currentColor";g?(J=ye(g,Ce,rt,2),J?H.appendChild(J):H.textContent=f):H.textContent=f,U=ye(x,Ce,rt,2),R?H.style.backgroundColor=R:H.classList.add("persona-bg-persona-primary")}else H.textContent=w,T?H.style.color=T:H.classList.add("persona-text-white");p.borderWidth&&(H.style.borderWidth=p.borderWidth,H.style.borderStyle="solid"),p.borderColor&&(H.style.borderColor=p.borderColor),p.paddingX?(H.style.paddingLeft=p.paddingX,H.style.paddingRight=p.paddingX):(H.style.paddingLeft="",H.style.paddingRight=""),p.paddingY?(H.style.paddingTop=p.paddingY,H.style.paddingBottom=p.paddingY):(H.style.paddingTop="",H.style.paddingBottom="");let $=null;j&&E&&($=h("div","persona-send-button-tooltip"),$.textContent=E,P.appendChild($)),H.setAttribute("aria-label",E),P.appendChild(H);let ie="send",be=Ce=>{if(Ce===ie)return;ie=Ce;let rt=Ce==="stop"?v:E;if(H.setAttribute("aria-label",rt),$&&($.textContent=rt),d){if(J&&U){let je=Ce==="stop"?U:J,Qt=Ce==="stop"?J:U;Qt.parentNode===H?H.replaceChild(je,Qt):H.appendChild(je)}}else H.textContent=Ce==="stop"?I:w},pe=(Ie=n==null?void 0:n.voiceRecognition)!=null?Ie:{},Ne=pe.enabled===!0,me=null,Re=null,Ee=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),He=((Oe=pe.provider)==null?void 0:Oe.type)==="runtype";if(Ne&&(Ee||He)){Re=h("div","persona-send-button-wrapper"),me=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),me.type="button",me.setAttribute("data-persona-composer-mic",""),me.setAttribute("aria-label","Start voice recognition");let Ce=(Je=pe.iconName)!=null?Je:"mic",rt=(Ye=pe.iconSize)!=null?Ye:A,je=parseFloat(rt)||24,Qt=(L=pe.backgroundColor)!=null?L:R,en=(ve=pe.iconColor)!=null?ve:T;me.style.width=rt,me.style.height=rt,me.style.minWidth=rt,me.style.minHeight=rt,me.style.fontSize="18px",me.style.lineHeight="1",en?me.style.color=en:me.style.color="var(--persona-text, #111827)";let tn=ye(Ce,je,en||"currentColor",1.5);tn?me.appendChild(tn):me.textContent="\u{1F3A4}",Qt&&(me.style.backgroundColor=Qt),pe.borderWidth&&(me.style.borderWidth=pe.borderWidth,me.style.borderStyle="solid"),pe.borderColor&&(me.style.borderColor=pe.borderColor),pe.paddingX&&(me.style.paddingLeft=pe.paddingX,me.style.paddingRight=pe.paddingX),pe.paddingY&&(me.style.paddingTop=pe.paddingY,me.style.paddingBottom=pe.paddingY),Re.appendChild(me);let et=(De=pe.tooltipText)!=null?De:"Start voice recognition";if(((it=pe.showTooltip)!=null?it:!1)&&et){let wn=h("div","persona-send-button-tooltip");wn.textContent=et,Re.appendChild(wn)}}let Q=(Z=n==null?void 0:n.attachments)!=null?Z:{},he=Q.enabled===!0,X=null,ge=null,ue=null,oe=null;if(he){oe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),oe.style.display="none",ue=h("input"),ue.type="file",ue.accept=((ne=Q.allowedTypes)!=null?ne:pr).join(","),ue.multiple=((_e=Q.maxFiles)!=null?_e:4)>1,ue.style.display="none",ue.setAttribute("aria-label","Attach files"),ge=h("div","persona-send-button-wrapper"),X=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),X.type="button",X.setAttribute("aria-label",(lt=Q.buttonTooltipText)!=null?lt:"Attach file");let Ce=(Rt=Q.buttonIconName)!=null?Rt:"paperclip",rt=A,je=parseFloat(rt)||40,Qt=Math.round(je*.6);X.style.width=rt,X.style.height=rt,X.style.minWidth=rt,X.style.minHeight=rt,X.style.fontSize="18px",X.style.lineHeight="1",X.style.backgroundColor="transparent",X.style.color="var(--persona-primary, #111827)",X.style.border="none",X.style.borderRadius="6px",X.style.transition="background-color 0.15s ease",X.addEventListener("mouseenter",()=>{X.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),X.addEventListener("mouseleave",()=>{X.style.backgroundColor="transparent"});let en=ye(Ce,Qt,"currentColor",1.5);en?X.appendChild(en):X.textContent="\u{1F4CE}",X.addEventListener("click",et=>{et.preventDefault(),ue==null||ue.click()}),ge.appendChild(X);let Wn=(Zt=Q.buttonTooltipText)!=null?Zt:"Attach file",tn=h("div","persona-send-button-tooltip");tn.textContent=Wn,ge.appendChild(tn)}s.addEventListener("click",Ce=>{Ce.target!==H&&Ce.target!==P&&Ce.target!==me&&Ce.target!==Re&&Ce.target!==X&&Ce.target!==ge&&o.focus()}),oe&&(oe.style.gap="8px",s.append(oe)),ue&&s.append(ue),s.append(o);let Te=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),Me=h("div","persona-flex persona-items-center persona-gap-2");ge&&Me.append(ge);let k=h("div","persona-flex persona-items-center persona-gap-1");Re&&k.append(Re),k.append(P),Te.append(Me,k),s.append(Te);let V=(mt=n==null?void 0:n.statusIndicator)!=null?mt:{},ae=V.align==="left"?"persona-text-left":V.align==="center"?"persona-text-center":"persona-text-right",D=h("div",`persona-mt-2 ${ae} persona-text-xs persona-text-persona-muted`);D.setAttribute("data-persona-composer-status","");let q=(pt=V.visible)!=null?pt:!0;D.style.display=q?"":"none";let le=(at=V.idleText)!=null?at:"Online";if(V.idleLink){let Ce=h("a");Ce.href=V.idleLink,Ce.target="_blank",Ce.rel="noopener noreferrer",Ce.textContent=le,Ce.style.color="inherit",Ce.style.textDecoration="none",D.appendChild(Ce)}else D.textContent=le;return t.append(r,s,D),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:H,sendButtonWrapper:P,micButton:me,micButtonWrapper:Re,statusText:D,attachmentButton:X,attachmentButtonWrapper:ge,attachmentInput:ue,attachmentPreviewsContainer:oe,actionsRow:Te,leftActions:Me,rightActions:k,setSendButtonMode:be}};var Gd=e=>{var c,p,d,f,g,x,E,v,w;let n=(p=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?p:!0;if(Jt(e)){let I=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),j=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return I.appendChild(j),{wrapper:I,panel:j}}if(!n){let I=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),j=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),A=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return I.style.width=A,j.style.width="100%",I.appendChild(j),{wrapper:I,panel:j}}let r=(g=e==null?void 0:e.launcher)!=null?g:{},s=r.position&&Yn[r.position]?Yn[r.position]:Yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);o.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:vn);let a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(w=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?w:e==null?void 0:e.launcherWidth,u=i!=null?i:Pn;return a.style.width=u,a.style.maxWidth=u,o.appendChild(a),{wrapper:o,panel:a}},Yd=(e,n=!0)=>{var v,w,I,j,A,R,T,P,H;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 r=(v=e==null?void 0:e.layout)==null?void 0:v.header,s=((w=e==null?void 0:e.layout)==null?void 0:w.showHeader)!==!1,o=r?bo(e,r,{showClose:n}):ur({config:e,showClose:n}),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=Jt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",u=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(j=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeTitle)!=null?j:"Hello \u{1F44B}";let p=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");p.textContent=(R=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",u.append(c,p);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(T=e==null?void 0:e.layout)==null?void 0:T.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),u.setAttribute("data-persona-intro-card",""),((P=e==null?void 0:e.copy)==null?void 0:P.showWelcomeCard)!==!1||(u.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(u,d);let x=xo({config:e}),E=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;return s?Qr(t,o,e):(o.header.style.display="none",Qr(t,o,e)),t.append(a),E||(x.footer.style.display="none"),t.append(x.footer),{container:t,body:a,messagesWrapper:d,suggestions:x.suggestions,textarea:x.textarea,sendButton:x.sendButton,sendButtonWrapper:x.sendButtonWrapper,micButton:x.micButton,micButtonWrapper:x.micButtonWrapper,composerForm:x.composerForm,statusText:x.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:x.footer,attachmentButton:x.attachmentButton,attachmentButtonWrapper:x.attachmentButtonWrapper,attachmentInput:x.attachmentInput,attachmentPreviewsContainer:x.attachmentPreviewsContainer,actionsRow:x.actionsRow,leftActions:x.leftActions,rightActions:x.rightActions,setSendButtonMode:x.setSendButtonMode}};var qu=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Vu=(e,n)=>{if(!e)return null;let t=qu(e);if(t===null)return null;let r=n==null?void 0:n[e],s=r!==void 0?r:t;return s||null},Uu=(e,n)=>{let t=h("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return t.setAttribute("data-stop-reason",e),t.setAttribute("role","note"),t.style.opacity="0.75",t.textContent=n,t},Ju=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},Ku=320,Gu=320,Yu=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),Xu=(e,n,t)=>{if(e.length===0)return null;try{let r=h("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),n&&(r.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,r.remove(),t==null||t())};return e.forEach((i,u)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${u+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${Ku}px`,c.style.maxHeight=`${Gu}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}),Ju(i.image)?(c.src=i.image,r.appendChild(c)):(p=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},eo=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-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="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 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="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(n),e.appendChild(t),e.appendChild(r),e.appendChild(s),e},Ya=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:eo};if(n){let s=n(r);if(s!==null)return s}return eo()},Zu=(e,n)=>{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"),r=n==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let s=h("img");s.src=r,s.alt=n==="user"?"User":"Assistant",s.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",t.appendChild(s)}else t.textContent=r,t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else t.textContent=n==="user"?"U":"A",t.classList.add(n==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return t},Xd=(e,n)=>{let t=h("div","persona-text-xs persona-text-persona-muted"),r=new Date(e.createdAt);return n.format?t.textContent=n.format(r):t.textContent=r.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),t},Qu=(e,n="bubble")=>{let t=["persona-message-bubble","persona-max-w-[85%]"];switch(n){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},Xa=(e,n,t)=>{var g,x,E,v,w,I;let r=(g=n.showCopy)!=null?g:!0,s=(x=n.showUpvote)!=null?x:!0,o=(E=n.showDownvote)!=null?E:!0;if(!r&&!s&&!o){let j=h("div");return j.style.display="none",j.id=`actions-${e.id}`,j.setAttribute("data-actions-for",e.id),j}let a=(v=n.visibility)!=null?v:"hover",i=(w=n.align)!=null?w:"right",u=(I=n.layout)!=null?I:"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"}[u],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${p} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(j,A,R)=>{let T=Ht({icon:j,label:A,size:14,className:"persona-message-action-btn"});return T.setAttribute("data-action",R),T};return r&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},vo=(e,n,t,r,s,o)=>{var Ee,He,de,Q,he,X,ge,ue,oe,Te,Me,k,V,ae,D,q,le;let a=t!=null?t:{},i=(Ee=a.layout)!=null?Ee:"bubble",u=a.avatar,c=a.timestamp,p=(He=u==null?void 0:u.show)!=null?He:!1,d=(de=c==null?void 0:c.show)!=null?de:!1,f=(Q=u==null?void 0:u.position)!=null?Q:"left",g=(he=c==null?void 0:c.position)!=null?he:"below",x=Qu(e.role,i),E=h("div",x.join(" "));E.id=`bubble-${e.id}`,E.setAttribute("data-message-id",e.id),E.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(E.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",E.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(E.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",E.style.color="var(--persona-message-assistant-text, var(--persona-text))");let v=Yu(e),w=(ge=(X=e.content)==null?void 0:X.trim())!=null?ge:"",j=v.length>0&&w===Vs,A=$d((oe=(ue=o==null?void 0:o.widgetConfig)==null?void 0:ue.features)==null?void 0:oe.streamAnimation),R=(k=(Me=(Te=o==null?void 0:o.widgetConfig)==null?void 0:Te.features)==null?void 0:Me.streamAnimation)==null?void 0:k.plugins,T=e.role==="assistant"&&A.type!=="none"?sa(A.type,R):null,P=e.role==="assistant"&&((V=T==null?void 0:T.isAnimating)==null?void 0:V.call(T,e))===!0,H=e.role==="assistant"&&T!==null&&(!!e.streaming||P);H&&(T!=null&&T.bubbleClass)&&E.classList.add(T.bubbleClass);let J=document.createElement("div");J.classList.add("persona-message-content"),H&&T&&(T.containerClass&&J.classList.add(T.containerClass),J.style.setProperty("--persona-stream-step",`${A.speed}ms`),J.style.setProperty("--persona-stream-duration",`${A.duration}ms`));let U=H?Vd((ae=e.content)!=null?ae:"",A.buffer,T,e,!!e.streaming):(D=e.content)!=null?D:"",$=n({text:U,message:e,streaming:!!e.streaming,raw:e.rawContent}),ie=$;H&&(T==null?void 0:T.wrap)==="char"?ie=za($,"char",e.id,{skipTags:T.skipTags}):H&&(T==null?void 0:T.wrap)==="word"&&(ie=za($,"word",e.id,{skipTags:T.skipTags}));let be=null;if(j?(be=document.createElement("div"),be.innerHTML=ie,be.style.display="none",J.appendChild(be)):J.innerHTML=ie,H&&(T!=null&&T.useCaret)&&!j&&w){let xe=Ud(),ee=J.querySelectorAll(".persona-stream-char, .persona-stream-word"),se=ee[ee.length-1];if(se!=null&&se.parentNode)se.parentNode.insertBefore(xe,se.nextSibling);else{let Et=J.lastElementChild;Et?Et.appendChild(xe):J.appendChild(xe)}}if(d&&g==="inline"&&e.createdAt){let xe=Xd(e,c);xe.classList.add("persona-ml-2","persona-inline"),J.appendChild(xe)}if(v.length>0){let xe=Xu(v,!j&&!!w,()=>{j&&be&&(be.style.display="")});xe?E.appendChild(xe):j&&be&&(be.style.display="")}if(E.appendChild(J),d&&g==="below"&&e.createdAt){let xe=Xd(e,c);xe.classList.add("persona-mt-1"),E.appendChild(xe)}let pe=e.role==="assistant"?Vu(e.stopReason,(le=(q=o==null?void 0:o.widgetConfig)==null?void 0:q.copy)==null?void 0:le.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let xe=!!(U&&U.trim()),ee=A.placeholder==="skeleton",se=ee&&A.buffer==="line"&&xe;if(xe)se&&E.appendChild(qa());else if(ee)E.appendChild(qa());else{let Et=Ya("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Et&&E.appendChild(Et)}}if(pe&&e.stopReason&&!e.streaming&&(w||(J.style.display="none"),E.appendChild(Uu(e.stopReason,pe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let xe=Xa(e,r,s);E.appendChild(xe)}if(!p||e.role==="system")return E;let me=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Re=Zu(u,e.role);return f==="right"||f==="left"&&e.role==="user"?me.append(E,Re):me.append(Re,E),E.classList.remove("persona-max-w-[85%]"),E.classList.add("persona-max-w-[calc(85%-2.5rem)]"),me},Zd=(e,n,t,r,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}):vo(e,n,t,r,s,o)};var Co=new Set,em=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),tm=(e,n)=>{var r,s;let t=(s=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?s:"";return t?t.split(/\r?\n/).map(o=>o.trim()).filter(Boolean).slice(0,n).join(`
|
|
17
|
+
`):""},Qd=(e,n)=>{let t=Co.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t"),o=n.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let c=ye(t?"chevron-up":"chevron-down",16,"currentColor",2);c?i.appendChild(c):i.textContent=t?"Hide":"Show"}s.style.display=t?"":"none",o&&(o.style.display=t?"none":o.textContent||o.childNodes.length?"":"none")},Za=(e,n)=>{var Ne,me,Re,Ee,He,de,Q,he,X,ge,ue;let t=e.reasoning,r=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(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!t)return r;let s=(me=(Ne=n==null?void 0:n.features)==null?void 0:Ne.reasoningDisplay)!=null?me:{},o=s.expandable!==!1,a=o&&Co.has(e.id),i=t.status!=="complete",u=tm(e,(Re=s.previewMaxLines)!=null?Re:3),c=h("button",o?"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":"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-default persona-border-none");c.type="button",o&&(c.setAttribute("aria-expanded",a?"true":"false"),c.setAttribute("data-expand-header","true")),c.setAttribute("data-bubble-type","reasoning");let p=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary"),f="Thinking...",g=(Ee=n==null?void 0:n.reasoning)!=null?Ee:{},x=String((He=t.startedAt)!=null?He:Date.now()),E=()=>{let oe=h("span","");return oe.setAttribute("data-tool-elapsed",x),oe.textContent=Fs(t),oe},v=(de=g.renderCollapsedSummary)==null?void 0:de.call(g,{message:e,reasoning:t,defaultSummary:f,previewText:u,isActive:i,config:n!=null?n:{},elapsed:Fs(t),createElapsedElement:E});typeof v=="string"&&v.trim()?(d.textContent=v,p.appendChild(d)):v instanceof HTMLElement?p.appendChild(v):(d.textContent=f,p.appendChild(d));let w=h("span","persona-text-xs persona-text-persona-primary");w.textContent=pd(t),p.appendChild(w);let I=(Q=s.loadingAnimation)!=null?Q:"none",j=g.activeTextTemplate,A=g.completeTextTemplate,R=i?j:A,T=v instanceof HTMLElement,P=(oe,Te,Me)=>{let k=Me;for(let V of Te){let ae=h("span","persona-tool-char");ae.style.setProperty("--char-index",String(k)),ae.textContent=V===" "?"\xA0":V,oe.appendChild(ae),k++}return k},H=(oe,Te)=>{d.textContent="";let Me=Os(oe,""),k=0;for(let V of Me){let ae=V.styles.length>0?(()=>{let D=h("span",V.styles.map(q=>`persona-tool-text-${q}`).join(" "));return d.appendChild(D),D})():d;if(V.isDuration&&i)ae.appendChild(E());else{let D=V.isDuration?Fs(t):V.text;Te?k=P(ae,D,k):ae.appendChild(document.createTextNode(D))}}};if(!T&&R)if(w.style.display="none",d.style.display="",i&&I!=="none"){let oe=(he=g.loadingAnimationDuration)!=null?he:2e3;d.setAttribute("data-preserve-animation","true"),I==="pulse"?(d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),H(R,!1)):(d.classList.add(`persona-tool-loading-${I}`),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor)),H(R,!0))}else H(R,!1);else if(!T&&i&&I!=="none"){d.style.display="";let oe=(X=g.loadingAnimationDuration)!=null?X:2e3;if(d.setAttribute("data-preserve-animation","true"),I==="pulse")d.classList.add("persona-tool-loading-pulse"),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`);else{d.classList.add(`persona-tool-loading-${I}`),d.style.setProperty("--persona-tool-anim-duration",`${oe}ms`),I==="shimmer-color"&&(g.loadingAnimationColor&&d.style.setProperty("--persona-tool-anim-color",g.loadingAnimationColor),g.loadingAnimationSecondaryColor&&d.style.setProperty("--persona-tool-anim-secondary-color",g.loadingAnimationSecondaryColor));let Te=d.textContent||f;d.textContent="",P(d,Te,0)}t.status==="complete"&&(d.style.display="none")}else T||(t.status==="complete"?d.style.display="none":d.style.display="");let J=null;if(o){J=h("div","persona-flex persona-items-center");let Te=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Te?J.appendChild(Te):J.textContent=a?"Hide":"Show";let Me=h("div","persona-flex persona-items-center persona-ml-auto");Me.append(J),c.append(p,Me)}else c.append(p);let U=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(U.setAttribute("data-persona-collapsed-preview","reasoning"),U.style.display="none",U.style.whiteSpace="pre-wrap",!a&&i&&s.activePreview&&u){let oe=(ue=(ge=n==null?void 0:n.reasoning)==null?void 0:ge.renderCollapsedPreview)==null?void 0:ue.call(ge,{message:e,reasoning:t,defaultPreview:u,isActive:i,config:n!=null?n:{}});em(U,oe)||(U.textContent=u),U.style.display=""}if(!a&&i&&s.activeMinHeight&&(r.style.minHeight=s.activeMinHeight),!o)return r.append(c,U),r;let $=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");$.style.display=a?"":"none";let ie=t.chunks.join(""),be=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return be.textContent=ie||(t.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),$.appendChild(be),(()=>{if(c.setAttribute("aria-expanded",a?"true":"false"),J){J.innerHTML="";let Te=ye(a?"chevron-up":"chevron-down",16,"currentColor",2);Te?J.appendChild(Te):J.textContent=a?"Hide":"Show"}$.style.display=a?"":"none",U.style.display=a?"none":U.textContent||U.childNodes.length?"":"none"})(),r.append(c,U,$),r};var wo=new Set,nm=(e,n)=>n==null?!1:typeof n=="string"?(e.textContent=n,!0):(e.appendChild(n),!0),rm=(e,n)=>{var o;let t=e.toolCall;if(!t)return"";let r=((o=t.chunks)!=null?o:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-n).join(`
|
|
18
|
+
`);let s=go(t.args).trim();return s?s.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,n).join(`
|
|
19
|
+
`):""},om=(e,n)=>{var p,d,f,g,x;let t=e.toolCall,r=(p=n==null?void 0:n.features)==null?void 0:p.toolCallDisplay,s=(d=r==null?void 0:r.collapsedMode)!=null?d:"tool-call",o=rm(e,(f=r==null?void 0:r.previewMaxLines)!=null?f:3),a=t?ud(t):"";if(!t)return{summary:a,previewText:o,isActive:!1};let i=t.status!=="complete",u=(g=n==null?void 0:n.toolCall)!=null?g:{},c=a;return s==="tool-name"?c=((x=t.name)==null?void 0:x.trim())||a:s==="tool-preview"&&o&&(c=o),i&&u.activeTextTemplate?c=Ra(t,u.activeTextTemplate,c):!i&&u.completeTextTemplate&&(c=Ra(t,u.completeTextTemplate,c)),{summary:c,previewText:o,isActive:i}},ep=(e,n,t)=>{var p;let r=wo.has(e),s=(p=t==null?void 0:t.toolCall)!=null?p:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t"),i=n.querySelector('[data-persona-collapsed-preview="tool"]');if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let u=o.querySelector(".persona-ml-auto"),c=u==null?void 0:u.querySelector(":scope > .persona-flex.persona-items-center");if(c){c.innerHTML="";let d=s.toggleTextColor||s.headerTextColor||"currentColor",f=ye(r?"chevron-up":"chevron-down",16,d,2);f?c.appendChild(f):c.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Qa=(e,n)=>{var ie,be,pe,Ne,me,Re,Ee,He,de;let t=e.toolCall,r=(ie=n==null?void 0:n.toolCall)!=null?ie:{},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),r.backgroundColor&&(s.style.backgroundColor=r.backgroundColor),r.borderColor&&(s.style.borderColor=r.borderColor),r.borderWidth&&(s.style.borderWidth=r.borderWidth),r.borderRadius&&(s.style.borderRadius=r.borderRadius),!t)return s;let o=(pe=(be=n==null?void 0:n.features)==null?void 0:be.toolCallDisplay)!=null?pe:{},a=o.expandable!==!1,i=a&&wo.has(e.id),{summary:u,previewText:c,isActive:p}=om(e,n),d=h("button",a?"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":"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-default persona-border-none");d.type="button",a&&(d.setAttribute("aria-expanded",i?"true":"false"),d.setAttribute("data-expand-header","true")),d.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(d.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(d.style.paddingLeft=r.headerPaddingX,d.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(d.style.paddingTop=r.headerPaddingY,d.style.paddingBottom=r.headerPaddingY);let f=h("div","persona-flex persona-flex-col persona-text-left"),g=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(g.style.color=r.headerTextColor);let x=String((Ne=t.startedAt)!=null?Ne:Date.now()),E=()=>{let Q=h("span","");return Q.setAttribute("data-tool-elapsed",x),Q.textContent=Go(t),Q},v=(Re=r.renderCollapsedSummary)==null?void 0:Re.call(r,{message:e,toolCall:t,defaultSummary:u,previewText:c,collapsedMode:(me=o.collapsedMode)!=null?me:"tool-call",isActive:p,config:n!=null?n:{},elapsed:Go(t),createElapsedElement:E});typeof v=="string"&&v.trim()?(g.textContent=v,f.appendChild(g)):v instanceof HTMLElement?f.appendChild(v):(g.textContent=u,f.appendChild(g));let w=(Ee=o.loadingAnimation)!=null?Ee:"none",I=r.activeTextTemplate,j=r.completeTextTemplate,A=p?I:j,R=v instanceof HTMLElement,T=(Q,he,X)=>{let ge=X;for(let ue of he){let oe=h("span","persona-tool-char");oe.style.setProperty("--char-index",String(ge)),oe.textContent=ue===" "?"\xA0":ue,Q.appendChild(oe),ge++}return ge},P=(Q,he)=>{var oe;g.textContent="";let X=((oe=t.name)==null?void 0:oe.trim())||"tool",ge=Os(Q,X),ue=0;for(let Te of ge){let Me=Te.styles.length>0?(()=>{let k=h("span",Te.styles.map(V=>`persona-tool-text-${V}`).join(" "));return g.appendChild(k),k})():g;if(Te.isDuration&&p)Me.appendChild(E());else{let k=Te.isDuration?Go(t):Te.text;he?ue=T(Me,k,ue):Me.appendChild(document.createTextNode(k))}}};if(!R)if(p&&w!=="none"){let Q=(He=r.loadingAnimationDuration)!=null?He:2e3;if(g.setAttribute("data-preserve-animation","true"),w==="pulse")g.classList.add("persona-tool-loading-pulse"),g.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),A&&P(A,!1);else if(g.classList.add(`persona-tool-loading-${w}`),g.style.setProperty("--persona-tool-anim-duration",`${Q}ms`),w==="shimmer-color"&&(r.loadingAnimationColor&&g.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&g.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),A)P(A,!0);else{let he=g.textContent||u;g.textContent="",T(g,he,0)}}else A&&P(A,!1);let H=null;if(a){H=h("div","persona-flex persona-items-center");let Q=r.toggleTextColor||r.headerTextColor||"currentColor",he=ye(i?"chevron-up":"chevron-down",16,Q,2);he?H.appendChild(he):H.textContent=i?"Hide":"Show";let X=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");X.append(H),d.append(f,X)}else d.append(f);let J=h("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(J.setAttribute("data-persona-collapsed-preview","tool"),J.style.display="none",J.style.whiteSpace="pre-wrap",!i&&p&&o.activePreview&&c){let Q=(de=r.renderCollapsedPreview)==null?void 0:de.call(r,{message:e,toolCall:t,defaultPreview:c,isActive:p,config:n!=null?n:{}});nm(J,Q)||(J.textContent=c),J.style.display=""}if(!i&&p&&o.activeMinHeight&&(s.style.minHeight=o.activeMinHeight),!a)return s.append(d,J),s;let U=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(U.style.display=i?"":"none",r.contentBackgroundColor&&(U.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(U.style.color=r.contentTextColor),r.contentPaddingX&&(U.style.paddingLeft=r.contentPaddingX,U.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(U.style.paddingTop=r.contentPaddingY,U.style.paddingBottom=r.contentPaddingY),t.name){let Q=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?Q.style.color=r.contentTextColor:r.headerTextColor&&(Q.style.color=r.headerTextColor),Q.textContent=t.name,U.appendChild(Q)}if(t.args!==void 0){let Q=h("div","persona-space-y-1"),he=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(he.style.color=r.labelTextColor),he.textContent="Arguments";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=go(t.args),Q.append(he,X),U.appendChild(Q)}if(t.chunks&&t.chunks.length){let Q=h("div","persona-space-y-1"),he=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(he.style.color=r.labelTextColor),he.textContent="Activity";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=t.chunks.join(""),Q.append(he,X),U.appendChild(Q)}if(t.status==="complete"&&t.result!==void 0){let Q=h("div","persona-space-y-1"),he=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(he.style.color=r.labelTextColor),he.textContent="Result";let X=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");X.style.fontSize="0.75rem",X.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(X.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(X.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(X.style.color=r.codeBlockTextColor),X.textContent=go(t.result),Q.append(he,X),U.appendChild(Q)}if(t.status==="complete"&&typeof t.duration=="number"){let Q=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(Q.style.color=r.contentTextColor),Q.textContent=`Duration: ${t.duration}ms`,U.appendChild(Q)}return(()=>{if(d.setAttribute("aria-expanded",i?"true":"false"),H){H.innerHTML="";let Q=r.toggleTextColor||r.headerTextColor||"currentColor",he=ye(i?"chevron-up":"chevron-down",16,Q,2);he?H.appendChild(he):H.textContent=i?"Hide":"Show"}U.style.display=i?"":"none",J.style.display=i?"none":J.textContent||J.childNodes.length?"":"none"})(),s.append(d,J,U),s};var ei=(e,n)=>{var E,v,w,I,j,A,R,T,P,H,J,U;let t=e.approval,r=(n==null?void 0:n.approval)!==!1?n==null?void 0:n.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=(E=r==null?void 0:r.backgroundColor)!=null?E:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(v=r==null?void 0:r.borderColor)!=null?v:"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 u=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)":(w=r==null?void 0:r.titleColor)!=null?w:"currentColor",p=ye(u,20,c,2);p&&i.appendChild(p);let d=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),g=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(g.style.color=r.titleColor),g.textContent=(I=r==null?void 0:r.title)!=null?I:"Approval Required",f.appendChild(g),!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($)}d.appendChild(f);let x=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(x.style.color=r.descriptionColor),x.textContent=t.description,d.appendChild(x),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");r!=null&&r.parameterBackgroundColor&&($.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&($.style.color=r.parameterTextColor),$.style.fontSize="0.75rem",$.style.lineHeight="1rem",$.textContent=go(t.parameters),d.appendChild($)}if(s){let $=h("div","persona-flex persona-gap-2 persona-mt-2");$.setAttribute("data-approval-buttons","true");let ie=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");ie.type="button",ie.style.backgroundColor=(j=r==null?void 0:r.approveButtonColor)!=null?j:"var(--persona-approval-approve-bg, #22c55e)",ie.style.color=(A=r==null?void 0:r.approveButtonTextColor)!=null?A:"#ffffff",ie.setAttribute("data-approval-action","approve");let be=ye("shield-check",14,(R=r==null?void 0:r.approveButtonTextColor)!=null?R:"#ffffff",2);be&&(be.style.marginRight="4px",ie.appendChild(be));let pe=document.createTextNode((T=r==null?void 0:r.approveLabel)!=null?T:"Approve");ie.appendChild(pe);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-cursor-pointer");Ne.type="button",Ne.style.backgroundColor=(P=r==null?void 0:r.denyButtonColor)!=null?P:"transparent",Ne.style.color=(H=r==null?void 0:r.denyButtonTextColor)!=null?H:"var(--persona-feedback-error, #dc2626)",Ne.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Ne.setAttribute("data-approval-action","deny");let me=ye("shield-x",14,(J=r==null?void 0:r.denyButtonTextColor)!=null?J:"var(--persona-feedback-error, #dc2626)",2);me&&(me.style.marginRight="4px",Ne.appendChild(me));let Re=document.createTextNode((U=r==null?void 0:r.denyLabel)!=null?U:"Deny");Ne.appendChild(Re),$.append(ie,Ne),d.appendChild($)}return a.append(i,d),o.appendChild(a),o};var tp=e=>{let n=[];return{buttons:n,render:(r,s,o,a,i)=>{if(e.innerHTML="",n.length=0,!r||!r.length||(a!=null?a:s?s.getMessages():[]).some(g=>g.role==="user"))return;let p=document.createDocumentFragment(),d=s?s.isStreaming():!1,f=g=>{switch(g){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(g=>{let x=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");x.type="button",x.textContent=g,x.disabled=d,i!=null&&i.fontFamily&&(x.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(x.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(x.style.paddingLeft=i.paddingX,x.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(x.style.paddingTop=i.paddingY,x.style.paddingBottom=i.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(g))}),p.appendChild(x),n.push(x)}),e.appendChild(p)}}};var ps=class{constructor(n=2e3,t=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=n,this.buffer=new Array(n),this.store=t}push(n){var t;this.buffer[this.head]=n,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(n.type),(t=this.store)==null||t.put(n)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let n=await this.store.getAll();if(n.length===0)return 0;let t=n.length>this.maxSize?n.slice(n.length-this.maxSize):n;for(let r of t)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=n.length,t.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(n){let t=this.getAll();return n>=t.length?t:t.slice(t.length-n)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var n;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.clear()}destroy(){var n;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(n=this.store)==null||n.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var us=class{constructor(n="persona-event-stream",t="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=n,this.storeName=t}open(){return new Promise((n,t)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let s=r.result;s.objectStoreNames.contains(this.storeName)||s.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}put(n){!this.db||this.isDestroyed||(this.pendingWrites.push(n),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(n){if(!(!this.db||this.isDestroyed||n.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}getAll(){return new Promise((n,t)=>{if(!this.db){n([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{n(a.result)},a.onerror=()=>{t(a.error)}}catch(r){t(r)}})}getCount(){return new Promise((n,t)=>{if(!this.db){n(0);return}try{let o=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();o.onsuccess=()=>{n(o.result)},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}clear(){return new Promise((n,t)=>{if(!this.db){n();return}this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();o.onsuccess=()=>{n()},o.onerror=()=>{t(o.error)}}catch(r){t(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((n,t)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{n()},r.onerror=()=>{t(r.error)}}catch(r){t(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let n=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let s of n)r.put(s)}catch{}}};function So(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var sm={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)"}},am={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},im=["flowName","stepName","reasoningText","text","name","tool","toolName"],lm=100;function cm(e,n){let t={...sm,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return am}function dm(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function pm(e){let n=new Date(e),t=String(n.getHours()).padStart(2,"0"),r=String(n.getMinutes()).padStart(2,"0"),s=String(n.getSeconds()).padStart(2,"0"),o=String(n.getMilliseconds()).padStart(3,"0");return`${t}:${r}:${s}.${o}`}function um(e,n){try{let t=JSON.parse(e);if(typeof t!="object"||t===null)return null;for(let r of n){let s=r.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 mm(e){var n;return(n=navigator.clipboard)!=null&&n.writeText?navigator.clipboard.writeText(e):new Promise(t=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),t()})}function gm(e){let n;try{n=JSON.parse(e.payload)}catch{n=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:n},null,2)}function fm(e,n,t){let r,s;try{s=JSON.parse(e.payload),r=JSON.stringify(s,null,2)}catch{s=e.payload,r=e.payload}let o=n.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]"),u=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return u.textContent=r,i.appendChild(u),i}}function ti(e,n,t,r,s,o,a,i){var f;let u=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");So(c,(f=r.classNames)==null?void 0:f.eventRow);let p=a.find(g=>g.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let g=p.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>d(),isExpanded:u,onToggleExpand:()=>o(e.id)});if(g)return c.appendChild(g),c}return c.appendChild(d()),c;function d(){var ie,be;let g=h("div",""),x=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");x.setAttribute("data-event-id",e.id);let E=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),v=ye(u?"chevron-down":"chevron-right","14px","currentColor",2);v&&E.appendChild(v);let w=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),I=(ie=r.timestampFormat)!=null?ie:"relative";w.textContent=I==="relative"?dm(e.timestamp,t):pm(e.timestamp);let j=null;r.showSequenceNumbers!==!1&&(j=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),j.textContent=String(n+1));let A=cm(e.type,r.badgeColors),R=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");R.style.backgroundColor=A.bg,R.style.color=A.text,R.style.borderColor=A.text+"50",R.textContent=e.type;let T=(be=r.descriptionFields)!=null?be:im,P=um(e.payload,T),H=null;P&&(H=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),H.textContent=P);let J=h("div","persona-flex-1 persona-min-w-0"),U=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"),$=ye("clipboard","12px","currentColor",1.5);return $&&U.appendChild($),U.addEventListener("click",async pe=>{pe.stopPropagation(),await mm(gm(e)),U.innerHTML="";let Ne=ye("check","12px","currentColor",1.5);Ne&&U.appendChild(Ne),setTimeout(()=>{U.innerHTML="";let me=ye("clipboard","12px","currentColor",1.5);me&&U.appendChild(me)},1500)}),x.appendChild(E),x.appendChild(w),j&&x.appendChild(j),x.appendChild(R),H&&x.appendChild(H),x.appendChild(J),x.appendChild(U),g.appendChild(x),u&&g.appendChild(fm(e,a,i)),g}}function np(e){var g,x,E,v,w;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(g=s==null?void 0:s.features)==null?void 0:g.scrollToBottom,i=(a==null?void 0:a.enabled)!==!1,u=(x=a==null?void 0:a.iconName)!=null?x:"arrow-down",c=(E=a==null?void 0:a.label)!=null?E:"",p=(w=(v=s==null?void 0:s.features)==null?void 0:v.eventStream)!=null?w:{},d=o.find(I=>I.renderEventStreamView);if(d!=null&&d.renderEventStreamView&&s){let I=d.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>f().element,onClose:r});if(I)return{element:I,update:()=>{},destroy:()=>{}}}return f();function f(){let I=p.classNames,j=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");So(j,I==null?void 0:I.panel);let A=[],R="",T="",P=null,H=[],J={},U=0,$=na(),ie=0,be=0,pe=!1,Ne=null,me=!1,Re=0,Ee=new Set,He=new Map,de="",Q="",he=null,X,ge,ue,oe,Te;function Me(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),ne=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");So(ne,I==null?void 0:I.headerBar);let _e=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_e.textContent="Events",X=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"),X.textContent="0";let lt=h("div","persona-flex-1");ge=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 Rt=h("option","");Rt.value="",Rt.textContent="All events",ge.appendChild(Rt),ue=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"),ue.type="button",ue.title="Copy All";let mt=ye("clipboard-copy","12px","currentColor",1.5);mt&&ue.appendChild(mt);let pt=h("span","persona-text-xs");pt.textContent="Copy All",ue.appendChild(pt),ne.appendChild(_e),ne.appendChild(X),ne.appendChild(lt),ne.appendChild(ge),ne.appendChild(ue);let at=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");So(at,I==null?void 0:I.searchBar);let Ce=ye("search","14px","var(--persona-muted, #9ca3af)",1.5),rt=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");Ce&&rt.appendChild(Ce),oe=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"),So(oe,I==null?void 0:I.searchInput),oe.type="text",oe.placeholder="Search event payloads...",Te=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"),Te.type="button",Te.style.display="none";let je=ye("x","12px","currentColor",2);return je&&Te.appendChild(je),at.appendChild(rt),at.appendChild(oe),at.appendChild(Te),Z.appendChild(ne),Z.appendChild(at),Z}let k,V=o.find(Z=>Z.renderEventStreamToolbar);if(V!=null&&V.renderEventStreamToolbar&&s){let Z=V.renderEventStreamToolbar({config:s,defaultRenderer:()=>Me(),eventCount:n.getSize(),filteredCount:0,onFilterChange:ne=>{R=ne,Xt(),Ke()},onSearchChange:ne=>{T=ne,Xt(),Ke()}});k=Z!=null?Z:Me()}else k=Me();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 D=h("div","persona-flex-1 persona-min-h-0 persona-relative"),q=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");q.style.height="100%";let le=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");So(le,I==null?void 0:I.scrollIndicator),le.style.display="none",le.setAttribute("data-persona-scroll-to-bottom-has-label",c?"true":"false");let xe=ye(u,"14px","currentColor",2);xe&&le.appendChild(xe);let ee=h("span","");ee.textContent=c,le.appendChild(ee);let se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");se.style.display="none",D.appendChild(q),D.appendChild(se),D.appendChild(le),j.setAttribute("tabindex","0"),j.appendChild(k),j.appendChild(ae),j.appendChild(D);function Et(){let Z=n.getAll(),ne={};for(let pt of Z)ne[pt.type]=(ne[pt.type]||0)+1;let _e=Object.keys(ne).sort(),lt=_e.length!==H.length||!_e.every((pt,at)=>pt===H[at]),Rt=!lt&&_e.some(pt=>ne[pt]!==J[pt]),Zt=Z.length!==Object.values(J).reduce((pt,at)=>pt+at,0);if(!lt&&!Rt&&!Zt||(H=_e,J=ne,!ge))return;let mt=ge.value;if(ge.options[0].textContent="All events",lt){for(;ge.options.length>1;)ge.remove(1);for(let pt of _e){let at=h("option","");at.value=pt,at.textContent=`${pt} (${ne[pt]||0})`,ge.appendChild(at)}mt&&_e.includes(mt)?ge.value=mt:mt&&(ge.value="",R="")}else for(let pt=1;pt<ge.options.length;pt++){let at=ge.options[pt];at.textContent=`${at.value} (${ne[at.value]||0})`}}function ht(){let Z=n.getAll();if(R&&(Z=Z.filter(ne=>ne.type===R)),T){let ne=T.toLowerCase();Z=Z.filter(_e=>_e.type.toLowerCase().includes(ne)||_e.payload.toLowerCase().includes(ne))}return Z}function Ve(){return R!==""||T!==""}function Xt(){U=0,ie=0,$.resume(),le.style.display="none"}function Qe(Z){Ee.has(Z)?Ee.delete(Z):Ee.add(Z),he=Z;let ne=q.scrollTop,_e=$.isFollowing();me=!0,$.pause(),Ke(),q.scrollTop=ne,_e&&$.resume(),me=!1}function fe(){return os(q,50)}function Ke(){be=Date.now(),pe=!1,Et();let Z=n.getEvictedCount();Z>0?(ae.textContent=`${Z.toLocaleString()} older events truncated`,ae.style.display=""):ae.style.display="none",A=ht();let ne=A.length,_e=n.getSize()>0;X&&(X.textContent=String(n.getSize())),ne===0&&_e&&Ve()?(se.textContent=T?`No events matching '${T}'`:"No events matching filter",se.style.display="",q.style.display="none"):(se.style.display="none",q.style.display=""),ue&&(ue.title=Ve()?`Copy Filtered (${ne})`:"Copy All"),i&&!$.isFollowing()&&ne>U&&(ie+=ne-U,ee.textContent=c?`${c}${ie>0?` (${ie})`:""}`:"",le.style.display=""),U=ne;let lt=n.getAll(),Rt=lt.length>0?lt[0].timestamp:0,Zt=new Set(A.map(at=>at.id));for(let at of Ee)Zt.has(at)||Ee.delete(at);let mt=R!==de||T!==Q,pt=He.size===0&&A.length>0;if(mt||pt||A.length===0){q.innerHTML="",He.clear();let at=document.createDocumentFragment();for(let Ce=0;Ce<A.length;Ce++){let rt=ti(A[Ce],Ce,Rt,p,Ee,Qe,o,s);He.set(A[Ce].id,rt),at.appendChild(rt)}q.appendChild(at),de=R,Q=T,he=null}else{if(he!==null){let Ce=He.get(he);if(Ce&&Ce.parentNode===q){let rt=A.findIndex(je=>je.id===he);if(rt>=0){let je=ti(A[rt],rt,Rt,p,Ee,Qe,o,s);q.insertBefore(je,Ce),Ce.remove(),He.set(he,je)}}he=null}let at=new Set(A.map(Ce=>Ce.id));for(let[Ce,rt]of He)at.has(Ce)||(rt.remove(),He.delete(Ce));for(let Ce=0;Ce<A.length;Ce++){let rt=A[Ce];if(!He.has(rt.id)){let je=ti(rt,Ce,Rt,p,Ee,Qe,o,s);He.set(rt.id,je),q.appendChild(je)}}}$.isFollowing()&&(q.scrollTop=q.scrollHeight)}function Bt(){if(Date.now()-be>=lm){Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),Ke();return}pe||(pe=!0,Ne=requestAnimationFrame(()=>{Ne=null,Ke()}))}let Dt=(Z,ne)=>{if(!ue)return;ue.innerHTML="";let _e=ye(Z,"12px","currentColor",1.5);_e&&ue.appendChild(_e);let lt=h("span","persona-text-xs");lt.textContent="Copy All",ue.appendChild(lt),setTimeout(()=>{ue.innerHTML="";let Rt=ye("clipboard-copy","12px","currentColor",1.5);Rt&&ue.appendChild(Rt);let Zt=h("span","persona-text-xs");Zt.textContent="Copy All",ue.appendChild(Zt),ue.disabled=!1},ne)},W=async()=>{if(ue){ue.disabled=!0;try{let Z;Ve()?Z=A:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let ne=Z.map(_e=>{try{return JSON.parse(_e.payload)}catch{return _e.payload}});await navigator.clipboard.writeText(JSON.stringify(ne,null,2)),Dt("check",1500)}catch{Dt("x",1500)}}},re=()=>{ge&&(R=ge.value,Xt(),Ke())},Ie=()=>{!oe||!Te||(Te.style.display=oe.value?"":"none",P&&clearTimeout(P),P=setTimeout(()=>{T=oe.value,Xt(),Ke()},150))},Oe=()=>{!oe||!Te||(oe.value="",T="",Te.style.display="none",P&&clearTimeout(P),Xt(),Ke())},Je=()=>{if(me)return;let Z=q.scrollTop,{action:ne,nextLastScrollTop:_e}=ra({following:$.isFollowing(),currentScrollTop:Z,lastScrollTop:Re,nearBottom:fe(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Re=_e,ne==="resume"?($.resume(),ie=0,le.style.display="none"):ne==="pause"&&($.pause(),i&&(ee.textContent=c,le.style.display=""))},Ye=Z=>{let ne=oa({following:$.isFollowing(),deltaY:Z.deltaY,nearBottom:fe(),resumeWhenNearBottom:!0});ne==="pause"?($.pause(),i&&(ee.textContent=c,le.style.display="")):ne==="resume"&&($.resume(),ie=0,le.style.display="none")},L=()=>{i&&(q.scrollTop=q.scrollHeight,$.resume(),ie=0,le.style.display="none")},ve=Z=>{let ne=Z.target;if(!ne||ne.closest("button"))return;let _e=ne.closest("[data-event-id]");if(!_e)return;let lt=_e.getAttribute("data-event-id");lt&&Qe(lt)},De=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),oe==null||oe.focus(),oe==null||oe.select();return}Z.key==="Escape"&&(oe&&document.activeElement===oe?(Oe(),oe.blur(),j.focus()):r&&r())};ue&&ue.addEventListener("click",W),ge&&ge.addEventListener("change",re),oe&&oe.addEventListener("input",Ie),Te&&Te.addEventListener("click",Oe),q.addEventListener("scroll",Je),q.addEventListener("wheel",Ye,{passive:!0}),q.addEventListener("click",ve),le.addEventListener("click",L),j.addEventListener("keydown",De);function it(){P&&clearTimeout(P),Ne!==null&&(cancelAnimationFrame(Ne),Ne=null),pe=!1,He.clear(),ue&&ue.removeEventListener("click",W),ge&&ge.removeEventListener("change",re),oe&&oe.removeEventListener("input",Ie),Te&&Te.removeEventListener("click",Oe),q.removeEventListener("scroll",Je),q.removeEventListener("wheel",Ye),q.removeEventListener("click",ve),le.removeEventListener("click",L),j.removeEventListener("keydown",De)}return{element:j,update:Bt,destroy:it}}}function rp(e,n){let t=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=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`),r&&i.setAttribute("data-open-artifact",r);let u=document.createElement("div");u.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-muted, #9ca3af)",u.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.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",d.appendChild(f);let g=document.createElement("span");g.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(g)}else d.textContent=a;if(c.append(p,d),i.append(u,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",r),i.append(f)}return i}var op=(e,n)=>{var r,s,o;let t=(o=(s=(r=n==null?void 0:n.config)==null?void 0:r.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:"",u=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",p=t({artifact:{artifactId:i,title:a,artifactType:c,status:u},config:n.config,defaultRenderer:()=>rp(e,n)});if(p)return p}return rp(e,n)};var ni=class{constructor(){this.components=new Map}register(n,t){this.components.has(n)&&console.warn(`[ComponentRegistry] Component "${n}" is already registered. Overwriting.`),this.components.set(n,t)}unregister(n){this.components.delete(n)}get(n){return this.components.get(n)}has(n){return this.components.has(n)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(n){Object.entries(n).forEach(([t,r])=>{this.register(t,r)})}},mr=new ni;mr.register("PersonaArtifactCard",op);function hm(e){var s;let n=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 r=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((s=e.props)!=null?s:{},null,2),n.appendChild(t),n.appendChild(r),n}function sp(e,n){var ue,oe,Te,Me;let t=(oe=(ue=e.features)==null?void 0:ue.artifacts)==null?void 0:oe.layout,s=((Te=t==null?void 0:t.toolbarPreset)!=null?Te:"default")==="document",o=(Me=t==null?void 0:t.panePadding)==null?void 0:Me.trim(),a=e.markdown?Ur(e.markdown):null,i=mo(e.sanitize),u=k=>{let V=a?a(k):uo(k);return i?i(V):V},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"),d.classList.remove("persona-artifact-drawer-open"),$==null||$.hide()};c&&c.addEventListener("click",()=>{var k;p(),(k=n.onDismiss)==null||k.call(n)});let d=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");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.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 g=h("span","persona-text-xs persona-font-medium persona-truncate");g.textContent="Artifacts";let x=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var k;p(),(k=n.onDismiss)==null||k.call(n)});let E="rendered",v=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),w=s?Ht({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Ht({icon:"eye",label:"Rendered view"}),I=s?Ht({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Ht({icon:"code-2",label:"Source"}),j=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),A=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,R=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,T=t==null?void 0:t.documentToolbarCopyMenuItems,P=!!(R&&T&&T.length>0),H=null,J,U=null,$=null;if(s&&(A||R)&&!P){if(J=A?cs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),R){let k=ye("chevron-down",14,"currentColor",2);k&&J.appendChild(k)}}else s&&P?(H=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),J=A?cs({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),U=Ht({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"}}),H.append(J,U)):s?J=Ht({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):J=Ht({icon:"copy",label:"Copy"});let ie=s?Ht({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Ht({icon:"refresh-cw",label:"Refresh"}),be=s?Ht({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Ht({icon:"x",label:"Close"}),pe=()=>{var q,le,xe;let k=(q=de.find(ee=>ee.id===Q))!=null?q:de[de.length-1],V=(le=k==null?void 0:k.id)!=null?le:null,ae=(k==null?void 0:k.artifactType)==="markdown"&&(xe=k.markdown)!=null?xe:"",D=k?JSON.stringify({component:k.component,props:k.props},null,2):"";return{markdown:ae,jsonPayload:D,id:V}},Ne=async()=>{var q;let{markdown:k,jsonPayload:V}=pe(),ae=(q=de.find(le=>le.id===Q))!=null?q:de[de.length-1],D=(ae==null?void 0:ae.artifactType)==="markdown"?k:ae?V:"";try{await navigator.clipboard.writeText(D)}catch{}};if(J.addEventListener("click",async()=>{let k=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(k&&P){let{markdown:V,jsonPayload:ae,id:D}=pe();try{await k({actionId:"primary",artifactId:D,markdown:V,jsonPayload:ae})}catch{}return}await Ne()}),U&&(T!=null&&T.length)){let k=()=>{var ae;return(ae=d.closest("[data-persona-root]"))!=null?ae:document.body},V=()=>{$=Pr({items:T.map(ae=>({id:ae.id,label:ae.label})),onSelect:async ae=>{let{markdown:D,jsonPayload:q,id:le}=pe(),xe=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{xe?await xe({actionId:ae,artifactId:le,markdown:D,jsonPayload:q}):ae==="markdown"||ae==="md"?await navigator.clipboard.writeText(D):ae==="json"||ae==="source"?await navigator.clipboard.writeText(q):await navigator.clipboard.writeText(D||q)}catch{}},anchor:H!=null?H:U,position:"bottom-right",portal:k()})};d.isConnected?V():requestAnimationFrame(V),U.addEventListener("click",ae=>{ae.stopPropagation(),$==null||$.toggle()})}ie.addEventListener("click",async()=>{var k;try{await((k=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:k.call(t))}catch{}X()}),be.addEventListener("click",()=>{var k;p(),(k=n.onDismiss)==null||k.call(n)});let me=()=>{s&&(w.setAttribute("aria-pressed",E==="rendered"?"true":"false"),I.setAttribute("aria-pressed",E==="source"?"true":"false"))};w.addEventListener("click",()=>{E="rendered",me(),X()}),I.addEventListener("click",()=>{E="source",me(),X()});let Re=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(),v.append(w,I),H?j.append(H,ie,be):j.append(J,ie,be),f.append(v,Re,j),me()):(f.appendChild(g),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let Ee=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"),He=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(Ee.style.paddingLeft=o,Ee.style.paddingRight=o,He.style.padding=o),d.appendChild(f),d.appendChild(Ee),d.appendChild(He);let de=[],Q=null,he=!1,X=()=>{var D,q,le,xe;let k=s&&de.length<=1;Ee.classList.toggle("persona-hidden",k),Ee.replaceChildren();for(let ee of de){let se=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");se.type="button",se.textContent=ee.title||ee.id.slice(0,8),ee.id===Q&&se.classList.add("persona-bg-persona-container","persona-border-persona-border"),se.addEventListener("click",()=>n.onSelect(ee.id)),Ee.appendChild(se)}He.replaceChildren();let V=Q&&de.find(ee=>ee.id===Q)||de[de.length-1];if(!V)return;if(s){let ee=V.artifactType==="markdown"?"MD":(D=V.component)!=null?D:"Component",Et=(V.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Re.textContent=`${Et} \xB7 ${ee}`}else g.textContent="Artifacts";if(V.artifactType==="markdown"){if(s&&E==="source"){let se=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");se.textContent=(q=V.markdown)!=null?q:"",He.appendChild(se);return}let ee=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");ee.innerHTML=u((le=V.markdown)!=null?le:""),He.appendChild(ee);return}let ae=V.component?mr.get(V.component):void 0;if(ae){let se={message:{id:V.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Et=ae((xe=V.props)!=null?xe:{},se);if(Et){He.appendChild(Et);return}}catch{}}He.appendChild(hm(V))},ge=()=>{var V;let k=de.length>0;if(d.classList.toggle("persona-hidden",!k),c){let ae=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,q=((V=ae==null?void 0:ae.classList.contains("persona-artifact-narrow-host"))!=null?V:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;k&&q&&he?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(k){var V,ae,D;de=k.artifacts,Q=(D=(ae=k.selectedId)!=null?ae:(V=k.artifacts[k.artifacts.length-1])==null?void 0:V.id)!=null?D:null,de.length>0&&(he=!0),X(),ge()},setMobileOpen(k){he=k,!k&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):ge()}}}function _n(e){var n,t;return((t=(n=e==null?void 0:e.features)==null?void 0:n.artifacts)==null?void 0:t.enabled)===!0}function ap(e,n){var o,a,i,u;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"),!_n(n))return;let t=(a=(o=n.features)==null?void 0:o.artifacts)==null?void 0:a.layout,r=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(u=t==null?void 0:t.paneBorderLeft)==null?void 0:u.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function ym(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 ca(e,n){var u,c,p,d,f,g,x,E,v,w;if(!_n(n)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),ym(e),ap(e,n);return}let t=(c=(u=n.features)==null?void 0:u.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",(d=t==null?void 0:t.paneWidth)!=null?d:"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 r=(g=t==null?void 0:t.paneBackground)==null?void 0:g.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(x=t==null?void 0:t.panePadding)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(E=t==null?void 0:t.documentToolbarIconColor)==null?void 0:E.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(v=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:v.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(w=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:w.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ap(e,n)}var ip=["panel","seamless"];function da(e,n){var i,u,c,p,d,f;for(let g of ip)e.classList.remove(`persona-artifact-appearance-${g}`);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"),!_n(n))return;let t=(u=(i=n.features)==null?void 0:i.artifacts)==null?void 0:u.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=ip.includes(r)?r:"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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.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 g=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;g&&e.style.setProperty("--persona-artifact-unified-outer-radius",g)}}function lp(e,n){var t,r,s;return!n||!_n(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function bm(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function xm(e){if(!(e!=null&&e.trim()))return null;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):null}function vm(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function Cm(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function cp(e,n){var a;let r=(a=(n.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",s=/^([\d.]+)px$/i.exec(r);if(s)return Number(s[1]);let o=/^([\d.]+)/.exec(r);return o?Number(o[1]):8}function dp(e,n,t,r,s,o){let a=bm(s,200),i=Cm(n,t,r,200);i=Math.max(a,i);let u=xm(o);return u!==null&&(i=Math.min(i,u)),vm(e,a,i)}var pp={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"}},ri=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,E,v;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(E=pp[a])!=null?E:pp.init;o.classList.add("persona-form-card","persona-space-y-4");let u=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,u.appendChild(c),i.description){let w=h("p","persona-text-sm persona-text-persona-muted");w.textContent=i.description,u.appendChild(w)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(w=>{var T,P;let I=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");I.htmlFor=`${n.id}-${a}-${w.name}`;let j=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");j.textContent=w.label,I.appendChild(j);let A=(T=w.type)!=null?T:"text",R;A==="textarea"?(R=document.createElement("textarea"),R.rows=3):(R=document.createElement("input"),R.type=A),R.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",R.id=`${n.id}-${a}-${w.name}`,R.name=w.name,R.placeholder=(P=w.placeholder)!=null?P:"",w.required&&(R.required=!0),I.appendChild(R),p.appendChild(I)});let d=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]"),g=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");g.type="submit",g.textContent=(v=i.submitLabel)!=null?v:"Submit",d.appendChild(f),d.appendChild(g),p.appendChild(d),o.replaceChildren(u,p),p.addEventListener("submit",async w=>{var R,T;w.preventDefault();let I=(R=t.formEndpoint)!=null?R:"/form",j=new FormData(p),A={};j.forEach((P,H)=>{A[H]=P}),A.type=a,g.disabled=!0,f.textContent="Submitting\u2026";try{let P=await fetch(I,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(A)});if(!P.ok)throw new Error(`Form submission failed (${P.status})`);let H=await P.json();f.textContent=(T=H.message)!=null?T:"Thanks! We'll be in touch soon.",H.success&&H.nextPrompt&&await r.sendMessage(String(H.nextPrompt))}catch(P){f.textContent=P instanceof Error?P.message:"Something went wrong. Please try again."}finally{g.disabled=!1}})})};var oi=class{constructor(){this.plugins=new Map}register(n){var t;this.plugins.has(n.id)&&console.warn(`Plugin "${n.id}" is already registered. Overwriting.`),this.plugins.set(n.id,n),(t=n.onRegister)==null||t.call(n)}unregister(n){var r;let t=this.plugins.get(n);t&&((r=t.onUnregister)==null||r.call(t),this.plugins.delete(n))}getAll(){return Array.from(this.plugins.values()).sort((n,t)=>{var r,s;return((r=t.priority)!=null?r:0)-((s=n.priority)!=null?s:0)})}getForInstance(n){let t=this.getAll();if(!n||n.length===0)return t;let r=new Set(n.map(o=>o.id));return[...t.filter(o=>!r.has(o.id)),...n].sort((o,a)=>{var i,u;return((i=a.priority)!=null?i:0)-((u=o.priority)!=null?u:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},ms=new oi;var up=()=>{let e=new Map,n=(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:n,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",u)}})}}};var wm=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Sm=e=>{let n=e.trim(),t=n.indexOf("{");if(t===-1)return null;let r=0;for(let s=t;s<n.length;s+=1){let o=n[s];if(o==="{"&&(r+=1),o==="}"&&(r-=1,r===0))return n.slice(t,s+1)}return null},gs=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=wm(e),t=Sm(n);if(!t)return null;let r=JSON.parse(t);if(!r||typeof r!="object"||!r.action)return null;let{action:s,...o}=r;return{type:String(s),payload:o,raw:r}}catch{return null}},si=e=>typeof e=="string"?e:e==null?"":String(e),to={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:si(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=si(t.element);if(r&&((s=n.document)!=null&&s.querySelector)){let o=n.document.querySelector(r);o?setTimeout(()=>{o.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:si(t.text)}}},mp=e=>Array.isArray(e)?e.map(n=>String(n)):[],fs=e=>{let n=new Set(mp(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(mp(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let o=Array.from(n);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:o}))};return{process:o=>{if(o.streaming||o.message.role!=="assistant"||!o.text||n.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;n.add(o.message.id),r();let u={action:i,message:o.message};e.emit("action:detected",u);for(let c of e.handlers)if(c)try{let p=()=>{e.emit("action:resubmit",u)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:t}};var Am=e=>{if(!e)return null;try{return JSON.parse(e)}catch(n){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",n),null}},Em=e=>e.map(n=>({...n,streaming:!1})),pa=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?Am(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?Em(t.messages):void 0};r.setItem(e,JSON.stringify(s))}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",s)}},clear:()=>{let t=n();if(t)try{t.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};var Ao=require("partial-json");function Tm(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function Mm(e,n){if(!Tm(e))return null;let t=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:t,raw:n}}function ua(){let e=null,n=0;return{getExtractedDirective:()=>e,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=n)return e;try{let s=(0,Ao.parse)(t,Ao.STR|Ao.OBJ),o=Mm(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function gp(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ma(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=mr.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:r,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 fp(){let e=ua();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function ga(e){if(!e.rawContent)return!1;try{let n=JSON.parse(e.rawContent);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function fa(e){if(!e.rawContent)return null;try{let n=JSON.parse(e.rawContent);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string")return{component:n.component,props:n.props&&typeof n.props=="object"&&n.props!==null?n.props:{},raw:e.rawContent}}catch{}return null}var km=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function ha(e){let{onSubmit:n,onDismiss:t,title:r="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,ratingLabels:c=km}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let g=document.createElement("div");g.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=r,g.appendChild(x);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,g.appendChild(E),f.appendChild(g);let v=document.createElement("div");v.className="persona-feedback-rating persona-feedback-rating-csat",v.setAttribute("role","radiogroup"),v.setAttribute("aria-label","Satisfaction rating from 1 to 5");let w=[];for(let T=1;T<=5;T++){let P=document.createElement("button");P.type="button",P.className="persona-feedback-rating-btn persona-feedback-star-btn",P.setAttribute("role","radio"),P.setAttribute("aria-checked","false"),P.setAttribute("aria-label",`${T} star${T>1?"s":""}: ${c[T-1]}`),P.title=c[T-1],P.dataset.rating=String(T),P.innerHTML=`
|
|
19
20
|
<svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
|
20
21
|
<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>
|
|
21
22
|
</svg>
|
|
22
|
-
`,E.addEventListener("click",()=>{d=W,S.forEach((K,Q)=>{let X=Q<W;K.classList.toggle("selected",X),K.setAttribute("aria-checked",Q===W-1?"true":"false")})}),S.push(E),C.appendChild(E)}f.appendChild(C);let M=null;if(u){let W=document.createElement("div");W.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),W.appendChild(M),f.appendChild(W)}let H=document.createElement("div");H.className="persona-feedback-actions";let w=document.createElement("button");w.type="button",w.className="persona-feedback-btn persona-feedback-btn-skip",w.textContent=i,w.addEventListener("click",()=>{t==null||t(),p.remove()});let L=document.createElement("button");return L.type="button",L.className="persona-feedback-btn persona-feedback-btn-submit",L.textContent=a,L.addEventListener("click",async()=>{if(d===null){C.classList.add("persona-feedback-shake"),setTimeout(()=>C.classList.remove("persona-feedback-shake"),500);return}L.disabled=!0,L.textContent="Submitting...";try{let W=(M==null?void 0:M.value.trim())||void 0;await r(d,W),p.remove()}catch(W){L.disabled=!1,L.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),H.appendChild(w),H.appendChild(L),f.appendChild(H),p.appendChild(f),p}function Qs(e){let{onSubmit:r,onDismiss:t,title:n="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let T=document.createElement("h3");T.className="persona-feedback-title",T.textContent=n,x.appendChild(T);let C=document.createElement("p");C.className="persona-feedback-subtitle",C.textContent=s,x.appendChild(C),g.appendChild(x);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-nps",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Likelihood rating from 0 to 10");let M=document.createElement("div");M.className="persona-feedback-labels";let H=document.createElement("span");H.className="persona-feedback-label-low",H.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=p,M.appendChild(H),M.appendChild(w);let L=document.createElement("div");L.className="persona-feedback-numbers";let W=[];for(let O=0;O<=10;O++){let oe=document.createElement("button");oe.type="button",oe.className="persona-feedback-rating-btn persona-feedback-number-btn",oe.setAttribute("role","radio"),oe.setAttribute("aria-checked","false"),oe.setAttribute("aria-label",`Rating ${O} out of 10`),oe.textContent=String(O),oe.dataset.rating=String(O),O<=6?oe.classList.add("persona-feedback-detractor"):O<=8?oe.classList.add("persona-feedback-passive"):oe.classList.add("persona-feedback-promoter"),oe.addEventListener("click",()=>{f=O,W.forEach((Ee,ae)=>{Ee.classList.toggle("selected",ae===O),Ee.setAttribute("aria-checked",ae===O?"true":"false")})}),W.push(oe),L.appendChild(oe)}S.appendChild(M),S.appendChild(L),g.appendChild(S);let E=null;if(u){let O=document.createElement("div");O.className="persona-feedback-comment-container",E=document.createElement("textarea"),E.className="persona-feedback-comment",E.placeholder=o,E.rows=3,E.setAttribute("aria-label","Additional comments"),O.appendChild(E),g.appendChild(O)}let K=document.createElement("div");K.className="persona-feedback-actions";let Q=document.createElement("button");Q.type="button",Q.className="persona-feedback-btn persona-feedback-btn-skip",Q.textContent=i,Q.addEventListener("click",()=>{t==null||t(),d.remove()});let X=document.createElement("button");return X.type="button",X.className="persona-feedback-btn persona-feedback-btn-submit",X.textContent=a,X.addEventListener("click",async()=>{if(f===null){L.classList.add("persona-feedback-shake"),setTimeout(()=>L.classList.remove("persona-feedback-shake"),500);return}X.disabled=!0,X.textContent="Submitting...";try{let O=(E==null?void 0:E.value.trim())||void 0;await r(f,O),d.remove()}catch(O){X.disabled=!1,X.textContent=a,console.error("[NPS Feedback] Failed to submit:",O)}}),K.appendChild(Q),K.appendChild(X),g.appendChild(K),d.appendChild(g),d}var ho="persona-chat-history",Ku=30*1e3,Xu={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Zu(e){var n,s,o;if(!e)return[];let r=[],t=Array.from((n=e.items)!=null?n:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){r.push(i);continue}let u=(s=Xu[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(r.length>0)return r;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&r.push(a);return r}function ea(e){if(!e)return!1;let r=e.types;return r?typeof r.contains=="function"?r.contains("Files"):Array.from(r).includes("Files"):!1}function Qu(e){var r,t,n,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(r=e.storage)!=null?r:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(n=e.persist)==null?void 0:n.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function em(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Na=e=>!e||typeof e!="object"?{}:{...e},Gd=e=>e.map(r=>({...r,streaming:!1})),Yd=(e,r,t)=>{let n=e!=null&&e.markdown?Nr(e.markdown):null,s=ro(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(r){let f=r.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?u=n(a):u=no(a),s?s(u):u}};function Kd(e){var i,u,c,p;let r=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&r.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&r.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&r.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&r.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&r.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&r.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&r.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",n=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(t,n,s,o);if(a&&r.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,r.appendChild(d)}return r}var ta=(e,r,t)=>{var ri,oi,si,ai,ii,li,ci,di,pi,ui,mi,gi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let n=Bs(r),s=Ko.getForInstance(n.plugins);n.components&&ir.registerAll(n.components);let o=qd(),a=(ri=n.storageAdapter)!=null?ri:Js(),i={},u=null,c=!1,p=l=>{if(n.onStateLoaded)try{let m=n.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:A}=m;return A&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=Na(y.metadata)),(oi=y.messages)!=null&&oi.length&&(n={...n,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(n.onStateLoaded)try{let l=p({messages:[],metadata:{}});(si=l.messages)!=null&&si.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},xo()},g=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Xo],x=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Vr.message,Vr.messageAndClick],T=Zo({parsers:g,handlers:x,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});T.syncFromMetadata();let C=(ii=(ai=n.launcher)==null?void 0:ai.enabled)!=null?ii:!0,S=(ci=(li=n.launcher)==null?void 0:li.autoExpand)!=null?ci:!1,M=(di=n.autoFocusInput)!=null?di:!1,H=S,w=C,L=(ui=(pi=n.layout)==null?void 0:pi.header)==null?void 0:ui.layout,W=!1,E=C?S:!0,K=!1,Q=null,X=()=>{K=!0,Q&&clearTimeout(Q),Q=setTimeout(()=>{K&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),K=!1)},1e4)},O=Yd(n,T,X),oe=(gi=(mi=n.features)==null?void 0:mi.showReasoning)!=null?gi:!0,Ee=(hi=(fi=n.features)==null?void 0:fi.showToolCalls)!=null?hi:!0,ae=(bi=(yi=n.features)==null?void 0:yi.showEventStreamToggle)!=null?bi:!1,we=(vi=(xi=n.features)==null?void 0:xi.scrollToBottom)!=null?vi:{},he=`${(wi=typeof n.persistState=="object"?(Ci=n.persistState)==null?void 0:Ci.keyPrefix:void 0)!=null?wi:"persona-"}event-stream`,We=ae?new Yo(he):null,Re=(Ei=(Ai=(Si=n.features)==null?void 0:Si.eventStream)==null?void 0:Ai.maxEvents)!=null?Ei:2e3,ie=ae?new Go(Re,We):null,Z=null,me=!1,V=null,re=0;We==null||We.open().then(()=>ie==null?void 0:ie.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let He={onCopy:l=>{var m,y;o.emit("message:copy",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.id,"copy").catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),D!=null&&D.isClientTokenMode()&&D.submitMessageFeedback(l.messageId,l.type).catch(A=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",A)}),(y=(m=n.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},ge=(Ti=n.statusIndicator)!=null?Ti:{},Be=l=>{var m,y,A,I;return l==="idle"?(m=ge.idleText)!=null?m:tn.idle:l==="connecting"?(y=ge.connectingText)!=null?y:tn.connecting:l==="connected"?(A=ge.connectedText)!=null?A:tn.connected:l==="error"?(I=ge.errorText)!=null?I:tn.error:tn[l]};function st(l,m,y,A){if(A==="idle"&&y.idleLink){l.textContent="";let I=document.createElement("a");I.href=y.idleLink,I.target="_blank",I.rel="noopener noreferrer",I.textContent=m,I.style.color="inherit",I.style.textDecoration="none",l.appendChild(I)}else l.textContent=m}let{wrapper:z,panel:U}=Md(n),se=kd(n,C),{container:N,body:J,messagesWrapper:ce,suggestions:fe,textarea:te,sendButton:pe,sendButtonWrapper:Lt,composerForm:dt,statusText:Wt,introTitle:Gt,introSubtitle:P,closeButton:$,iconHolder:ne,headerTitle:Pe,headerSubtitle:Fe,header:Ce,footer:be,actionsRow:at,leftActions:mt,rightActions:At}=se,j=se.micButton,xe=se.micButtonWrapper,ue=se.attachmentButton,Ze=se.attachmentButtonWrapper,qe=se.attachmentInput,de=se.attachmentPreviewsContainer;N.classList.add("persona-relative"),J.classList.add("persona-relative");let Te=12,Ve=()=>{var l;return(l=we.label)!=null?l:""},vt=()=>{var l;return(l=we.iconName)!=null?l:"arrow-down"},Ot=()=>we.enabled!==!1,pt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");pt.type="button",pt.style.display="none",pt.setAttribute("data-persona-scroll-to-bottom","true");let $t=h("span","persona-flex persona-items-center"),ht=h("span","");pt.append($t,ht),N.appendChild(pt);let Qe=()=>{let m=be.style.display==="none"?0:be.offsetHeight;pt.style.bottom=`${m+Te}px`};Qe();let yt=()=>{let l=!!Ve();pt.setAttribute("aria-label",Ve()||"Jump to latest"),pt.title=Ve(),pt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),$t.innerHTML="";let m=ye(vt(),"14px","currentColor",2);m?($t.appendChild(m),$t.style.display=""):$t.style.display="none",ht.textContent=Ve(),ht.style.display=l?"":"none"};yt();let je=null,_t=null,zn=s.find(l=>l.renderHeader);if(zn!=null&&zn.renderHeader){let l=zn.renderHeader({config:n,defaultRenderer:()=>{let m=ar({config:n,showClose:C});return qr(N,m,n),m.header},onClose:()=>Pt(!1,"user")});if(l){let m=N.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),Ce=l)}}let Kn=()=>{var m,y,A,I;if(!ie)return;if(me=!0,!Z&&ie&&(Z=Hd({buffer:ie,getFullHistory:()=>ie.getAllFromStore(),onClose:()=>Rn(),config:n,plugins:s})),Z&&(J.style.display="none",(m=be.parentNode)==null||m.insertBefore(Z.element,be),Z.update()),tt){tt.style.boxShadow=`inset 0 0 0 1.5px ${fn.actionIconColor}`;let R=(I=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:I.toggleButtonActive;R&&R.split(/\s+/).forEach(B=>B&&tt.classList.add(B))}let l=()=>{if(!me)return;let R=Date.now();R-re>=200&&(Z==null||Z.update(),re=R),V=requestAnimationFrame(l)};re=0,V=requestAnimationFrame(l),tr(),o.emit("eventStream:opened",{timestamp:Date.now()})},Rn=()=>{var l,m,y;if(me){if(me=!1,Z&&Z.element.remove(),J.style.display="",tt){tt.style.boxShadow="";let A=(y=(m=(l=n.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(I=>I&&tt.classList.remove(I))}V!==null&&(cancelAnimationFrame(V),V=null),tr(),o.emit("eventStream:closed",{timestamp:Date.now()})}},tt=null;if(ae){let l=(ki=(Mi=n.features)==null?void 0:Mi.eventStream)==null?void 0:ki.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");tt=h("button",m),tt.style.width="28px",tt.style.height="28px",tt.style.color=fn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let y=ye("activity","18px","currentColor",1.5);y&&tt.appendChild(y);let A=se.clearChatButtonWrapper,I=se.closeButtonWrapper,R=A||I;R&&R.parentNode===Ce?Ce.insertBefore(tt,R):Ce.appendChild(tt),tt.addEventListener("click",()=>{me?Rn():Kn()})}let Ar=l=>{var A,I,R;let m=n.attachments;if(!(m!=null&&m.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let B=l.querySelector("[data-persona-composer-form]");B!=null&&B.parentNode?B.parentNode.insertBefore(y,B):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let B=h("input");B.type="file",B.accept=((A=m.allowedTypes)!=null?A:sr).join(","),B.multiple=((I=m.maxFiles)!=null?I:4)>1,B.style.display="none",B.setAttribute("aria-label",(R=m.buttonTooltipText)!=null?R:"Attach files"),l.appendChild(B)}},qn=s.find(l=>l.renderComposer);if(qn!=null&&qn.renderComposer){let l=n.composer,m=qn.renderComposer({config:n,defaultRenderer:()=>co({config:n}).footer,onSubmit:y=>{var B;if(!D||D.isStreaming())return;let A=y.trim(),I=(B=je==null?void 0:je.hasAttachments())!=null?B:!1;if(!A&&!I)return;let R;I&&(R=[],R.push(...je.getContentParts()),A&&R.push(Bo(A))),D.sendMessage(A,{contentParts:R}),I&&je.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{qe==null||qe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y},n.agent&&(n.agent={...n.agent,model:y})},onVoiceToggle:((Li=n.voiceRecognition)==null?void 0:Li.enabled)===!0?()=>{_t==null||_t()}:void 0});m&&(be.replaceWith(m),be=m)}let Er=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),I=l.querySelector("[data-persona-composer-mic]"),R=l.querySelector("[data-persona-composer-status]");m&&(dt=m),y&&(te=y),A&&(pe=A),I&&(j=I,xe=I.parentElement),R&&(Wt=R);let B=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");B&&(fe=B);let G=l.querySelector(".persona-attachment-button");G&&(ue=G,Ze=G.parentElement),qe=l.querySelector('input[type="file"]'),de=l.querySelector(".persona-attachment-previews");let F=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");F&&(at=F)};Ar(be),Er(be);let En=(Ii=n.layout)==null?void 0:Ii.contentMaxWidth;if(En&&dt&&(dt.style.maxWidth=En,dt.style.marginLeft="auto",dt.style.marginRight="auto"),En&&fe&&(fe.style.maxWidth=En,fe.style.marginLeft="auto",fe.style.marginRight="auto"),En&&de&&(de.style.maxWidth=En,de.style.marginLeft="auto",de.style.marginRight="auto"),(Pi=n.attachments)!=null&&Pi.enabled&&qe&&de){je=zr.fromConfig(n.attachments),je.setPreviewsContainer(de),qe.addEventListener("change",y=>{let A=y.target;je==null||je.handleFileSelect(A.files),A.value=""});let l=n.attachments.dropOverlay,m=Kd(l);N.appendChild(m)}(()=>{var A,I;let l=(I=(A=n.layout)==null?void 0:A.slots)!=null?I:{},m=R=>{switch(R){case"body-top":return N.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return ce;case"footer-top":return fe;case"composer":return dt;case"footer-bottom":return Wt;default:return null}},y=(R,B)=>{var G;switch(R){case"header-left":case"header-center":case"header-right":if(R==="header-left")Ce.insertBefore(B,Ce.firstChild);else if(R==="header-right")Ce.appendChild(B);else{let F=Ce.querySelector(".persona-flex-col");F?(G=F.parentNode)==null||G.insertBefore(B,F.nextSibling):Ce.appendChild(B)}break;case"body-top":{let F=J.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");F?F.replaceWith(B):J.insertBefore(B,J.firstChild);break}case"body-bottom":J.appendChild(B);break;case"footer-top":fe.replaceWith(B);break;case"footer-bottom":Wt.replaceWith(B);break;default:break}};for(let[R,B]of Object.entries(l))if(B)try{let G=B({config:n,defaultContent:()=>m(R)});G&&y(R,G)}catch(G){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${R}":`,G)}})();let cr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-bubble-type");R==="reasoning"?(uo.has(I)?uo.delete(I):uo.add(I),Pd(I,A)):R==="tool"&&(mo.has(I)?mo.delete(I):mo.add(I),Wd(I,A,n)),Mn.delete(I)};ce.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cr(l))}),ce.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),cr(l))});let Xn=new Map;ce.addEventListener("click",l=>{var B;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest("[data-actions-for]");if(!A)return;let I=A.getAttribute("data-actions-for");if(!I)return;let R=y.getAttribute("data-action");if(R==="copy"){let F=D.getMessages().find(ve=>ve.id===I);if(F&&He.onCopy){let ve=F.content||"";navigator.clipboard.writeText(ve).then(()=>{y.classList.add("persona-message-action-success");let Se=ye("check",14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Me=ye("copy",14,"currentColor",2);Me&&(y.innerHTML="",y.appendChild(Me))},2e3)}).catch(Se=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",Se)}),He.onCopy(F)}}else if(R==="upvote"||R==="downvote"){let F=((B=Xn.get(I))!=null?B:null)===R,ve=R==="upvote"?"thumbs-up":"thumbs-down";if(F){Xn.delete(I),y.classList.remove("persona-message-action-active");let Se=ye(ve,14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se))}else{let Se=R==="upvote"?"downvote":"upvote",Me=A.querySelector(`[data-action="${Se}"]`);if(Me){Me.classList.remove("persona-message-action-active");let Ge=ye(Se==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);Ge&&(Me.innerHTML="",Me.appendChild(Ge))}Xn.set(I,R),y.classList.add("persona-message-action-active");let ke=ye(ve,14,"currentColor",2);ke&&(ke.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(ke)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ue=D.getMessages().find(lt=>lt.id===I);Ue&&He.onFeedback&&He.onFeedback({type:R,messageId:Ue.id,message:Ue})}}}),ce.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".persona-approval-bubble");if(!A)return;let I=A.getAttribute("data-message-id");if(!I)return;let R=y.getAttribute("data-approval-action");if(!R)return;let B=R==="approve"?"approved":"denied",F=D.getMessages().find(Se=>Se.id===I);if(!(F!=null&&F.approval))return;let ve=A.querySelector("[data-approval-buttons]");ve&&ve.querySelectorAll("button").forEach(Me=>{Me.disabled=!0,Me.style.opacity="0.5",Me.style.cursor="not-allowed"}),D.resolveApproval(F.approval,B)});let it=null,hn=null,Hn={artifacts:[],selectedId:null},nn=!1,dr={current:null};ce.addEventListener("click",l=>{var Me,ke,Ne,Ue,lt;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Ne=(ke=(Me=n.features)==null?void 0:Me.artifacts)==null?void 0:ke.onArtifactAction)==null?void 0:Ne.call(ke,{type:"download",artifactId:A}))===!0)return;let R=D.getArtifactById(A),B=R==null?void 0:R.markdown,G=(R==null?void 0:R.title)||"artifact";if(!B){let Ge=y.closest("[data-open-artifact]"),_=Ge==null?void 0:Ge.closest("[data-message-id]"),Oe=_==null?void 0:_.getAttribute("data-message-id");if(Oe){let Ae=D.getMessages().find(ze=>ze.id===Oe);if(Ae!=null&&Ae.rawContent)try{let ze=JSON.parse(Ae.rawContent);B=(Ue=ze==null?void 0:ze.props)==null?void 0:Ue.markdown,G=((lt=ze==null?void 0:ze.props)==null?void 0:lt.title)||G}catch{}}}if(!B)return;let F=new Blob([B],{type:"text/markdown"}),ve=URL.createObjectURL(F),Se=document.createElement("a");Se.href=ve,Se.download=`${G}.md`,Se.click(),URL.revokeObjectURL(ve)}),ce.addEventListener("click",l=>{var R,B,G;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((G=(B=(R=n.features)==null?void 0:R.artifacts)==null?void 0:B.onArtifactAction)==null?void 0:G.call(B,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),nn=!1,D.selectArtifact(A),bn())}),ce.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let yn=null,Et=null,rn=null,Tn=null,pr=()=>{};function Zn(){Tn==null||Tn(),Tn=null}let ur=()=>{var B;if(!yn||!Et)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((B=e.ownerDocument.defaultView)!=null?B:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){Et.style.removeProperty("position"),Et.style.removeProperty("left"),Et.style.removeProperty("top"),Et.style.removeProperty("bottom"),Et.style.removeProperty("width"),Et.style.removeProperty("z-index");return}let A=yn.firstElementChild;if(!A||A===Et)return;let I=10;Et.style.position="absolute",Et.style.top="0",Et.style.bottom="0",Et.style.width=`${I}px`,Et.style.zIndex="5";let R=A.offsetWidth-I/2;Et.style.left=`${Math.max(0,R)}px`},Un=()=>{},bn=()=>{var y,A,I,R,B;if(!it||!Wn(n))return;Us(e,n),Vs(e,n),Un();let l=(R=(I=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:I.narrowHostMaxWidth)!=null?R:520,m=U.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),it.update(Hn),nn?(it.setMobileOpen(!1),it.element.classList.add("persona-hidden"),(B=it.backdrop)==null||B.classList.add("persona-hidden")):Hn.artifacts.length>0&&(it.element.classList.remove("persona-hidden"),it.setMobileOpen(!0)),pr()};if(Wn(n)){U.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(N),it=Nd(n,{onSelect:y=>{var A;return(A=dr.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{nn=!0,bn()}}),it.element.classList.add("persona-hidden"),yn=m,m.appendChild(l),m.appendChild(it.element),it.backdrop&&U.appendChild(it.backdrop),U.appendChild(m),pr=()=>{var A,I,R,B;if(!yn||!it)return;if(!(((R=(I=(A=n.features)==null?void 0:A.artifacts)==null?void 0:I.layout)==null?void 0:R.resizable)===!0)){rn==null||rn(),rn=null,Zn(),Et&&(Et.remove(),Et=null),it.element.style.removeProperty("width"),it.element.style.removeProperty("maxWidth");return}if(!Et){let G=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");G.setAttribute("role","separator"),G.setAttribute("aria-orientation","vertical"),G.setAttribute("aria-label","Resize artifacts panel"),G.tabIndex=0;let F=e.ownerDocument,ve=(B=F.defaultView)!=null?B:window,Se=Me=>{var _,Oe;if(!it||Me.button!==0||e.classList.contains("persona-artifact-narrow-host")||ve.innerWidth<=640)return;Me.preventDefault(),Zn();let ke=Me.clientX,Ne=it.element.getBoundingClientRect().width,Ue=(Oe=(_=n.features)==null?void 0:_.artifacts)==null?void 0:Oe.layout,lt=_e=>{let Ae=yn.getBoundingClientRect().width,ze=e.classList.contains("persona-artifact-appearance-seamless"),St=ze?0:_d(yn,ve),xt=ze?0:G.getBoundingClientRect().width||6,Ut=Ne-(_e.clientX-ke),Xt=jd(Ut,Ae,St,xt,Ue==null?void 0:Ue.resizableMinWidth,Ue==null?void 0:Ue.resizableMaxWidth);it.element.style.width=`${Xt}px`,it.element.style.maxWidth="none",ur()},Ge=()=>{F.removeEventListener("pointermove",lt),F.removeEventListener("pointerup",Ge),F.removeEventListener("pointercancel",Ge),Tn=null;try{G.releasePointerCapture(Me.pointerId)}catch{}};Tn=Ge,F.addEventListener("pointermove",lt),F.addEventListener("pointerup",Ge),F.addEventListener("pointercancel",Ge);try{G.setPointerCapture(Me.pointerId)}catch{}};G.addEventListener("pointerdown",Se),Et=G,yn.insertBefore(G,it.element),rn=()=>{G.removeEventListener("pointerdown",Se)}}if(Et){let G=Hn.artifacts.length>0&&!nn;Et.classList.toggle("persona-hidden",!G),ur()}},Un=()=>{var ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae,ze,St;if(!C||!it||((Se=(ve=n.launcher)==null?void 0:ve.sidebarMode)!=null?Se:!1)||Jt(n)&&Pn(n).reveal==="emerge")return;let A=(Me=e.ownerDocument.defaultView)!=null?Me:window,I=(Ne=(ke=n.launcher)==null?void 0:ke.mobileFullscreen)!=null?Ne:!0,R=(lt=(Ue=n.launcher)==null?void 0:Ue.mobileBreakpoint)!=null?lt:640;if(I&&A.innerWidth<=R||!$d(n,C))return;let B=(Oe=(_=(Ge=n.launcher)==null?void 0:Ge.width)!=null?_:n.launcherWidth)!=null?Oe:An,G=(St=(ze=(Ae=(_e=n.features)==null?void 0:_e.artifacts)==null?void 0:Ae.layout)==null?void 0:ze.expandedPanelWidth)!=null?St:"min(720px, calc(100vw - 24px))";Hn.artifacts.length>0&&!nn?(U.style.width=G,U.style.maxWidth=G):(U.style.width=B,U.style.maxWidth=B)},typeof ResizeObserver!="undefined"&&(hn=new ResizeObserver(()=>{bn()}),hn.observe(U))}else U.appendChild(N);e.appendChild(z);let Vn=()=>{var xt,Ut,Xt,Ie,dn,Qt,$n,ot,gt,pn,rr,Ye,Tt,Wr,Rr,us,ms,gs,da,pa,jt,fs,Mo;let l=Jt(n),m=(Ut=(xt=n.launcher)==null?void 0:xt.sidebarMode)!=null?Ut:!1,y=l||m||((Ie=(Xt=n.launcher)==null?void 0:Xt.fullHeight)!=null?Ie:!1),A=((dn=n.launcher)==null?void 0:dn.enabled)===!1,I=($n=(Qt=n.theme)==null?void 0:Qt.components)==null?void 0:$n.panel,R=_o(n),B=(un,In)=>{var to;return un==null||un===""?In:(to=Oo(R,un))!=null?to:un},G=(ot=e.ownerDocument.defaultView)!=null?ot:window,F=(pn=(gt=n.launcher)==null?void 0:gt.mobileFullscreen)!=null?pn:!0,ve=(Ye=(rr=n.launcher)==null?void 0:rr.mobileBreakpoint)!=null?Ye:640,Se=G.innerWidth<=ve,Me=F&&Se&&C,ke=(Wr=(Tt=n.launcher)==null?void 0:Tt.position)!=null?Wr:"bottom-left",Ne=ke==="bottom-left"||ke==="top-left",Ue=(us=(Rr=n.launcher)==null?void 0:Rr.zIndex)!=null?us:gn,lt=m||Me?"none":"1px solid var(--persona-border)",Ge=Me?"none":m?Ne?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Me&&(Ge="none",lt="none");let _=m||Me?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Oe=B(I==null?void 0:I.border,lt),_e=B(I==null?void 0:I.shadow,Ge),Ae=B(I==null?void 0:I.borderRadius,_);if(e.style.cssText="",z.style.cssText="",U.style.cssText="",N.style.cssText="",J.style.cssText="",be.style.cssText="",Me){z.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),z.style.cssText=`
|
|
23
|
+
`,P.addEventListener("click",()=>{d=T,w.forEach((H,J)=>{let U=J<T;H.classList.toggle("selected",U),H.setAttribute("aria-checked",J===T-1?"true":"false")})}),w.push(P),v.appendChild(P)}f.appendChild(v);let I=null;if(u){let T=document.createElement("div");T.className="persona-feedback-comment-container",I=document.createElement("textarea"),I.className="persona-feedback-comment",I.placeholder=o,I.rows=3,I.setAttribute("aria-label","Additional comments"),T.appendChild(I),f.appendChild(T)}let j=document.createElement("div");j.className="persona-feedback-actions";let A=document.createElement("button");A.type="button",A.className="persona-feedback-btn persona-feedback-btn-skip",A.textContent=i,A.addEventListener("click",()=>{t==null||t(),p.remove()});let R=document.createElement("button");return R.type="button",R.className="persona-feedback-btn persona-feedback-btn-submit",R.textContent=a,R.addEventListener("click",async()=>{if(d===null){v.classList.add("persona-feedback-shake"),setTimeout(()=>v.classList.remove("persona-feedback-shake"),500);return}R.disabled=!0,R.textContent="Submitting...";try{let T=(I==null?void 0:I.value.trim())||void 0;await n(d,T),p.remove()}catch(T){R.disabled=!1,R.textContent=a,console.error("[CSAT Feedback] Failed to submit:",T)}}),j.appendChild(A),j.appendChild(R),f.appendChild(j),p.appendChild(f),p}function ya(e){let{onSubmit:n,onDismiss:t,title:r="How likely are you to recommend us?",subtitle:s="On a scale of 0 to 10",commentPlaceholder:o="What could we do better? (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:u=!0,lowLabel:c="Not likely",highLabel:p="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,g=document.createElement("div");g.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let E=document.createElement("h3");E.className="persona-feedback-title",E.textContent=r,x.appendChild(E);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,x.appendChild(v),g.appendChild(x);let w=document.createElement("div");w.className="persona-feedback-rating persona-feedback-rating-nps",w.setAttribute("role","radiogroup"),w.setAttribute("aria-label","Likelihood rating from 0 to 10");let I=document.createElement("div");I.className="persona-feedback-labels";let j=document.createElement("span");j.className="persona-feedback-label-low",j.textContent=c;let A=document.createElement("span");A.className="persona-feedback-label-high",A.textContent=p,I.appendChild(j),I.appendChild(A);let R=document.createElement("div");R.className="persona-feedback-numbers";let T=[];for(let $=0;$<=10;$++){let ie=document.createElement("button");ie.type="button",ie.className="persona-feedback-rating-btn persona-feedback-number-btn",ie.setAttribute("role","radio"),ie.setAttribute("aria-checked","false"),ie.setAttribute("aria-label",`Rating ${$} out of 10`),ie.textContent=String($),ie.dataset.rating=String($),$<=6?ie.classList.add("persona-feedback-detractor"):$<=8?ie.classList.add("persona-feedback-passive"):ie.classList.add("persona-feedback-promoter"),ie.addEventListener("click",()=>{f=$,T.forEach((be,pe)=>{be.classList.toggle("selected",pe===$),be.setAttribute("aria-checked",pe===$?"true":"false")})}),T.push(ie),R.appendChild(ie)}w.appendChild(I),w.appendChild(R),g.appendChild(w);let P=null;if(u){let $=document.createElement("div");$.className="persona-feedback-comment-container",P=document.createElement("textarea"),P.className="persona-feedback-comment",P.placeholder=o,P.rows=3,P.setAttribute("aria-label","Additional comments"),$.appendChild(P),g.appendChild($)}let H=document.createElement("div");H.className="persona-feedback-actions";let J=document.createElement("button");J.type="button",J.className="persona-feedback-btn persona-feedback-btn-skip",J.textContent=i,J.addEventListener("click",()=>{t==null||t(),d.remove()});let U=document.createElement("button");return U.type="button",U.className="persona-feedback-btn persona-feedback-btn-submit",U.textContent=a,U.addEventListener("click",async()=>{if(f===null){R.classList.add("persona-feedback-shake"),setTimeout(()=>R.classList.remove("persona-feedback-shake"),500);return}U.disabled=!0,U.textContent="Submitting...";try{let $=(P==null?void 0:P.value.trim())||void 0;await n(f,$),d.remove()}catch($){U.disabled=!1,U.textContent=a,console.error("[NPS Feedback] Failed to submit:",$)}}),H.appendChild(J),H.appendChild(U),g.appendChild(H),d.appendChild(g),d}var Eo="persona-chat-history",Lm=30*1e3,Im={"image/png":"png","image/jpeg":"jpg","image/jpg":"jpg","image/gif":"gif","image/webp":"webp","image/svg+xml":"svg","image/bmp":"bmp","image/tiff":"tiff"};function Pm(e){var r,s,o;if(!e)return[];let n=[],t=Array.from((r=e.items)!=null?r:[]);for(let a of t){if(a.kind!=="file"||!a.type.startsWith("image/"))continue;let i=a.getAsFile();if(!i)continue;if(i.name){n.push(i);continue}let u=(s=Im[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${u}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function ba(e){if(!e)return!1;let n=e.types;return n?typeof n.contains=="function"?n.contains("Files"):Array.from(n).includes("Files"):!1}function Wm(e){var n,t,r,s,o,a,i,u,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(s=(r=e.persist)==null?void 0:r.openState)!=null?s:!0,voiceState:(a=(o=e.persist)==null?void 0:o.voiceState)!=null?a:!0,focusInput:(u=(i=e.persist)==null?void 0:i.focusInput)!=null?u:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function Rm(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var ai=e=>!e||typeof e!="object"?{}:{...e},hp=e=>e.map(n=>({...n,streaming:!1})),yp=(e,n,t)=>{let r=e!=null&&e.markdown?Ur(e.markdown):null,s=mo(e==null?void 0:e.sanitize);return e!=null&&e.postprocessMessage&&s&&(e==null?void 0:e.sanitize)===void 0&&console.warn("[Persona] A custom postprocessMessage is active with the default HTML sanitizer. Tags or attributes not in the built-in allowlist will be stripped. To keep custom HTML, set `sanitize: false` or provide a custom sanitize function."),o=>{var c,p,d;let a=(c=o.text)!=null?c:"",i=(p=o.message.rawContent)!=null?p:null;if(n){let f=n.process({text:a,raw:i!=null?i:a,message:o.message,streaming:o.streaming});f!==null&&(a=f.text,f.persist||(o.message.__skipPersist=!0),f.resubmit&&!o.streaming&&t&&t())}let u;return e!=null&&e.postprocessMessage?u=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):r?u=r(a):u=uo(a),s?s(u):u}};function bp(e){var i,u,c,p;let n=h("div","persona-attachment-drop-overlay");e!=null&&e.background&&n.style.setProperty("--persona-drop-overlay-bg",e.background),(e==null?void 0:e.backdropBlur)!==void 0&&n.style.setProperty("--persona-drop-overlay-blur",e.backdropBlur),e!=null&&e.border&&n.style.setProperty("--persona-drop-overlay-border",e.border),e!=null&&e.borderRadius&&n.style.setProperty("--persona-drop-overlay-radius",e.borderRadius),e!=null&&e.inset&&n.style.setProperty("--persona-drop-overlay-inset",e.inset),e!=null&&e.labelSize&&n.style.setProperty("--persona-drop-overlay-label-size",e.labelSize),e!=null&&e.labelColor&&n.style.setProperty("--persona-drop-overlay-label-color",e.labelColor);let t=(i=e==null?void 0:e.iconName)!=null?i:"upload",r=(u=e==null?void 0:e.iconSize)!=null?u:"48px",s=(c=e==null?void 0:e.iconColor)!=null?c:"rgba(59, 130, 246, 0.6)",o=(p=e==null?void 0:e.iconStrokeWidth)!=null?p:.5,a=ye(t,r,s,o);if(a&&n.appendChild(a),e!=null&&e.label){let d=h("span","persona-drop-overlay-label");d.textContent=e.label,n.appendChild(d)}return n}var xa=(e,n,t)=>{var St,It,Kt,bt,At,Gt,sn,nn,jt,Fn,Ai,Ei,Ti,Mi,ki,Li,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Fi,Oi,$i,_i,ji,zi,qi,Vi,Ui,Ji,Ki,Gi,Yi,Xi,Zi,Qi,el;if(e==null)throw new Error('createAgentExperience: mount must be a non-null HTMLElement (e.g. pass document.getElementById("my-root") after the node exists).');e.id&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.hasAttribute("data-persona-root")||e.setAttribute("data-persona-root","true");let r=Zs(n),s=ms.getForInstance(r.plugins);r.components&&mr.registerAll(r.components);let o=up(),a=(St=r.storageAdapter)!=null?St:pa(),i={},u=null,c=!1,p=l=>{if(r.onStateLoaded)try{let m=r.onStateLoaded(l);if(m&&typeof m=="object"&&"state"in m){let{state:y,open:S}=m;return S&&(c=!0),y}return m}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",m)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")u=l.then(m=>{let y=m!=null?m:{messages:[],metadata:{}};return p(y)});else{let m=l!=null?l:{messages:[],metadata:{}},y=p(m);y.metadata&&(i=ai(y.metadata)),(It=y.messages)!=null&&It.length&&(r={...r,initialMessages:y.messages})}}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] Failed to load stored state:",l)}else if(r.onStateLoaded)try{let l=p({messages:[],metadata:{}});(Kt=l.messages)!=null&&Kt.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},ko()},g=r.actionParsers&&r.actionParsers.length?r.actionParsers:[gs],x=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[to.message,to.messageAndClick],E=fs({parsers:g,handlers:x,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});E.syncFromMetadata();let v=(At=(bt=r.launcher)==null?void 0:bt.enabled)!=null?At:!0,w=(sn=(Gt=r.launcher)==null?void 0:Gt.autoExpand)!=null?sn:!1,I=(nn=r.autoFocusInput)!=null?nn:!1,j=w,A=v,R=(Fn=(jt=r.layout)==null?void 0:jt.header)==null?void 0:Fn.layout,T=!1,P=v?w:!0,H=!1,J=null,U=()=>{H=!0,J&&clearTimeout(J),J=setTimeout(()=>{H&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),H=!1)},1e4)},$=yp(r,E,U),ie=(Ei=(Ai=r.features)==null?void 0:Ai.showReasoning)!=null?Ei:!0,be=(Mi=(Ti=r.features)==null?void 0:Ti.showToolCalls)!=null?Mi:!0,pe=(Li=(ki=r.features)==null?void 0:ki.showEventStreamToggle)!=null?Li:!1,Ne=(Pi=(Ii=r.features)==null?void 0:Ii.scrollToBottom)!=null?Pi:{},Re=`${(Ri=typeof r.persistState=="object"?(Wi=r.persistState)==null?void 0:Wi.keyPrefix:void 0)!=null?Ri:"persona-"}event-stream`,Ee=pe?new us(Re):null,He=(Di=(Bi=(Hi=r.features)==null?void 0:Hi.eventStream)==null?void 0:Bi.maxEvents)!=null?Di:2e3,de=pe?new ps(He,Ee):null,Q=null,he=!1,X=null,ge=0;Ee==null||Ee.open().then(()=>de==null?void 0:de.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ue={onCopy:l=>{var m,y;o.emit("message:copy",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.id,"copy").catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(y=(m=r.messageActions)==null?void 0:m.onCopy)==null||y.call(m,l)},onFeedback:l=>{var m,y;o.emit("message:feedback",l),O!=null&&O.isClientTokenMode()&&O.submitMessageFeedback(l.messageId,l.type).catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(y=(m=r.messageActions)==null?void 0:m.onFeedback)==null||y.call(m,l)}},oe=(Ni=r.statusIndicator)!=null?Ni:{},Te=l=>{var m,y,S,M;return l==="idle"?(m=oe.idleText)!=null?m:cn.idle:l==="connecting"?(y=oe.connectingText)!=null?y:cn.connecting:l==="connected"?(S=oe.connectedText)!=null?S:cn.connected:l==="error"?(M=oe.errorText)!=null?M:cn.error:cn[l]};function Me(l,m,y,S){if(S==="idle"&&y.idleLink){l.textContent="";let M=document.createElement("a");M.href=y.idleLink,M.target="_blank",M.rel="noopener noreferrer",M.textContent=m,M.style.color="inherit",M.style.textDecoration="none",l.appendChild(M)}else l.textContent=m}let{wrapper:k,panel:V}=Gd(r),ae=Yd(r,v),{container:D,body:q,messagesWrapper:le,suggestions:xe,textarea:ee,sendButton:se,sendButtonWrapper:Et,composerForm:ht,statusText:Ve,introTitle:Xt,introSubtitle:Qe,closeButton:fe,iconHolder:Ke,headerTitle:Bt,headerSubtitle:Dt,header:W,footer:re,actionsRow:Ie,leftActions:Oe,rightActions:Je}=ae,Ye=ae.setSendButtonMode,L=ae.micButton,ve=ae.micButtonWrapper,De=ae.attachmentButton,it=ae.attachmentButtonWrapper,Z=ae.attachmentInput,ne=ae.attachmentPreviewsContainer;D.classList.add("persona-relative"),q.classList.add("persona-relative");let _e=12,lt=()=>{var l;return(l=Ne.label)!=null?l:""},Rt=()=>{var l;return(l=Ne.iconName)!=null?l:"arrow-down"},Zt=()=>Ne.enabled!==!1,mt=h("button","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-z-10 persona-flex persona-items-center persona-gap-1 persona-text-xs persona-transform persona--translate-x-1/2 persona-cursor-pointer");mt.type="button",mt.style.display="none",mt.setAttribute("data-persona-scroll-to-bottom","true");let pt=h("span","persona-flex persona-items-center"),at=h("span","");mt.append(pt,at),D.appendChild(mt);let Ce=()=>{let m=re.style.display==="none"?0:re.offsetHeight;mt.style.bottom=`${m+_e}px`};Ce();let rt=()=>{let l=!!lt();mt.setAttribute("aria-label",lt()||"Jump to latest"),mt.title=lt(),mt.setAttribute("data-persona-scroll-to-bottom-has-label",l?"true":"false"),pt.innerHTML="";let m=ye(Rt(),"14px","currentColor",2);m?(pt.appendChild(m),pt.style.display=""):pt.style.display="none",at.textContent=lt(),at.style.display=l?"":"none"};rt();let je=null,Qt=null,en=s.find(l=>l.renderHeader);if(en!=null&&en.renderHeader){let l=en.renderHeader({config:r,defaultRenderer:()=>{let m=ur({config:r,showClose:v});return Qr(D,m,r),m.header},onClose:()=>Nt(!1,"user")});if(l){let m=D.querySelector(".persona-border-b-persona-divider");m&&(m.replaceWith(l),W=l)}}let Wn=()=>{var m,y,S,M;if(!de)return;if(he=!0,!Q&&de&&(Q=np({buffer:de,getFullHistory:()=>de.getAllFromStore(),onClose:()=>tn(),config:r,plugins:s})),Q&&(q.style.display="none",(m=re.parentNode)==null||m.insertBefore(Q.element,re),Q.update()),et){et.style.boxShadow=`inset 0 0 0 1.5px ${Cn.actionIconColor}`;let B=(M=(S=(y=r.features)==null?void 0:y.eventStream)==null?void 0:S.classNames)==null?void 0:M.toggleButtonActive;B&&B.split(/\s+/).forEach(F=>F&&et.classList.add(F))}let l=()=>{if(!he)return;let B=Date.now();B-ge>=200&&(Q==null||Q.update(),ge=B),X=requestAnimationFrame(l)};ge=0,X=requestAnimationFrame(l),ar(),o.emit("eventStream:opened",{timestamp:Date.now()})},tn=()=>{var l,m,y;if(he){if(he=!1,Q&&Q.element.remove(),q.style.display="",et){et.style.boxShadow="";let S=(y=(m=(l=r.features)==null?void 0:l.eventStream)==null?void 0:m.classNames)==null?void 0:y.toggleButtonActive;S&&S.split(/\s+/).forEach(M=>M&&et.classList.remove(M))}X!==null&&(cancelAnimationFrame(X),X=null),ar(),o.emit("eventStream:closed",{timestamp:Date.now()})}},et=null;if(pe){let l=(Oi=(Fi=r.features)==null?void 0:Fi.eventStream)==null?void 0:Oi.classNames,m="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");et=h("button",m),et.style.width="28px",et.style.height="28px",et.style.color=Cn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let y=ye("activity","18px","currentColor",1.5);y&&et.appendChild(y);let S=ae.clearChatButtonWrapper,M=ae.closeButtonWrapper,B=S||M;B&&B.parentNode===W?W.insertBefore(et,B):W.appendChild(et),et.addEventListener("click",()=>{he?tn():Wn()})}let fr=l=>{var S,M,B;let m=r.attachments;if(!(m!=null&&m.enabled))return;let y=l.querySelector(".persona-attachment-previews");if(!y){y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),y.style.display="none";let F=l.querySelector("[data-persona-composer-form]");F!=null&&F.parentNode?F.parentNode.insertBefore(y,F):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let F=h("input");F.type="file",F.accept=((S=m.allowedTypes)!=null?S:pr).join(","),F.multiple=((M=m.maxFiles)!=null?M:4)>1,F.style.display="none",F.setAttribute("aria-label",(B=m.buttonTooltipText)!=null?B:"Attach files"),l.appendChild(F)}},wn=s.find(l=>l.renderComposer);if(wn!=null&&wn.renderComposer){let l=r.composer,m=wn.renderComposer({config:r,defaultRenderer:()=>xo({config:r}).footer,onSubmit:y=>{var F;if(!O||O.isStreaming())return;let S=y.trim(),M=(F=je==null?void 0:je.hasAttachments())!=null?F:!1;if(!S&&!M)return;let B;M&&(B=[],B.push(...je.getContentParts()),S&&B.push(Yo(S))),O.sendMessage(S,{contentParts:B}),M&&je.clearAttachments()},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Z==null||Z.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y},r.agent&&(r.agent={...r.agent,model:y})},onVoiceToggle:(($i=r.voiceRecognition)==null?void 0:$i.enabled)===!0?()=>{Qt==null||Qt()}:void 0});m&&(re.replaceWith(m),re=m)}let Rr=l=>{let m=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),M=l.querySelector("[data-persona-composer-mic]"),B=l.querySelector("[data-persona-composer-status]");m&&(ht=m),y&&(ee=y),S&&(se=S),M&&(L=M,ve=M.parentElement),B&&(Ve=B);let F=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");F&&(xe=F);let K=l.querySelector(".persona-attachment-button");K&&(De=K,it=K.parentElement),Z=l.querySelector('input[type="file"]'),ne=l.querySelector(".persona-attachment-previews");let _=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");_&&(Ie=_)};fr(re),Rr(re);let Rn=(_i=r.layout)==null?void 0:_i.contentMaxWidth;if(Rn&&ht&&(ht.style.maxWidth=Rn,ht.style.marginLeft="auto",ht.style.marginRight="auto"),Rn&&xe&&(xe.style.maxWidth=Rn,xe.style.marginLeft="auto",xe.style.marginRight="auto"),Rn&&ne&&(ne.style.maxWidth=Rn,ne.style.marginLeft="auto",ne.style.marginRight="auto"),(ji=r.attachments)!=null&&ji.enabled&&Z&&ne){je=Zr.fromConfig(r.attachments),je.setPreviewsContainer(ne),Z.addEventListener("change",y=>{let S=y.target;je==null||je.handleFileSelect(S.files),S.value=""});let l=r.attachments.dropOverlay,m=bp(l);D.appendChild(m)}(()=>{var S,M;let l=(M=(S=r.layout)==null?void 0:S.slots)!=null?M:{},m=B=>{switch(B){case"body-top":return D.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return le;case"footer-top":return xe;case"composer":return ht;case"footer-bottom":return Ve;default:return null}},y=(B,F)=>{var K;switch(B){case"header-left":case"header-center":case"header-right":if(B==="header-left")W.insertBefore(F,W.firstChild);else if(B==="header-right")W.appendChild(F);else{let _=W.querySelector(".persona-flex-col");_?(K=_.parentNode)==null||K.insertBefore(F,_.nextSibling):W.appendChild(F)}break;case"body-top":{let _=q.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");_?_.replaceWith(F):q.insertBefore(F,q.firstChild);break}case"body-bottom":q.appendChild(F);break;case"footer-top":xe.replaceWith(F);break;case"footer-bottom":Ve.replaceWith(F);break;default:break}};for(let[B,F]of Object.entries(l))if(F)try{let K=F({config:r,defaultContent:()=>m(B)});K&&y(B,K)}catch(K){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${B}":`,K)}})();let hr=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let S=y.closest(".persona-reasoning-bubble, .persona-tool-bubble");if(!S)return;let M=S.getAttribute("data-message-id");if(!M)return;let B=y.getAttribute("data-bubble-type");B==="reasoning"?(Co.has(M)?Co.delete(M):Co.add(M),Qd(M,S)):B==="tool"&&(wo.has(M)?wo.delete(M):wo.add(M),ep(M,S,r)),Dn.delete(M)};le.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),hr(l))}),le.addEventListener("keydown",l=>{let m=l.target;(l.key==="Enter"||l.key===" ")&&m.closest('button[data-expand-header="true"]')&&(l.preventDefault(),hr(l))});let nr=new Map;le.addEventListener("click",l=>{var F;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.closest("[data-actions-for]");if(!S)return;let M=S.getAttribute("data-actions-for");if(!M)return;let B=y.getAttribute("data-action");if(B==="copy"){let _=O.getMessages().find(Se=>Se.id===M);if(_&&ue.onCopy){let Se=_.content||"";navigator.clipboard.writeText(Se).then(()=>{y.classList.add("persona-message-action-success");let ke=ye("check",14,"currentColor",2);ke&&(y.innerHTML="",y.appendChild(ke)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Pe=ye("copy",14,"currentColor",2);Pe&&(y.innerHTML="",y.appendChild(Pe))},2e3)}).catch(ke=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",ke)}),ue.onCopy(_)}}else if(B==="upvote"||B==="downvote"){let _=((F=nr.get(M))!=null?F:null)===B,Se=B==="upvote"?"thumbs-up":"thumbs-down";if(_){nr.delete(M),y.classList.remove("persona-message-action-active");let ke=ye(Se,14,"currentColor",2);ke&&(y.innerHTML="",y.appendChild(ke))}else{let ke=B==="upvote"?"downvote":"upvote",Pe=S.querySelector(`[data-action="${ke}"]`);if(Pe){Pe.classList.remove("persona-message-action-active");let nt=ye(ke==="upvote"?"thumbs-up":"thumbs-down",14,"currentColor",2);nt&&(Pe.innerHTML="",Pe.appendChild(nt))}nr.set(M,B),y.classList.add("persona-message-action-active");let We=ye(Se,14,"currentColor",2);We&&(We.setAttribute("fill","currentColor"),y.innerHTML="",y.appendChild(We)),y.classList.remove("persona-message-action-pop"),y.offsetWidth,y.classList.add("persona-message-action-pop");let Ge=O.getMessages().find(ft=>ft.id===M);Ge&&ue.onFeedback&&ue.onFeedback({type:B,messageId:Ge.id,message:Ge})}}}),le.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.closest(".persona-approval-bubble");if(!S)return;let M=S.getAttribute("data-message-id");if(!M)return;let B=y.getAttribute("data-approval-action");if(!B)return;let F=B==="approve"?"approved":"denied",_=O.getMessages().find(ke=>ke.id===M);if(!(_!=null&&_.approval))return;let Se=S.querySelector("[data-approval-buttons]");Se&&Se.querySelectorAll("button").forEach(Pe=>{Pe.disabled=!0,Pe.style.opacity="0.5",Pe.style.cursor="not-allowed"}),O.resolveApproval(_.approval,F)});let gt=null,Sn=null,jn={artifacts:[],selectedId:null},dn=!1,yr={current:null};le.addEventListener("click",l=>{var Pe,We,Fe,Ge,ft;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.getAttribute("data-download-artifact");if(!S||((Fe=(We=(Pe=r.features)==null?void 0:Pe.artifacts)==null?void 0:We.onArtifactAction)==null?void 0:Fe.call(We,{type:"download",artifactId:S}))===!0)return;let B=O.getArtifactById(S),F=B==null?void 0:B.markdown,K=(B==null?void 0:B.title)||"artifact";if(!F){let nt=y.closest("[data-open-artifact]"),z=nt==null?void 0:nt.closest("[data-message-id]"),$e=z==null?void 0:z.getAttribute("data-message-id");if($e){let Le=O.getMessages().find(Ue=>Ue.id===$e);if(Le!=null&&Le.rawContent)try{let Ue=JSON.parse(Le.rawContent);F=(Ge=Ue==null?void 0:Ue.props)==null?void 0:Ge.markdown,K=((ft=Ue==null?void 0:Ue.props)==null?void 0:ft.title)||K}catch{}}}if(!F)return;let _=new Blob([F],{type:"text/markdown"}),Se=URL.createObjectURL(_),ke=document.createElement("a");ke.href=Se,ke.download=`${K}.md`,ke.click(),URL.revokeObjectURL(Se)}),le.addEventListener("click",l=>{var B,F,K;let y=l.target.closest("[data-open-artifact]");if(!y)return;let S=y.getAttribute("data-open-artifact");!S||((K=(F=(B=r.features)==null?void 0:B.artifacts)==null?void 0:F.onArtifactAction)==null?void 0:K.call(F,{type:"open",artifactId:S}))===!0||(l.preventDefault(),l.stopPropagation(),dn=!1,O.selectArtifact(S),En())}),le.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let m=l.target;m.hasAttribute("data-open-artifact")&&(l.preventDefault(),m.click())});let An=null,Mt=null,pn=null,Hn=null,br=()=>{};function rr(){Hn==null||Hn(),Hn=null}let xr=()=>{var F;if(!An||!Mt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((F=e.ownerDocument.defaultView)!=null?F:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){Mt.style.removeProperty("position"),Mt.style.removeProperty("left"),Mt.style.removeProperty("top"),Mt.style.removeProperty("bottom"),Mt.style.removeProperty("width"),Mt.style.removeProperty("z-index");return}let S=An.firstElementChild;if(!S||S===Mt)return;let M=10;Mt.style.position="absolute",Mt.style.top="0",Mt.style.bottom="0",Mt.style.width=`${M}px`,Mt.style.zIndex="5";let B=S.offsetWidth-M/2;Mt.style.left=`${Math.max(0,B)}px`},Xn=()=>{},En=()=>{var y,S,M,B,F;if(!gt||!_n(r))return;ca(e,r),da(e,r),Xn();let l=(B=(M=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:M.narrowHostMaxWidth)!=null?B:520,m=V.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",m>0&&m<=l),gt.update(jn),dn?(gt.setMobileOpen(!1),gt.element.classList.add("persona-hidden"),(F=gt.backdrop)==null||F.classList.add("persona-hidden")):jn.artifacts.length>0&&(gt.element.classList.remove("persona-hidden"),gt.setMobileOpen(!0)),br()};if(_n(r)){V.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),m=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(D),gt=sp(r,{onSelect:y=>{var S;return(S=yr.current)==null?void 0:S.selectArtifact(y)},onDismiss:()=>{dn=!0,En()}}),gt.element.classList.add("persona-hidden"),An=m,m.appendChild(l),m.appendChild(gt.element),gt.backdrop&&V.appendChild(gt.backdrop),V.appendChild(m),br=()=>{var S,M,B,F;if(!An||!gt)return;if(!(((B=(M=(S=r.features)==null?void 0:S.artifacts)==null?void 0:M.layout)==null?void 0:B.resizable)===!0)){pn==null||pn(),pn=null,rr(),Mt&&(Mt.remove(),Mt=null),gt.element.style.removeProperty("width"),gt.element.style.removeProperty("maxWidth");return}if(!Mt){let K=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");K.setAttribute("role","separator"),K.setAttribute("aria-orientation","vertical"),K.setAttribute("aria-label","Resize artifacts panel"),K.tabIndex=0;let _=e.ownerDocument,Se=(F=_.defaultView)!=null?F:window,ke=Pe=>{var z,$e;if(!gt||Pe.button!==0||e.classList.contains("persona-artifact-narrow-host")||Se.innerWidth<=640)return;Pe.preventDefault(),rr();let We=Pe.clientX,Fe=gt.element.getBoundingClientRect().width,Ge=($e=(z=r.features)==null?void 0:z.artifacts)==null?void 0:$e.layout,ft=qe=>{let Le=An.getBoundingClientRect().width,Ue=e.classList.contains("persona-artifact-appearance-seamless"),Tt=Ue?0:cp(An,Se),xt=Ue?0:K.getBoundingClientRect().width||6,Vt=Fe-(qe.clientX-We),rn=dp(Vt,Le,Tt,xt,Ge==null?void 0:Ge.resizableMinWidth,Ge==null?void 0:Ge.resizableMaxWidth);gt.element.style.width=`${rn}px`,gt.element.style.maxWidth="none",xr()},nt=()=>{_.removeEventListener("pointermove",ft),_.removeEventListener("pointerup",nt),_.removeEventListener("pointercancel",nt),Hn=null;try{K.releasePointerCapture(Pe.pointerId)}catch{}};Hn=nt,_.addEventListener("pointermove",ft),_.addEventListener("pointerup",nt),_.addEventListener("pointercancel",nt);try{K.setPointerCapture(Pe.pointerId)}catch{}};K.addEventListener("pointerdown",ke),Mt=K,An.insertBefore(K,gt.element),pn=()=>{K.removeEventListener("pointerdown",ke)}}if(Mt){let K=jn.artifacts.length>0&&!dn;Mt.classList.toggle("persona-hidden",!K),xr()}},Xn=()=>{var Se,ke,Pe,We,Fe,Ge,ft,nt,z,$e,qe,Le,Ue,Tt;if(!v||!gt||((ke=(Se=r.launcher)==null?void 0:Se.sidebarMode)!=null?ke:!1)||Jt(r)&&$n(r).reveal==="emerge")return;let S=(Pe=e.ownerDocument.defaultView)!=null?Pe:window,M=(Fe=(We=r.launcher)==null?void 0:We.mobileFullscreen)!=null?Fe:!0,B=(ft=(Ge=r.launcher)==null?void 0:Ge.mobileBreakpoint)!=null?ft:640;if(M&&S.innerWidth<=B||!lp(r,v))return;let F=($e=(z=(nt=r.launcher)==null?void 0:nt.width)!=null?z:r.launcherWidth)!=null?$e:Pn,K=(Tt=(Ue=(Le=(qe=r.features)==null?void 0:qe.artifacts)==null?void 0:Le.layout)==null?void 0:Ue.expandedPanelWidth)!=null?Tt:"min(720px, calc(100vw - 24px))";jn.artifacts.length>0&&!dn?(V.style.width=K,V.style.maxWidth=K):(V.style.width=F,V.style.maxWidth=F)},typeof ResizeObserver!="undefined"&&(Sn=new ResizeObserver(()=>{En()}),Sn.observe(V))}else V.appendChild(D);e.appendChild(k);let Zn=()=>{var rn,Be,hn,an,Kn,ut,vt,yn,cr,ot,kt,_r,jr,Is,Ps,Ws,La,Ia,qt,Rs,jo,zo,po;let l=Jt(r),m=(Be=(rn=r.launcher)==null?void 0:rn.sidebarMode)!=null?Be:!1,y=l||m||((an=(hn=r.launcher)==null?void 0:hn.fullHeight)!=null?an:!1),S=((Kn=r.launcher)==null?void 0:Kn.enabled)===!1,M=(vt=(ut=r.theme)==null?void 0:ut.components)==null?void 0:vt.panel,B=ns(r),F=(bn,on)=>{var On;return bn==null||bn===""?on:(On=es(B,bn))!=null?On:bn},K=(yn=e.ownerDocument.defaultView)!=null?yn:window,_=(ot=(cr=r.launcher)==null?void 0:cr.mobileFullscreen)!=null?ot:!0,Se=(_r=(kt=r.launcher)==null?void 0:kt.mobileBreakpoint)!=null?_r:640,ke=K.innerWidth<=Se,Pe=_&&ke&&v,We=(Is=(jr=r.launcher)==null?void 0:jr.position)!=null?Is:"bottom-left",Fe=We==="bottom-left"||We==="top-left",Ge=(Ws=(Ps=r.launcher)==null?void 0:Ps.zIndex)!=null?Ws:vn,ft=m||Pe?"none":"1px solid var(--persona-border)",nt=Pe?"none":m?Fe?"var(--persona-palette-shadows-sidebar-left, 2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-sidebar-right, -2px 0 12px rgba(0, 0, 0, 0.08))":"var(--persona-palette-shadows-xl, 0 25px 50px -12px rgba(0, 0, 0, 0.25))";l&&!Pe&&(nt="none",ft="none");let z=m||Pe?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",$e=F(M==null?void 0:M.border,ft),qe=F(M==null?void 0:M.shadow,nt),Le=F(M==null?void 0:M.borderRadius,z),Ue=q.scrollTop;e.style.cssText="",k.style.cssText="",V.style.cssText="",D.style.cssText="",q.style.cssText="",re.style.cssText="";let Tt=()=>{var on;if(Ue<=0)return;((on=q.ownerDocument.defaultView)!=null?on:window).requestAnimationFrame(()=>{if(q.scrollTop===Ue)return;let On=q.scrollHeight-q.clientHeight;On<=0||(q.scrollTop=Math.min(Ue,On))})};if(Pe){k.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),k.style.cssText=`
|
|
23
24
|
position: fixed !important;
|
|
24
25
|
inset: 0 !important;
|
|
25
26
|
width: 100% !important;
|
|
@@ -29,9 +30,9 @@
|
|
|
29
30
|
padding: 0 !important;
|
|
30
31
|
display: flex !important;
|
|
31
32
|
flex-direction: column !important;
|
|
32
|
-
z-index: ${
|
|
33
|
+
z-index: ${Ge} !important;
|
|
33
34
|
background-color: var(--persona-surface, #ffffff) !important;
|
|
34
|
-
`,
|
|
35
|
+
`,V.style.cssText=`
|
|
35
36
|
position: relative !important;
|
|
36
37
|
display: flex !important;
|
|
37
38
|
flex-direction: column !important;
|
|
@@ -44,7 +45,7 @@
|
|
|
44
45
|
padding: 0 !important;
|
|
45
46
|
box-shadow: none !important;
|
|
46
47
|
border-radius: 0 !important;
|
|
47
|
-
`,
|
|
48
|
+
`,D.style.cssText=`
|
|
48
49
|
display: flex !important;
|
|
49
50
|
flex-direction: column !important;
|
|
50
51
|
flex: 1 1 0% !important;
|
|
@@ -55,20 +56,20 @@
|
|
|
55
56
|
overflow: hidden !important;
|
|
56
57
|
border-radius: 0 !important;
|
|
57
58
|
border: none !important;
|
|
58
|
-
`,
|
|
59
|
+
`,q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",re.style.flexShrink="0",T=!0,Tt();return}let xt=(Ia=(La=r==null?void 0:r.launcher)==null?void 0:La.width)!=null?Ia:r==null?void 0:r.launcherWidth,Vt=xt!=null?xt:Pn;if(!m&&!l)S&&y?(V.style.width="100%",V.style.maxWidth="100%"):(V.style.width=Vt,V.style.maxWidth=Vt);else if(l)if($n(r).reveal==="emerge"){let on=$n(r).width;V.style.width=on,V.style.maxWidth=on}else V.style.width="100%",V.style.maxWidth="100%";if(Xn(),V.style.boxShadow=qe,V.style.borderRadius=Le,D.style.border=$e,D.style.borderRadius=Le,l&&!Pe&&(M==null?void 0:M.border)===void 0&&(D.style.border="none",$n(r).side==="right"?D.style.borderLeft="1px solid var(--persona-border)":D.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",S&&(e.style.width="100%"),k.style.display="flex",k.style.flexDirection="column",k.style.flex="1 1 0%",k.style.minHeight="0",k.style.maxHeight="100%",k.style.height="100%",S&&(k.style.overflow="hidden"),V.style.display="flex",V.style.flexDirection="column",V.style.flex="1 1 0%",V.style.minHeight="0",V.style.maxHeight="100%",V.style.height="100%",V.style.overflow="hidden",D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.overflow="hidden",q.style.flex="1 1 0%",q.style.minHeight="0",q.style.overflowY="auto",re.style.flexShrink="0"),k.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!m&&!S&&!l&&((qt=Yn[We])!=null?qt:Yn["bottom-right"]).split(" ").forEach(on=>k.classList.add(on)),m){let bn=(jo=(Rs=r.launcher)==null?void 0:Rs.sidebarWidth)!=null?jo:"420px";k.style.cssText=`
|
|
59
60
|
position: fixed !important;
|
|
60
61
|
top: 0 !important;
|
|
61
62
|
bottom: 0 !important;
|
|
62
|
-
width: ${
|
|
63
|
+
width: ${bn} !important;
|
|
63
64
|
height: 100vh !important;
|
|
64
65
|
max-height: 100vh !important;
|
|
65
66
|
margin: 0 !important;
|
|
66
67
|
padding: 0 !important;
|
|
67
68
|
display: flex !important;
|
|
68
69
|
flex-direction: column !important;
|
|
69
|
-
z-index: ${
|
|
70
|
-
${
|
|
71
|
-
`,
|
|
70
|
+
z-index: ${Ge} !important;
|
|
71
|
+
${Fe?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
|
|
72
|
+
`,V.style.cssText=`
|
|
72
73
|
position: relative !important;
|
|
73
74
|
display: flex !important;
|
|
74
75
|
flex-direction: column !important;
|
|
@@ -79,9 +80,9 @@
|
|
|
79
80
|
min-height: 0 !important;
|
|
80
81
|
margin: 0 !important;
|
|
81
82
|
padding: 0 !important;
|
|
82
|
-
box-shadow: ${
|
|
83
|
-
border-radius: ${
|
|
84
|
-
`,
|
|
83
|
+
box-shadow: ${qe} !important;
|
|
84
|
+
border-radius: ${Le} !important;
|
|
85
|
+
`,V.style.setProperty("width","100%","important"),V.style.setProperty("max-width","100%","important"),D.style.cssText=`
|
|
85
86
|
display: flex !important;
|
|
86
87
|
flex-direction: column !important;
|
|
87
88
|
flex: 1 1 0% !important;
|
|
@@ -90,29 +91,29 @@
|
|
|
90
91
|
min-height: 0 !important;
|
|
91
92
|
max-height: 100% !important;
|
|
92
93
|
overflow: hidden !important;
|
|
93
|
-
border-radius: ${
|
|
94
|
-
border: ${
|
|
95
|
-
`,
|
|
94
|
+
border-radius: ${Le} !important;
|
|
95
|
+
border: ${$e} !important;
|
|
96
|
+
`,re.style.cssText=`
|
|
96
97
|
flex-shrink: 0 !important;
|
|
97
98
|
border-top: none !important;
|
|
98
99
|
padding: 8px 16px 12px 16px !important;
|
|
99
|
-
`}if(!A&&!l){let un="max-height: -moz-available !important; max-height: stretch !important;",In=m?"":"padding-top: 1.25em !important;",to=m?"":`z-index: ${(Mo=(fs=n.launcher)==null?void 0:fs.zIndex)!=null?Mo:gn} !important;`;z.style.cssText+=un+In+to}};Vn(),xr(e,n),Us(e,n),Vs(e,n);let Ct=[],Bt=null,Dt=null;Ct.push(()=>{Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null}),hn&&Ct.push(()=>{hn==null||hn.disconnect(),hn=null}),Ct.push(()=>{rn==null||rn(),rn=null,Zn(),Et&&(Et.remove(),Et=null),it==null||it.element.style.removeProperty("width"),it==null||it.element.style.removeProperty("maxWidth")}),ae&&Ct.push(()=>{V!==null&&(cancelAnimationFrame(V),V=null),Z==null||Z.destroy(),Z=null,ie==null||ie.destroy(),ie=null,We=null});let xn=null,mr=()=>{xn&&(xn(),xn=null),n.colorScheme==="auto"&&(xn=Fs(()=>{xr(e,n)}))};mr(),Ct.push(()=>{xn&&(xn(),xn=null)});let Bn=Rd(fe),vn=null,D,Dn=!1,Mn=Sd(),gr=0,an=Os(),ln=0,le=null,Cn=!1,Qn=!1,es=4,yo=24,ts=80,Yr=new Map,et={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},bo=(Ri=(Wi=n.voiceRecognition)==null?void 0:Wi.autoResume)!=null?Ri:!1,kn=l=>{o.emit("voice:state",{active:et.active,source:l,timestamp:Date.now()})},cn=()=>{f(l=>({...l,voiceState:{active:et.active,timestamp:Date.now(),manuallyDeactivated:et.manuallyDeactivated}}))},ns=()=>{var A,I;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Na(i.voiceState),m=!!l.active,y=Number((I=l.timestamp)!=null?I:0);et.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Ku&&setTimeout(()=>{var R,B;et.active||(et.manuallyDeactivated=!1,((B=(R=n.voiceRecognition)==null?void 0:R.provider)==null?void 0:B.type)==="runtype"?D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),kn("restore"),D.isVoiceActive()&&yr()}):Lr("restore"))},1e3)},rs=()=>D?Gd(D.getMessages()).filter(l=>!l.__skipPersist):[];function xo(l){if(!(a!=null&&a.save))return;let y={messages:l?Gd(l):D?rs():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(I=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",I)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let er=null,os=()=>z.querySelector("#persona-scroll-container")||J,Tr=()=>{er!==null&&(cancelAnimationFrame(er),er=null),Cn=!1},vo=()=>{le!==null&&(cancelAnimationFrame(le),le=null),Qn=!1,Tr()},tr=()=>{if(!Ot()||me){pt.parentNode&&pt.remove(),pt.style.display="none";return}pt.parentNode!==N&&N.appendChild(pt),Qe();let l=jo(J)>0;pt.style.display=an.isFollowing()||!l?"none":""},Co=()=>{an.pause()&&(vo(),tr())},fr=()=>{an.resume(),tr()},hr=(l=!1)=>{an.isFollowing()&&(!l&&!Dn||(le!==null&&(cancelAnimationFrame(le),le=null),Qn=!0,le=requestAnimationFrame(()=>{le=null,Qn=!1,an.isFollowing()&&ss(os(),l?220:140)})))},ss=(l,m=500)=>{let y=l.scrollTop,A=jo(l),I=A-y;if(Math.abs(I)<1){ln=l.scrollTop;return}if(Math.abs(I)>=ts){Tr(),Cn=!0,l.scrollTop=A,ln=l.scrollTop,Cn=!1;return}Tr();let R=performance.now();Cn=!0;let B=F=>1-Math.pow(1-F,3),G=F=>{if(!an.isFollowing()){Tr();return}let ve=jo(l);ve!==A&&(A=ve,I=A-y);let Se=F-R,Me=Math.min(Se/m,1),ke=B(Me),Ne=y+I*ke;l.scrollTop=Ne,ln=l.scrollTop,Me<1?er=requestAnimationFrame(G):(l.scrollTop=A,ln=l.scrollTop,er=null,Cn=!1)};er=requestAnimationFrame(G)},as=l=>{let m=new Map;l.forEach(y=>{let A=Yr.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!A&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(A!=null&&A.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(A?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),Yr.clear(),m.forEach((y,A)=>{Yr.set(A,y)})},Mr=(l,m,y)=>{var Me,ke,Ne,Ue,lt,Ge;let A=document.createElement("div"),R=(()=>{var Oe;let _=s.find(_e=>_e.renderLoadingIndicator);if(_!=null&&_.renderLoadingIndicator)return _.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),B=(_,Oe)=>Oe==null?!1:typeof Oe=="string"?(_.textContent=Oe,!0):(_.appendChild(Oe),!0),G=new Set;if(m.forEach(_=>{var Ut,Xt;G.add(_.id);let Oe=wd(_,gr),_e=Ad(Mn,_.id,Oe);if(_e){A.appendChild(_e.cloneNode(!0));return}let Ae=null,ze=s.find(Ie=>!!(_.variant==="reasoning"&&Ie.renderReasoning||_.variant==="tool"&&Ie.renderToolCall||_.variant==="approval"&&Ie.renderApproval||!_.variant&&Ie.renderMessage)),St=(Ut=n.layout)==null?void 0:Ut.messages;if(ze)if(_.variant==="reasoning"&&_.reasoning&&ze.renderReasoning){if(!oe)return;Ae=ze.renderReasoning({message:_,defaultRenderer:()=>La(_,n),config:n})}else if(_.variant==="tool"&&_.toolCall&&ze.renderToolCall){if(!Ee)return;Ae=ze.renderToolCall({message:_,defaultRenderer:()=>Ia(_,n),config:n})}else if(_.variant==="approval"&&_.approval&&ze.renderApproval){if(n.approval===!1)return;Ae=ze.renderApproval({message:_,defaultRenderer:()=>Pa(_,n),config:n})}else ze.renderMessage&&(Ae=ze.renderMessage({message:_,defaultRenderer:()=>{let Ie=po(_,y,St,n.messageActions,He,{loadingIndicatorRenderer:R,widgetConfig:n});return _.role!=="user"&&Ha(Ie,_,n,D),Ie},config:n}));if(!Ae&&_.role==="assistant"&&!_.variant&&n.enableComponentStreaming!==!1&&Ks(_)){let dn=Xs(_);if(dn){let Qt=Ys(dn,{config:n,message:_,transform:y});if(Qt)if(n.wrapComponentDirectiveInBubble!==!1){let ot=document.createElement("div");if(ot.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(gt)}ot.appendChild(Qt),Ae=ot}else{let ot=document.createElement("div");if(ot.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ot.id=`bubble-${_.id}`,ot.setAttribute("data-message-id",_.id),ot.setAttribute("data-persona-component-directive","true"),_.content&&_.content.trim()){let gt=document.createElement("div");gt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gt.innerHTML=y({text:_.content,message:_,streaming:!!_.streaming,raw:_.rawContent}),ot.appendChild(gt)}ot.appendChild(Qt),Ae=ot}}}if(!Ae)if(_.variant==="reasoning"&&_.reasoning){if(!oe)return;Ae=La(_,n)}else if(_.variant==="tool"&&_.toolCall){if(!Ee)return;Ae=Ia(_,n)}else if(_.variant==="approval"&&_.approval){if(n.approval===!1)return;Ae=Pa(_,n)}else{let Ie=(Xt=n.layout)==null?void 0:Xt.messages;Ie!=null&&Ie.renderUserMessage&&_.role==="user"?Ae=Ie.renderUserMessage({message:_,config:n,streaming:!!_.streaming}):Ie!=null&&Ie.renderAssistantMessage&&_.role==="assistant"?Ae=Ie.renderAssistantMessage({message:_,config:n,streaming:!!_.streaming}):Ae=po(_,y,Ie,n.messageActions,He,{loadingIndicatorRenderer:R,widgetConfig:n}),_.role!=="user"&&Ae&&Ha(Ae,_,n,D)}let xt=document.createElement("div");xt.className="persona-flex",xt.id=`wrapper-${_.id}`,xt.setAttribute("data-wrapper-id",_.id),_.role==="user"&&xt.classList.add("persona-justify-end"),(Ae==null?void 0:Ae.getAttribute("data-persona-component-directive"))==="true"&&xt.classList.add("persona-w-full"),xt.appendChild(Ae),Ed(Mn,_.id,Oe,xt),A.appendChild(xt)}),(ke=(Me=n.features)==null?void 0:Me.toolCallDisplay)!=null&&ke.grouped){let _=[],Oe=[];m.forEach(_e=>{if(_e.variant==="tool"&&_e.toolCall&&Ee){Oe.push(_e);return}Oe.length>1&&_.push(Oe),Oe=[]}),Oe.length>1&&_.push(Oe),_.forEach((_e,Ae)=>{var Qt,$n;let ze=_e.map(ot=>Array.from(A.children).find(gt=>gt instanceof HTMLElement&>.getAttribute("data-wrapper-id")===ot.id)).filter(ot=>!!ot);if(ze.length<2)return;let St=document.createElement("div");St.className="persona-flex",St.id=`wrapper-tool-group-${Ae}-${_e[0].id}`,St.setAttribute("data-wrapper-id",`tool-group-${Ae}-${_e[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let Ut=document.createElement("div");Ut.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let Xt=`Called ${_e.length} tools`,Ie=($n=(Qt=n.toolCall)==null?void 0:Qt.renderGroupedSummary)==null?void 0:$n.call(Qt,{messages:_e,toolCalls:_e.map(ot=>ot.toolCall).filter(ot=>!!ot),defaultSummary:Xt,config:n});B(Ut,Ie)||(Ut.textContent=Xt);let dn=document.createElement("div");dn.className="persona-tool-group-stack persona-flex persona-flex-col",xt.append(Ut,dn),St.appendChild(xt),ze[0].before(St),ze.forEach((ot,gt)=>{let pn=document.createElement("div");pn.className="persona-tool-group-item persona-relative",pn.setAttribute("data-persona-tool-group-item","true"),gt<ze.length-1&&pn.setAttribute("data-persona-tool-group-connector","true"),pn.appendChild(ot),dn.appendChild(pn)})})}Td(Mn,G);let F=m.some(_=>_.role==="assistant"&&_.streaming),ve=m[m.length-1],Se=(ve==null?void 0:ve.role)==="assistant"&&!ve.streaming&&ve.variant!=="approval";if(Dn&&m.some(_=>_.role==="user")&&!F&&!Se){let _={config:n,streaming:!0,location:"standalone",defaultRenderer:Ur},Oe=s.find(Ae=>Ae.renderLoadingIndicator),_e=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(_e=Oe.renderLoadingIndicator(_)),_e===null&&((Ne=n.loadingIndicator)!=null&&Ne.render)&&(_e=n.loadingIndicator.render(_)),_e===null&&(_e=Ur()),_e){let Ae=document.createElement("div"),ze=((Ue=n.loadingIndicator)==null?void 0:Ue.showBubble)!==!1;Ae.className=ze?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ae.setAttribute("data-typing-indicator","true"),Ae.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Ae.appendChild(_e);let St=document.createElement("div");St.className="persona-flex",St.id="wrapper-typing-indicator",St.setAttribute("data-wrapper-id","typing-indicator"),St.appendChild(Ae),A.appendChild(St)}}if(!Dn&&m.length>0){let _=m[m.length-1],Oe={config:n,lastMessage:_,messageCount:m.length},_e=s.find(ze=>ze.renderIdleIndicator),Ae=null;if(_e!=null&&_e.renderIdleIndicator&&(Ae=_e.renderIdleIndicator(Oe)),Ae===null&&((lt=n.loadingIndicator)!=null&<.renderIdle)&&(Ae=n.loadingIndicator.renderIdle(Oe)),Ae){let ze=document.createElement("div"),St=((Ge=n.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;ze.className=St?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),ze.setAttribute("data-idle-indicator","true"),ze.appendChild(Ae);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(ze),A.appendChild(xt)}}Cd(l,A)},kr=()=>{var F,ve,Se,Me,ke;if(!C)return;let l=Jt(n),m=(F=e.ownerDocument.defaultView)!=null?F:window,y=(Se=(ve=n.launcher)==null?void 0:ve.mobileBreakpoint)!=null?Se:640,A=(ke=(Me=n.launcher)==null?void 0:Me.mobileFullscreen)!=null?ke:!0,I=m.innerWidth<=y,R=A&&I&&C,B=Pn(n).reveal;E?(z.style.removeProperty("display"),z.style.display=l?"flex":"",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-95","persona-opacity-0"),U.classList.add("persona-scale-100","persona-opacity-100"),b?b.element.style.display="none":k&&(k.style.display="none")):(l?l&&(B==="overlay"||B==="push")&&!R?(z.style.removeProperty("display"),z.style.display="flex",z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.setProperty("display","none","important"),z.classList.remove("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(z.style.display="",z.classList.add("persona-pointer-events-none","persona-opacity-0"),U.classList.remove("persona-scale-100","persona-opacity-100"),U.classList.add("persona-scale-95","persona-opacity-0")),b?b.element.style.display=l?"none":"":k&&(k.style.display=l?"none":""))},Pt=(l,m="user")=>{var R,B;if(!C||E===l)return;let y=E;E=l,kr();let A=(()=>{var Ne,Ue,lt,Ge,_,Oe,_e;let G=(Ue=(Ne=n.launcher)==null?void 0:Ne.sidebarMode)!=null?Ue:!1,F=(lt=e.ownerDocument.defaultView)!=null?lt:window,ve=(_=(Ge=n.launcher)==null?void 0:Ge.mobileFullscreen)!=null?_:!0,Se=(_e=(Oe=n.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?_e:640,Me=F.innerWidth<=Se,ke=Jt(n)&&ve&&Me;return G||ve&&Me&&C||ke})();if(E&&A){if(!Bt){let G=e.getRootNode(),F=G instanceof ShadowRoot?G.host:e.closest(".persona-host");F&&(Bt=wa(F,(B=(R=n.launcher)==null?void 0:R.zIndex)!=null?B:gn))}Dt||(Dt=Sa(e.ownerDocument))}else E||(Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null);E&&(v(),hr(!0));let I={open:E,source:m,timestamp:Date.now()};E&&!y?o.emit("widget:opened",I):!E&&y&&o.emit("widget:closed",I),o.emit("widget:state",{open:E,launcherEnabled:C,voiceActive:et.active,streaming:D.isStreaming()})},Kr=l=>{pe.disabled=l,j&&(j.disabled=l),Bn.buttons.forEach(m=>{m.disabled=l}),be.dataset.personaComposerStreaming=l?"true":"false",be.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},Xr=()=>{et.active||te&&te.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>Xr(),200)});let wo=()=>{var y,A,I,R,B,G,F,ve,Se,Me,ke;Gt.textContent=(A=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?A:"Hello \u{1F44B}",P.textContent=(R=(I=n.copy)==null?void 0:I.welcomeSubtitle)!=null?R:"Ask anything about your account or products.",te.placeholder=(G=(B=n.copy)==null?void 0:B.inputPlaceholder)!=null?G:"How can I help...";let l=J.querySelector("[data-persona-intro-card]");if(l){let Ne=((F=n.copy)==null?void 0:F.showWelcomeCard)!==!1;l.style.display=Ne?"":"none",Ne?(J.classList.remove("persona-gap-3"),J.classList.add("persona-gap-6")):(J.classList.remove("persona-gap-6"),J.classList.add("persona-gap-3"))}(Se=(ve=n.sendButton)==null?void 0:ve.useIcon)!=null&&Se||(pe.textContent=(ke=(Me=n.copy)==null?void 0:Me.sendButtonLabel)!=null?ke:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Jn=null,is=()=>{Jn==null&&(Jn=setInterval(()=>{let l=ce.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Jn),Jn=null;return}let m=Date.now();l.forEach(y=>{let A=Number(y.getAttribute("data-tool-elapsed"));A&&(y.textContent=vs(m-A))})},100))};if(D=new ao(n,{onMessagesChanged(l){Mr(ce,l,O),is(),D&&(l.some(I=>I.role==="user")?Bn.render([],D,te,l):Bn.render(n.suggestionChips,D,te,l,n.suggestionChipsConfig)),hr(!Dn),as(l);let m=[...l].reverse().find(A=>A.role==="user"),y=et.lastUserMessageId;m&&m.id!==y&&(et.lastUserMessageId=m.id,o.emit("user:message",m)),et.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),xo(l)},onStatusChanged(l){var A;let m=(A=n.statusIndicator)!=null?A:{};st(Wt,(I=>{var R,B,G,F;return I==="idle"?(R=m.idleText)!=null?R:tn.idle:I==="connecting"?(B=m.connectingText)!=null?B:tn.connecting:I==="connected"?(G=m.connectedText)!=null?G:tn.connected:I==="error"?(F=m.errorText)!=null?F:tn.error:tn[I]})(l),m,l)},onStreamingChanged(l){Dn=l,Kr(l),D&&Mr(ce,D.getMessages(),O),l||hr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":Fn(),cs();break;case"speaking":Fn(),ds();break;default:l==="idle"&&D.isBargeInActive()?(Fn(),yr(),j==null||j.setAttribute("aria-label","End voice session")):(et.active=!1,Fn(),kn("system"),cn());break}},onArtifactsState(l){Hn=l,bn()}}),dr.current=D,((Bi=(Hi=n.voiceRecognition)==null?void 0:Hi.provider)==null?void 0:Bi.type)==="runtype")try{D.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&D.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(ie||n.onSSEEvent)&&D.setSSEEventCallback((l,m)=>{var y;(y=n.onSSEEvent)==null||y.call(n,l,m),ie==null||ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=Na(l.metadata),T.syncFromMetadata()),(m=l.messages)!=null&&m.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let So=l=>{var I;l.preventDefault();let m=te.value.trim(),y=(I=je==null?void 0:je.hasAttachments())!=null?I:!1;if(!m&&!y)return;let A;y&&(A=[],A.push(...je.getContentParts()),m&&A.push(Bo(m))),te.value="",te.style.height="auto",D.sendMessage(m,{contentParts:A}),y&&je.clearAttachments()},Ao=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),pe.click())},Eo=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!je)return;let m=Zu(l.clipboardData);m.length!==0&&(l.preventDefault(),await je.handleFiles(m))},on=null,wn=!1,nr=null,Je=null,To=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Lr=(l="user")=>{var R,B,G,F,ve,Se,Me;if(wn||D.isStreaming())return;let m=To();if(!m)return;on=new m;let A=(B=((R=n.voiceRecognition)!=null?R:{}).pauseDuration)!=null?B:2e3;on.continuous=!0,on.interimResults=!0,on.lang="en-US";let I=te.value;on.onresult=ke=>{let Ne="",Ue="";for(let Ge=0;Ge<ke.results.length;Ge++){let _=ke.results[Ge],Oe=_[0].transcript;_.isFinal?Ne+=Oe+" ":Ue=Oe}let lt=I+Ne+Ue;te.value=lt,nr&&clearTimeout(nr),(Ne||Ue)&&(nr=window.setTimeout(()=>{let Ge=te.value.trim();Ge&&on&&wn&&(Nn(),te.value="",te.style.height="auto",D.sendMessage(Ge,{viaVoice:!0}))},A))},on.onerror=ke=>{ke.error!=="no-speech"&&Nn()},on.onend=()=>{if(wn){let ke=te.value.trim();ke&&ke!==I.trim()&&(te.value="",te.style.height="auto",D.sendMessage(ke,{viaVoice:!0})),Nn()}};try{if(on.start(),wn=!0,et.active=!0,l!=="system"&&(et.manuallyDeactivated=!1),kn(l),cn(),j){let ke=(G=n.voiceRecognition)!=null?G:{};Je={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(F=ke.iconName)!=null?F:"mic",iconSize:parseFloat((Me=(Se=ke.iconSize)!=null?Se:(ve=n.sendButton)==null?void 0:ve.size)!=null?Me:"40")||24};let Ne=ke.recordingBackgroundColor,Ue=ke.recordingIconColor,lt=ke.recordingBorderColor;if(j.classList.add("persona-voice-recording"),j.style.backgroundColor=Ne!=null?Ne:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=Ue!=null?Ue:"var(--persona-voice-recording-indicator, #ffffff)",Ue){let Ge=j.querySelector("svg");Ge&&Ge.setAttribute("stroke",Ue)}lt&&(j.style.borderColor=lt),j.setAttribute("aria-label","Stop voice recognition")}}catch{Nn("system")}},Nn=(l="user")=>{if(wn){if(wn=!1,nr&&(clearTimeout(nr),nr=null),on){try{on.stop()}catch{}on=null}if(et.active=!1,kn(l),cn(),j){if(j.classList.remove("persona-voice-recording"),Je){j.style.backgroundColor=Je.backgroundColor,j.style.color=Je.color,j.style.borderColor=Je.borderColor;let m=j.querySelector("svg");m&&m.setAttribute("stroke",Je.color||"currentColor"),Je=null}j.setAttribute("aria-label","Start voice recognition")}}},ls=(l,m)=>{var _,Oe,_e,Ae,ze,St,xt,Ut;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((_=l==null?void 0:l.provider)==null?void 0:_.type)==="runtype";if(!(y||A))return null;let R=h("div","persona-send-button-wrapper"),B=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");B.type="button",B.setAttribute("aria-label","Start voice recognition");let G=(Oe=l==null?void 0:l.iconName)!=null?Oe:"mic",F=(_e=m==null?void 0:m.size)!=null?_e:"40px",ve=(Ae=l==null?void 0:l.iconSize)!=null?Ae:F,Se=parseFloat(ve)||24,Me=(ze=l==null?void 0:l.backgroundColor)!=null?ze:m==null?void 0:m.backgroundColor,ke=(St=l==null?void 0:l.iconColor)!=null?St:m==null?void 0:m.textColor;B.style.width=ve,B.style.height=ve,B.style.minWidth=ve,B.style.minHeight=ve,B.style.fontSize="18px",B.style.lineHeight="1",ke?B.style.color=ke:B.style.color="var(--persona-text, #111827)";let Ue=ye(G,Se,ke||"currentColor",1.5);Ue?B.appendChild(Ue):B.textContent="\u{1F3A4}",Me?B.style.backgroundColor=Me:B.style.backgroundColor="",l!=null&&l.borderWidth&&(B.style.borderWidth=l.borderWidth,B.style.borderStyle="solid"),l!=null&&l.borderColor&&(B.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(B.style.paddingLeft=l.paddingX,B.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(B.style.paddingTop=l.paddingY,B.style.paddingBottom=l.paddingY),R.appendChild(B);let lt=(xt=l==null?void 0:l.tooltipText)!=null?xt:"Start voice recognition";if(((Ut=l==null?void 0:l.showTooltip)!=null?Ut:!1)&<){let Xt=h("div","persona-send-button-tooltip");Xt.textContent=lt,R.appendChild(Xt)}return{micButton:B,micButtonWrapper:R}},Zr=()=>{var m,y,A,I,R;if(!j||Je)return;let l=(m=n.voiceRecognition)!=null?m:{};Je={backgroundColor:j.style.backgroundColor,color:j.style.color,borderColor:j.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((R=(I=l.iconSize)!=null?I:(A=n.sendButton)==null?void 0:A.size)!=null?R:"40")||24}},Qr=(l,m)=>{var R,B,G,F,ve;if(!j)return;let y=j.querySelector("svg");y&&y.remove();let A=(ve=Je==null?void 0:Je.iconSize)!=null?ve:parseFloat((F=(G=(R=n.voiceRecognition)==null?void 0:R.iconSize)!=null?G:(B=n.sendButton)==null?void 0:B.size)!=null?F:"40")||24,I=ye(l,A,m,1.5);I&&j.appendChild(I)},Ir=()=>{j&&j.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},yr=()=>{var I;if(!j)return;Zr();let l=(I=n.voiceRecognition)!=null?I:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,A=l.recordingBorderColor;if(Ir(),j.classList.add("persona-voice-recording"),j.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",j.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let R=j.querySelector("svg");R&&R.setAttribute("stroke",y)}A&&(j.style.borderColor=A),j.setAttribute("aria-label","Stop voice recognition")},cs=()=>{var G,F,ve,Se,Me,ke,Ne,Ue;if(!j)return;Zr();let l=(G=n.voiceRecognition)!=null?G:{},m=D.getVoiceInterruptionMode(),y=(F=l.processingIconName)!=null?F:"loader",A=(Se=(ve=l.processingIconColor)!=null?ve:Je==null?void 0:Je.color)!=null?Se:"",I=(ke=(Me=l.processingBackgroundColor)!=null?Me:Je==null?void 0:Je.backgroundColor)!=null?ke:"",R=(Ue=(Ne=l.processingBorderColor)!=null?Ne:Je==null?void 0:Je.borderColor)!=null?Ue:"";Ir(),j.classList.add("persona-voice-processing"),j.style.backgroundColor=I,j.style.borderColor=R;let B=A||"currentColor";j.style.color=B,Qr(y,B),j.setAttribute("aria-label","Processing voice input"),m==="none"&&(j.style.cursor="default")},ds=()=>{var ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae;if(!j)return;Zr();let l=(ve=n.voiceRecognition)!=null?ve:{},m=D.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",A=(Se=l.speakingIconName)!=null?Se:y,I=(Ue=l.speakingIconColor)!=null?Ue:m==="barge-in"?(ke=(Me=l.recordingIconColor)!=null?Me:Je==null?void 0:Je.color)!=null?ke:"":(Ne=Je==null?void 0:Je.color)!=null?Ne:"",R=(_=l.speakingBackgroundColor)!=null?_:m==="barge-in"?(lt=l.recordingBackgroundColor)!=null?lt:"var(--persona-voice-recording-bg, #ef4444)":(Ge=Je==null?void 0:Je.backgroundColor)!=null?Ge:"",B=(Ae=l.speakingBorderColor)!=null?Ae:m==="barge-in"?(Oe=l.recordingBorderColor)!=null?Oe:"":(_e=Je==null?void 0:Je.borderColor)!=null?_e:"";Ir(),j.classList.add("persona-voice-speaking"),j.style.backgroundColor=R,j.style.borderColor=B;let G=I||"currentColor";j.style.color=G,Qr(A,G);let F=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";j.setAttribute("aria-label",F),m==="none"&&(j.style.cursor="default"),m==="barge-in"&&j.classList.add("persona-voice-recording")},Fn=()=>{var l,m,y;j&&(Ir(),Je&&(j.style.backgroundColor=(l=Je.backgroundColor)!=null?l:"",j.style.color=(m=Je.color)!=null?m:"",j.style.borderColor=(y=Je.borderColor)!=null?y:"",Qr(Je.iconName,Je.color||"currentColor"),Je=null),j.style.cursor="",j.setAttribute("aria-label","Start voice recognition"))},Pr=()=>{var l,m;if(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=D.getVoiceStatus(),A=D.getVoiceInterruptionMode();if(A==="none"&&(y==="processing"||y==="speaking"))return;if(A==="cancel"&&(y==="processing"||y==="speaking")){D.stopVoicePlayback();return}if(D.isBargeInActive()){D.stopVoicePlayback(),D.deactivateBargeIn().then(()=>{et.active=!1,et.manuallyDeactivated=!0,cn(),kn("user"),Fn()});return}D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),et.manuallyDeactivated=!D.isVoiceActive(),cn(),kn("user"),D.isVoiceActive()?yr():Fn()});return}if(wn){let y=te.value.trim();et.manuallyDeactivated=!0,cn(),Nn("user"),y&&(te.value="",te.style.height="auto",D.sendMessage(y))}else et.manuallyDeactivated=!1,cn(),Lr("user")};_t=Pr,j&&(j.addEventListener("click",Pr),Ct.push(()=>{var l,m;((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),Fn()):Nn("system"),j&&j.removeEventListener("click",Pr)}));let ps=o.on("assistant:complete",()=>{bo&&(et.active||et.manuallyDeactivated||bo==="assistant"&&!et.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!et.active&&!et.manuallyDeactivated&&(((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),kn("auto"),D.isVoiceActive()&&yr()}):Lr("auto"))},600))});Ct.push(ps);let eo=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});Ct.push(eo);let De=()=>{Pt(!E,"user")},b=null,k=null;if(C){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:n,defaultRenderer:()=>Uo(n,De).element,onToggle:De});m&&(k=m)}k||(b=Uo(n,De))}b?e.appendChild(b.element):k&&e.appendChild(k),kr(),Bn.render(n.suggestionChips,D,te,void 0,n.suggestionChipsConfig),wo(),Kr(D.isStreaming()),hr(!0),ns(),M&&(C?E&&setTimeout(()=>Xr(),200):setTimeout(()=>Xr(),0));let v=()=>{var F,ve,Se,Me,ke,Ne,Ue,lt,Ge,_,Oe,_e,Ae,ze,St,xt,Ut,Xt,Ie,dn,Qt,$n;let l=Jt(n),m=(ve=(F=n.launcher)==null?void 0:F.sidebarMode)!=null?ve:!1,y=l||m||((Me=(Se=n.launcher)==null?void 0:Se.fullHeight)!=null?Me:!1),A=(ke=e.ownerDocument.defaultView)!=null?ke:window,I=(Ue=(Ne=n.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ue:!0,R=(Ge=(lt=n.launcher)==null?void 0:lt.mobileBreakpoint)!=null?Ge:640,B=A.innerWidth<=R,G=I&&B&&C;try{if(G){Vn(),xr(e,n);return}if(W&&(W=!1,Vn(),xr(e,n)),!C&&!l){U.style.height="",U.style.width="";return}if(!m&&!l){let ot=(Oe=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?Oe:n==null?void 0:n.launcherWidth,gt=ot!=null?ot:An;U.style.width=gt,U.style.maxWidth=gt}if(Un(),!y){let ot=A.innerHeight,gt=64,pn=(Ae=(_e=n.launcher)==null?void 0:_e.heightOffset)!=null?Ae:0,rr=Math.max(200,ot-gt),Ye=Math.min(640,rr),Tt=Math.max(200,Ye-pn);U.style.height=`${Tt}px`}}finally{if(Qe(),kr(),E&&C){let gt=((ze=e.ownerDocument.defaultView)!=null?ze:window).innerWidth<=((xt=(St=n.launcher)==null?void 0:St.mobileBreakpoint)!=null?xt:640),pn=(Xt=(Ut=n.launcher)==null?void 0:Ut.sidebarMode)!=null?Xt:!1,rr=(dn=(Ie=n.launcher)==null?void 0:Ie.mobileFullscreen)!=null?dn:!0,Ye=Jt(n)&&rr&>,Tt=pn||rr&>&&C||Ye;if(Tt&&!Dt){let Wr=e.getRootNode(),Rr=Wr instanceof ShadowRoot?Wr.host:e.closest(".persona-host");Rr&&!Bt&&(Bt=wa(Rr,($n=(Qt=n.launcher)==null?void 0:Qt.zIndex)!=null?$n:gn)),Dt=Sa(e.ownerDocument)}else Tt||(Bt==null||Bt(),Bt=null,Dt==null||Dt(),Dt=null)}}};v();let ee=(Di=e.ownerDocument.defaultView)!=null?Di:window;if(ee.addEventListener("resize",v),Ct.push(()=>ee.removeEventListener("resize",v)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Qe()});l.observe(be),Ct.push(()=>l.disconnect())}ln=J.scrollTop;let q=()=>{let l=J.scrollTop,{action:m,nextLastScrollTop:y}=$s({following:an.isFollowing(),currentScrollTop:l,lastScrollTop:ln,nearBottom:zo(J,yo),userScrollThreshold:es,isAutoScrolling:Cn||Qn,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(ln=y,m==="resume"){fr();return}m==="pause"&&Co()};J.addEventListener("scroll",q,{passive:!0}),Ct.push(()=>J.removeEventListener("scroll",q));let Le=l=>{let m=_s({following:an.isFollowing(),deltaY:l.deltaY,nearBottom:zo(J,yo),resumeWhenNearBottom:!0});m==="pause"?Co():m==="resume"&&fr()};J.addEventListener("wheel",Le,{passive:!0}),Ct.push(()=>J.removeEventListener("wheel",Le)),pt.addEventListener("click",()=>{J.scrollTop=J.scrollHeight,ln=J.scrollTop,fr(),hr(!0)}),Ct.push(()=>pt.remove()),Ct.push(()=>{vo()});let Xe=()=>{$&&(vn&&($.removeEventListener("click",vn),vn=null),C?($.style.display="",vn=()=>{Pt(!1,"user")},$.addEventListener("click",vn)):$.style.display="none")};Xe(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{D.clearMessages(),Mn.clear(),fr();try{localStorage.removeItem(ho),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ho}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ho)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(A=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",A)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},T.syncFromMetadata(),ie==null||ie.clear(),Z==null||Z.update()})})(),dt&&dt.addEventListener("submit",So),te==null||te.addEventListener("keydown",Ao),te==null||te.addEventListener("paste",Eo);let wt="persona-attachment-drop-active",Yt=0,Ht=()=>{Yt=0,N.classList.remove(wt)},Zt=()=>{var l;return((l=n.attachments)==null?void 0:l.enabled)===!0&&je!==null},rt=l=>{!ea(l.dataTransfer)||!Zt()||(Yt++,Yt===1&&N.classList.add(wt))},ut=l=>{!ea(l.dataTransfer)||!Zt()||(Yt--,Yt<=0&&Ht())},zt=l=>{!ea(l.dataTransfer)||!Zt()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},On=l=>{var y;if(!ea(l.dataTransfer)||!Zt())return;l.preventDefault(),l.stopPropagation(),Ht();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&je.handleFiles(m)},bt=!0;N.addEventListener("dragenter",rt,bt),N.addEventListener("dragleave",ut,bt),e.addEventListener("dragover",zt,bt),e.addEventListener("drop",On,bt);let Nt=e.ownerDocument,ti=l=>{Zt()&&l.preventDefault()},ni=l=>{Zt()&&l.preventDefault()};Nt.addEventListener("dragover",ti),Nt.addEventListener("drop",ni),Ct.push(()=>{dt&&dt.removeEventListener("submit",So),te==null||te.removeEventListener("keydown",Ao),te==null||te.removeEventListener("paste",Eo)}),Ct.push(()=>{N.removeEventListener("dragenter",rt,bt),N.removeEventListener("dragleave",ut,bt),e.removeEventListener("dragover",zt,bt),e.removeEventListener("drop",On,bt),Nt.removeEventListener("dragover",ti),Nt.removeEventListener("drop",ni),Ht()}),Ct.push(()=>{D.cancel()}),b?Ct.push(()=>{b==null||b.destroy()}):k&&Ct.push(()=>{k==null||k.remove()});let qt={update(l){var zi,qi,Ui,Vi,Ji,Gi,Yi,Ki,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Ul,Vl,Jl,Gl,Yl,Kl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Sc,Ac,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,zc;let m=n.toolCall,y=n.messageActions,A=(zi=n.layout)==null?void 0:zi.messages,I=n.colorScheme,R=n.loadingIndicator,B=n.iterationDisplay,G=(qi=n.features)==null?void 0:qi.showReasoning,F=(Ui=n.features)==null?void 0:Ui.showToolCalls,ve=(Vi=n.features)==null?void 0:Vi.toolCallDisplay,Se=(Ji=n.features)==null?void 0:Ji.reasoningDisplay;n={...n,...l},Vn(),xr(e,n),Us(e,n),Vs(e,n),bn(),n.colorScheme!==I&&mr();let Me=Ko.getForInstance(n.plugins);s.length=0,s.push(...Me),C=(Yi=(Gi=n.launcher)==null?void 0:Gi.enabled)!=null?Yi:!0,S=(Xi=(Ki=n.launcher)==null?void 0:Ki.autoExpand)!=null?Xi:!1,oe=(Qi=(Zi=n.features)==null?void 0:Zi.showReasoning)!=null?Qi:!0,Ee=(tl=(el=n.features)==null?void 0:el.showToolCalls)!=null?tl:!0,we=(rl=(nl=n.features)==null?void 0:nl.scrollToBottom)!=null?rl:{},yt(),tr();let ke=ae;if(ae=(sl=(ol=n.features)==null?void 0:ol.showEventStreamToggle)!=null?sl:!1,ae&&!ke){if(ie||(We=new Yo(he),ie=new Go(Re,We),We.open().then(()=>ie==null?void 0:ie.restore()).catch(()=>{}),D.setSSEEventCallback((Y,ct)=>{var Mt;(Mt=n.onSSEEvent)==null||Mt.call(n,Y,ct),ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Y,timestamp:Date.now(),payload:JSON.stringify(ct)})})),!tt&&Ce){let Y=(il=(al=n.features)==null?void 0:al.eventStream)==null?void 0:il.classNames,ct="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(Y!=null&&Y.toggleButton?" "+Y.toggleButton:"");tt=h("button",ct),tt.style.width="28px",tt.style.height="28px",tt.style.color=fn.actionIconColor,tt.type="button",tt.setAttribute("aria-label","Event Stream"),tt.title="Event Stream";let Mt=ye("activity","18px","currentColor",1.5);Mt&&tt.appendChild(Mt);let Ke=se.clearChatButtonWrapper,ft=se.closeButtonWrapper,Vt=Ke||ft;Vt&&Vt.parentNode===Ce?Ce.insertBefore(tt,Vt):Ce.appendChild(tt),tt.addEventListener("click",()=>{me?Rn():Kn()})}}else!ae&&ke&&(Rn(),tt&&(tt.remove(),tt=null),ie==null||ie.clear(),We==null||We.destroy(),ie=null,We=null);if(((ll=n.launcher)==null?void 0:ll.enabled)===!1&&b&&(b.destroy(),b=null),((cl=n.launcher)==null?void 0:cl.enabled)===!1&&k&&(k.remove(),k=null),((dl=n.launcher)==null?void 0:dl.enabled)!==!1&&!b&&!k){let Y=s.find(ct=>ct.renderLauncher);if(Y!=null&&Y.renderLauncher){let ct=Y.renderLauncher({config:n,defaultRenderer:()=>Uo(n,De).element,onToggle:De});ct&&(k=ct,e.appendChild(k))}k||(b=Uo(n,De),e.appendChild(b.element))}b&&b.update(n),Pe&&((pl=n.launcher)==null?void 0:pl.title)!==void 0&&(Pe.textContent=n.launcher.title),Fe&&((ul=n.launcher)==null?void 0:ul.subtitle)!==void 0&&(Fe.textContent=n.launcher.subtitle);let Ne=(ml=n.layout)==null?void 0:ml.header;if((Ne==null?void 0:Ne.layout)!==L&&Ce){let Y=Ne?lo(n,Ne,{showClose:C,onClose:()=>Pt(!1,"user")}):ar({config:n,showClose:C,onClose:()=>Pt(!1,"user")});Ce.replaceWith(Y.header),Ce=Y.header,ne=Y.iconHolder,Pe=Y.headerTitle,Fe=Y.headerSubtitle,$=Y.closeButton,L=Ne==null?void 0:Ne.layout}else if(Ne&&(ne&&(ne.style.display=Ne.showIcon===!1?"none":""),Pe&&(Pe.style.display=Ne.showTitle===!1?"none":""),Fe&&(Fe.style.display=Ne.showSubtitle===!1?"none":""),$&&($.style.display=Ne.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let Y=Ne.showClearChat;if(Y!==void 0){se.clearChatButtonWrapper.style.display=Y?"":"none";let{closeButtonWrapper:ct}=se;ct&&!ct.classList.contains("persona-absolute")&&(Y?ct.classList.remove("persona-ml-auto"):ct.classList.add("persona-ml-auto"))}}let lt=((gl=n.layout)==null?void 0:gl.showHeader)!==!1;Ce&&(Ce.style.display=lt?"":"none");let Ge=((fl=n.layout)==null?void 0:fl.showFooter)!==!1;be&&(be.style.display=Ge?"":"none"),Qe(),tr(),C!==w?C?Pt(S,"auto"):(E=!0,kr()):S!==H&&Pt(S,"auto"),H=S,w=C,v(),Xe();let _e=JSON.stringify(l.toolCall)!==JSON.stringify(m),Ae=JSON.stringify(n.messageActions)!==JSON.stringify(y),ze=JSON.stringify((hl=n.layout)==null?void 0:hl.messages)!==JSON.stringify(A),St=((yl=n.loadingIndicator)==null?void 0:yl.render)!==(R==null?void 0:R.render)||((bl=n.loadingIndicator)==null?void 0:bl.renderIdle)!==(R==null?void 0:R.renderIdle)||((xl=n.loadingIndicator)==null?void 0:xl.showBubble)!==(R==null?void 0:R.showBubble),xt=n.iterationDisplay!==B,Ut=((Cl=(vl=n.features)==null?void 0:vl.showReasoning)!=null?Cl:!0)!==(G!=null?G:!0)||((Sl=(wl=n.features)==null?void 0:wl.showToolCalls)!=null?Sl:!0)!==(F!=null?F:!0)||JSON.stringify((Al=n.features)==null?void 0:Al.toolCallDisplay)!==JSON.stringify(ve)||JSON.stringify((El=n.features)==null?void 0:El.reasoningDisplay)!==JSON.stringify(Se);(_e||Ae||ze||St||xt||Ut)&&D&&(gr++,Mr(ce,D.getMessages(),O));let Ie=(Tl=n.launcher)!=null?Tl:{},dn=(Ml=Ie.headerIconHidden)!=null?Ml:!1,Qt=(Ll=(kl=n.layout)==null?void 0:kl.header)==null?void 0:Ll.showIcon,$n=dn||Qt===!1,ot=Ie.headerIconName,gt=(Il=Ie.headerIconSize)!=null?Il:"48px";if(ne){let Y=N.querySelector(".persona-border-b-persona-divider"),ct=Y==null?void 0:Y.querySelector(".persona-flex-col");if($n)ne.style.display="none",Y&&ct&&!Y.contains(ct)&&Y.insertBefore(ct,Y.firstChild);else{if(ne.style.display="",ne.style.height=gt,ne.style.width=gt,Y&&ct&&(Y.contains(ne)?ne.nextSibling!==ct&&(ne.remove(),Y.insertBefore(ne,ct)):Y.insertBefore(ne,ct)),ot){let Ke=parseFloat(gt)||24,ft=ye(ot,Ke*.6,"#ffffff",2);ft?ne.replaceChildren(ft):ne.textContent=(Pl=Ie.agentIconText)!=null?Pl:"\u{1F4AC}"}else if(Ie.iconUrl){let Ke=ne.querySelector("img");if(Ke)Ke.src=Ie.iconUrl,Ke.style.height=gt,Ke.style.width=gt;else{let ft=document.createElement("img");ft.src=Ie.iconUrl,ft.alt="",ft.className="persona-rounded-xl persona-object-cover",ft.style.height=gt,ft.style.width=gt,ne.replaceChildren(ft)}}else{let Ke=ne.querySelector("svg"),ft=ne.querySelector("img");(Ke||ft)&&ne.replaceChildren(),ne.textContent=(Wl=Ie.agentIconText)!=null?Wl:"\u{1F4AC}"}let Mt=ne.querySelector("img");Mt&&(Mt.style.height=gt,Mt.style.width=gt)}}let pn=(Hl=(Rl=n.layout)==null?void 0:Rl.header)==null?void 0:Hl.showTitle,rr=(Dl=(Bl=n.layout)==null?void 0:Bl.header)==null?void 0:Dl.showSubtitle;if(Pe&&(Pe.style.display=pn===!1?"none":""),Fe&&(Fe.style.display=rr===!1?"none":""),$){((Fl=(Nl=n.layout)==null?void 0:Nl.header)==null?void 0:Fl.showCloseButton)===!1?$.style.display="none":$.style.display="";let ct=(Ol=Ie.closeButtonSize)!=null?Ol:"32px",Mt=($l=Ie.closeButtonPlacement)!=null?$l:"inline";$.style.height=ct,$.style.width=ct;let{closeButtonWrapper:Ke}=se,ft=Mt==="top-right",Vt=Ke==null?void 0:Ke.classList.contains("persona-absolute");if(Ke&&ft!==Vt)if(Ke.remove(),ft)Ke.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",N.style.position="relative",N.appendChild(Ke);else{let nt=(jl=(_l=Ie.clearChat)==null?void 0:_l.placement)!=null?jl:"inline",Kt=(ql=(zl=Ie.clearChat)==null?void 0:zl.enabled)!=null?ql:!0;Ke.className=Kt&&nt==="inline"?"":"persona-ml-auto";let mn=N.querySelector(".persona-border-b-persona-divider");mn&&mn.appendChild(Ke)}if($.style.color=Ie.closeButtonColor||fn.actionIconColor,Ie.closeButtonBackgroundColor?($.style.backgroundColor=Ie.closeButtonBackgroundColor,$.classList.remove("hover:persona-bg-gray-100")):($.style.backgroundColor="",$.classList.add("hover:persona-bg-gray-100")),Ie.closeButtonBorderWidth||Ie.closeButtonBorderColor){let nt=Ie.closeButtonBorderWidth||"0px",Kt=Ie.closeButtonBorderColor||"transparent";$.style.border=`${nt} solid ${Kt}`,$.classList.remove("persona-border-none")}else $.style.border="",$.classList.add("persona-border-none");Ie.closeButtonBorderRadius?($.style.borderRadius=Ie.closeButtonBorderRadius,$.classList.remove("persona-rounded-full")):($.style.borderRadius="",$.classList.add("persona-rounded-full")),Ie.closeButtonPaddingX?($.style.paddingLeft=Ie.closeButtonPaddingX,$.style.paddingRight=Ie.closeButtonPaddingX):($.style.paddingLeft="",$.style.paddingRight=""),Ie.closeButtonPaddingY?($.style.paddingTop=Ie.closeButtonPaddingY,$.style.paddingBottom=Ie.closeButtonPaddingY):($.style.paddingTop="",$.style.paddingBottom="");let en=(Ul=Ie.closeButtonIconName)!=null?Ul:"x",_n=(Vl=Ie.closeButtonIconText)!=null?Vl:"\xD7";$.innerHTML="";let sn=ye(en,"20px","currentColor",2);sn?$.appendChild(sn):$.textContent=_n;let Ft=(Jl=Ie.closeButtonTooltipText)!=null?Jl:"Close chat",Sn=(Gl=Ie.closeButtonShowTooltip)!=null?Gl:!0;if($.setAttribute("aria-label",Ft),Ke&&(Ke._cleanupTooltip&&(Ke._cleanupTooltip(),delete Ke._cleanupTooltip),Sn&&Ft)){let nt=null,Kt=()=>{if(nt||!$)return;let Br=$.ownerDocument,Io=Br.body;if(!Io)return;nt=Gn(Br,"div","persona-clear-chat-tooltip"),nt.textContent=Ft;let Po=Gn(Br,"div");Po.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Po);let Dr=$.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(vr),nt.style.left=`${Dr.left+Dr.width/2}px`,nt.style.top=`${Dr.top-8}px`,nt.style.transform="translate(-50%, -100%)",Io.appendChild(nt)},mn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Ke.addEventListener("mouseenter",Kt),Ke.addEventListener("mouseleave",mn),$.addEventListener("focus",Kt),$.addEventListener("blur",mn),Ke._cleanupTooltip=()=>{mn(),Ke&&(Ke.removeEventListener("mouseenter",Kt),Ke.removeEventListener("mouseleave",mn)),$&&($.removeEventListener("focus",Kt),$.removeEventListener("blur",mn))}}}let{clearChatButton:Ye,clearChatButtonWrapper:Tt}=se;if(Ye){let Y=(Yl=Ie.clearChat)!=null?Yl:{},ct=(Kl=Y.enabled)!=null?Kl:!0,Mt=(Zl=(Xl=n.layout)==null?void 0:Xl.header)==null?void 0:Zl.showClearChat,Ke=Mt!==void 0?Mt:ct,ft=(Ql=Y.placement)!=null?Ql:"inline";if(Tt){Tt.style.display=Ke?"":"none";let{closeButtonWrapper:Vt}=se;Vt&&!Vt.classList.contains("persona-absolute")&&(Ke?Vt.classList.remove("persona-ml-auto"):Vt.classList.add("persona-ml-auto"));let en=ft==="top-right",_n=Tt.classList.contains("persona-absolute");if(en!==_n&&Ke){if(Tt.remove(),en)Tt.className="persona-absolute persona-top-4 persona-z-50",Tt.style.right="48px",N.style.position="relative",N.appendChild(Tt);else{Tt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Tt.style.right="";let Ft=N.querySelector(".persona-border-b-persona-divider"),Sn=se.closeButtonWrapper;Ft&&Sn&&Sn.parentElement===Ft?Ft.insertBefore(Tt,Sn):Ft&&Ft.appendChild(Tt)}let sn=se.closeButtonWrapper;sn&&!sn.classList.contains("persona-absolute")&&(en?sn.classList.add("persona-ml-auto"):sn.classList.remove("persona-ml-auto"))}}if(Ke){let Vt=(ec=Y.size)!=null?ec:"32px";Ye.style.height=Vt,Ye.style.width=Vt;let en=(tc=Y.iconName)!=null?tc:"refresh-cw",_n=(nc=Y.iconColor)!=null?nc:"";Ye.style.color=_n||fn.actionIconColor,Ye.innerHTML="";let sn=ye(en,"20px","currentColor",2);if(sn&&Ye.appendChild(sn),Y.backgroundColor?(Ye.style.backgroundColor=Y.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Y.borderWidth||Y.borderColor){let nt=Y.borderWidth||"0px",Kt=Y.borderColor||"transparent";Ye.style.border=`${nt} solid ${Kt}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Y.borderRadius?(Ye.style.borderRadius=Y.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Y.paddingX?(Ye.style.paddingLeft=Y.paddingX,Ye.style.paddingRight=Y.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Y.paddingY?(Ye.style.paddingTop=Y.paddingY,Ye.style.paddingBottom=Y.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let Ft=(rc=Y.tooltipText)!=null?rc:"Clear chat",Sn=(oc=Y.showTooltip)!=null?oc:!0;if(Ye.setAttribute("aria-label",Ft),Tt&&(Tt._cleanupTooltip&&(Tt._cleanupTooltip(),delete Tt._cleanupTooltip),Sn&&Ft)){let nt=null,Kt=()=>{if(nt||!Ye)return;let Br=Ye.ownerDocument,Io=Br.body;if(!Io)return;nt=Gn(Br,"div","persona-clear-chat-tooltip"),nt.textContent=Ft;let Po=Gn(Br,"div");Po.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Po);let Dr=Ye.getBoundingClientRect();nt.style.position="fixed",nt.style.zIndex=String(vr),nt.style.left=`${Dr.left+Dr.width/2}px`,nt.style.top=`${Dr.top-8}px`,nt.style.transform="translate(-50%, -100%)",Io.appendChild(nt)},mn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};Tt.addEventListener("mouseenter",Kt),Tt.addEventListener("mouseleave",mn),Ye.addEventListener("focus",Kt),Ye.addEventListener("blur",mn),Tt._cleanupTooltip=()=>{mn(),Tt&&(Tt.removeEventListener("mouseenter",Kt),Tt.removeEventListener("mouseleave",mn)),Ye&&(Ye.removeEventListener("focus",Kt),Ye.removeEventListener("blur",mn))}}}}let Wr=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Xo],Rr=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Vr.message,Vr.messageAndClick];T=Zo({parsers:Wr,handlers:Rr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),O=Yd(n,T,X),D.updateConfig(n),Mr(ce,D.getMessages(),O),Bn.render(n.suggestionChips,D,te,void 0,n.suggestionChipsConfig),wo(),Kr(D.isStreaming());let us=((sc=n.voiceRecognition)==null?void 0:sc.enabled)===!0,ms=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),gs=((ic=(ac=n.voiceRecognition)==null?void 0:ac.provider)==null?void 0:ic.type)==="runtype";if(us&&(ms||gs))if(!j||!xe){let Y=ls(n.voiceRecognition,n.sendButton);Y&&(j=Y.micButton,xe=Y.micButtonWrapper,At.insertBefore(xe,Lt),j.addEventListener("click",Pr),j.disabled=D.isStreaming())}else{let Y=(lc=n.voiceRecognition)!=null?lc:{},ct=(cc=n.sendButton)!=null?cc:{},Mt=(dc=Y.iconName)!=null?dc:"mic",Ke=(pc=ct.size)!=null?pc:"40px",ft=(uc=Y.iconSize)!=null?uc:Ke,Vt=parseFloat(ft)||24;j.style.width=ft,j.style.height=ft,j.style.minWidth=ft,j.style.minHeight=ft;let en=(gc=(mc=Y.iconColor)!=null?mc:ct.textColor)!=null?gc:"currentColor";j.innerHTML="";let _n=ye(Mt,Vt,en,2);_n?j.appendChild(_n):j.textContent="\u{1F3A4}";let sn=(fc=Y.backgroundColor)!=null?fc:ct.backgroundColor;sn?j.style.backgroundColor=sn:j.style.backgroundColor="",en?j.style.color=en:j.style.color="var(--persona-text, #111827)",Y.borderWidth?(j.style.borderWidth=Y.borderWidth,j.style.borderStyle="solid"):(j.style.borderWidth="",j.style.borderStyle=""),Y.borderColor?j.style.borderColor=Y.borderColor:j.style.borderColor="",Y.paddingX?(j.style.paddingLeft=Y.paddingX,j.style.paddingRight=Y.paddingX):(j.style.paddingLeft="",j.style.paddingRight=""),Y.paddingY?(j.style.paddingTop=Y.paddingY,j.style.paddingBottom=Y.paddingY):(j.style.paddingTop="",j.style.paddingBottom="");let Ft=xe==null?void 0:xe.querySelector(".persona-send-button-tooltip"),Sn=(hc=Y.tooltipText)!=null?hc:"Start voice recognition";if(((yc=Y.showTooltip)!=null?yc:!1)&&Sn)if(Ft)Ft.textContent=Sn,Ft.style.display="";else{let Kt=document.createElement("div");Kt.className="persona-send-button-tooltip",Kt.textContent=Sn,xe==null||xe.insertBefore(Kt,j)}else Ft&&(Ft.style.display="none");xe.style.display="",j.disabled=D.isStreaming()}else j&&xe&&(xe.style.display="none",((xc=(bc=n.voiceRecognition)==null?void 0:bc.provider)==null?void 0:xc.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():wn&&Nn());if(((vc=n.attachments)==null?void 0:vc.enabled)===!0)if(!Ze||!ue){let Y=(Cc=n.attachments)!=null?Cc:{},Mt=(Sc=((wc=n.sendButton)!=null?wc:{}).size)!=null?Sc:"40px";de||(de=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),de.style.display="none",dt.insertBefore(de,te)),qe||(qe=document.createElement("input"),qe.type="file",qe.accept=((Ac=Y.allowedTypes)!=null?Ac:sr).join(","),qe.multiple=((Ec=Y.maxFiles)!=null?Ec:4)>1,qe.style.display="none",qe.setAttribute("aria-label","Attach files"),dt.insertBefore(qe,te)),Ze=h("div","persona-send-button-wrapper"),ue=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ue.type="button",ue.setAttribute("aria-label",(Tc=Y.buttonTooltipText)!=null?Tc:"Attach file");let Ke=(Mc=Y.buttonIconName)!=null?Mc:"paperclip",ft=Mt,Vt=parseFloat(ft)||40,en=Math.round(Vt*.6);ue.style.width=ft,ue.style.height=ft,ue.style.minWidth=ft,ue.style.minHeight=ft,ue.style.fontSize="18px",ue.style.lineHeight="1",ue.style.backgroundColor="transparent",ue.style.color="var(--persona-primary, #111827)",ue.style.border="none",ue.style.borderRadius="6px",ue.style.transition="background-color 0.15s ease",ue.addEventListener("mouseenter",()=>{ue.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ue.addEventListener("mouseleave",()=>{ue.style.backgroundColor="transparent"});let _n=ye(Ke,en,"currentColor",1.5);_n?ue.appendChild(_n):ue.textContent="\u{1F4CE}",ue.addEventListener("click",Sn=>{Sn.preventDefault(),qe==null||qe.click()}),Ze.appendChild(ue);let sn=(kc=Y.buttonTooltipText)!=null?kc:"Attach file",Ft=h("div","persona-send-button-tooltip");Ft.textContent=sn,Ze.appendChild(Ft),mt.append(Ze),!je&&qe&&de&&(je=zr.fromConfig(Y),je.setPreviewsContainer(de),qe.addEventListener("change",async()=>{je&&(qe!=null&&qe.files)&&(await je.handleFileSelect(qe.files),qe.value="")})),N.querySelector(".persona-attachment-drop-overlay")||N.appendChild(Kd(Y.dropOverlay))}else{Ze.style.display="";let Y=(Lc=n.attachments)!=null?Lc:{};qe&&(qe.accept=((Ic=Y.allowedTypes)!=null?Ic:sr).join(","),qe.multiple=((Pc=Y.maxFiles)!=null?Pc:4)>1),je&&je.updateConfig({allowedTypes:Y.allowedTypes,maxFileSize:Y.maxFileSize,maxFiles:Y.maxFiles})}else Ze&&(Ze.style.display="none"),je&&je.clearAttachments(),(Wc=N.querySelector(".persona-attachment-drop-overlay"))==null||Wc.remove();let jt=(Rc=n.sendButton)!=null?Rc:{},fs=(Hc=jt.useIcon)!=null?Hc:!1,Mo=(Bc=jt.iconText)!=null?Bc:"\u2191",un=jt.iconName,In=(Dc=jt.tooltipText)!=null?Dc:"Send message",to=(Nc=jt.showTooltip)!=null?Nc:!1,ko=(Fc=jt.size)!=null?Fc:"40px",hs=jt.backgroundColor,Hr=jt.textColor;if(fs){if(pe.style.width=ko,pe.style.height=ko,pe.style.minWidth=ko,pe.style.minHeight=ko,pe.style.fontSize="18px",pe.style.lineHeight="1",pe.innerHTML="",Hr?pe.style.color=Hr:pe.style.color="var(--persona-button-primary-fg, #ffffff)",un){let Y=parseFloat(ko)||24,ct=(Hr==null?void 0:Hr.trim())||"currentColor",Mt=ye(un,Y,ct,2);Mt?pe.appendChild(Mt):pe.textContent=Mo}else pe.textContent=Mo;pe.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",hs?(pe.style.backgroundColor=hs,pe.classList.remove("persona-bg-persona-primary")):(pe.style.backgroundColor="",pe.classList.add("persona-bg-persona-primary"))}else pe.textContent=($c=(Oc=n.copy)==null?void 0:Oc.sendButtonLabel)!=null?$c:"Send",pe.style.width="",pe.style.height="",pe.style.minWidth="",pe.style.minHeight="",pe.style.fontSize="",pe.style.lineHeight="",pe.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",hs?(pe.style.backgroundColor=hs,pe.classList.remove("persona-bg-persona-accent")):pe.classList.add("persona-bg-persona-accent"),Hr?pe.style.color=Hr:pe.classList.add("persona-text-white");jt.borderWidth?(pe.style.borderWidth=jt.borderWidth,pe.style.borderStyle="solid"):(pe.style.borderWidth="",pe.style.borderStyle=""),jt.borderColor?pe.style.borderColor=jt.borderColor:pe.style.borderColor="",jt.paddingX?(pe.style.paddingLeft=jt.paddingX,pe.style.paddingRight=jt.paddingX):(pe.style.paddingLeft="",pe.style.paddingRight=""),jt.paddingY?(pe.style.paddingTop=jt.paddingY,pe.style.paddingBottom=jt.paddingY):(pe.style.paddingTop="",pe.style.paddingBottom="");let Lo=Lt==null?void 0:Lt.querySelector(".persona-send-button-tooltip");if(to&&In)if(Lo)Lo.textContent=In,Lo.style.display="";else{let Y=document.createElement("div");Y.className="persona-send-button-tooltip",Y.textContent=In,Lt==null||Lt.insertBefore(Y,pe)}else Lo&&(Lo.style.display="none");let ys=(_c=n.layout)==null?void 0:_c.contentMaxWidth;ys?(ce.style.maxWidth=ys,ce.style.marginLeft="auto",ce.style.marginRight="auto",ce.style.width="100%",dt&&(dt.style.maxWidth=ys,dt.style.marginLeft="auto",dt.style.marginRight="auto"),fe&&(fe.style.maxWidth=ys,fe.style.marginLeft="auto",fe.style.marginRight="auto")):(ce.style.maxWidth="",ce.style.marginLeft="",ce.style.marginRight="",ce.style.width="",dt&&(dt.style.maxWidth="",dt.style.marginLeft="",dt.style.marginRight=""),fe&&(fe.style.maxWidth="",fe.style.marginLeft="",fe.style.marginRight=""));let br=(jc=n.statusIndicator)!=null?jc:{},Bp=(zc=br.visible)!=null?zc:!0;if(Wt.style.display=Bp?"":"none",D){let Y=D.getStatus();st(Wt,(Mt=>{var Ke,ft,Vt,en;return Mt==="idle"?(Ke=br.idleText)!=null?Ke:tn.idle:Mt==="connecting"?(ft=br.connectingText)!=null?ft:tn.connecting:Mt==="connected"?(Vt=br.connectedText)!=null?Vt:tn.connected:Mt==="error"?(en=br.errorText)!=null?en:tn.error:tn[Mt]})(Y),br,Y)}Wt.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Dp=br.align==="left"?"persona-text-left":br.align==="center"?"persona-text-center":"persona-text-right";Wt.classList.add(Dp)},open(){C&&Pt(!0,"api")},close(){C&&Pt(!1,"api")},toggle(){C&&Pt(!E,"api")},clearChat(){nn=!1,D.clearMessages(),Mn.clear(),fr();try{localStorage.removeItem(ho),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${ho}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==ho)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},T.syncFromMetadata(),ie==null||ie.clear(),Z==null||Z.update()},setMessage(l){return!te||D.isStreaming()?!1:(!E&&C&&Pt(!0,"system"),te.value=l,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let m=(l==null?void 0:l.trim())||te.value.trim();return m?(!E&&C&&Pt(!0,"system"),te.value="",te.style.height="auto",D.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return D.isStreaming()?!1:((y=(m=n.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!E&&C&&Pt(!0,"system"),et.manuallyDeactivated=!1,cn(),D.toggleVoice().then(()=>{et.active=D.isVoiceActive(),kn("user"),D.isVoiceActive()&&yr()})),!0):wn?!0:To()?(!E&&C&&Pt(!0,"system"),et.manuallyDeactivated=!1,cn(),Lr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{et.active=!1,et.manuallyDeactivated=!0,cn(),kn("user"),Fn()}),!0):!1:wn?(et.manuallyDeactivated=!0,cn(),Nn("user"),!0):!1},injectMessage(l){return!E&&C&&Pt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!E&&C&&Pt(!0,"system");let m=D.injectAssistantMessage(l);return K&&(K=!1,Q&&(clearTimeout(Q),Q=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),m},injectUserMessage(l){return!E&&C&&Pt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!E&&C&&Pt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!E&&C&&Pt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!E&&C&&Pt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,m){return D.connectStream(l,m)},__pushEventStreamEvent(l){ie&&ie.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!ae||!ie||Kn()},hideEventStream(){me&&Rn()},isEventStreamVisible(){return me},showArtifacts(){Wn(n)&&(nn=!1,bn(),it==null||it.setMobileOpen(!0))},hideArtifacts(){Wn(n)&&(nn=!0,bn())},upsertArtifact(l){return Wn(n)?(nn=!1,D.upsertArtifact(l)):null},selectArtifact(l){Wn(n)&&D.selectArtifact(l)},clearArtifacts(){Wn(n)&&D.clearArtifacts()},focusInput(){return C&&!E||!te?!1:(te.focus(),!0)},async resolveApproval(l,m){let A=D.getMessages().find(I=>{var R;return I.variant==="approval"&&((R=I.approval)==null?void 0:R.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,m)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return C&&E},isVoiceActive(){return et.active},getState(){return{open:C&&E,launcherEnabled:C,voiceActive:et.active,streaming:D.isStreaming()}},showCSATFeedback(l){!E&&C&&Pt(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=Zs({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitCSATFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!E&&C&&Pt(!0,"system");let m=ce.querySelector(".persona-feedback-container");m&&m.remove();let y=Qs({onSubmit:async(A,I)=>{var R;D.isClientTokenMode()&&await D.submitNPSFeedback(A,I),(R=l==null?void 0:l.onSubmit)==null||R.call(l,A,I)},onDismiss:l==null?void 0:l.onDismiss,...l});ce.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return D.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return D.submitNPSFeedback(l,m)},destroy(){Jn!=null&&(clearInterval(Jn),Jn=null),Ct.forEach(l=>l()),z.remove(),b==null||b.destroy(),k==null||k.remove(),vn&&$.removeEventListener("click",vn)}};if((((Ni=t==null?void 0:t.debugTools)!=null?Ni:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:qt,getMessages:qt.getMessages,getStatus:qt.getStatus,getMetadata:qt.getPersistentMetadata,updateMetadata:qt.updatePersistentMetadata,clearHistory:()=>qt.clearChat(),setVoiceActive:y=>y?qt.startVoiceRecognition():qt.stopVoiceRecognition()};window.AgentWidgetBrowser=m,Ct.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.focusInput()};if(window.addEventListener("persona:focusInput",m),Ct.push(()=>{window.removeEventListener("persona:focusInput",m)}),ae){let G=ve=>{let Se=ve.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&qt.showEventStream()},F=ve=>{let Se=ve.detail;(!(Se!=null&&Se.instanceId)||Se.instanceId===l)&&qt.hideEventStream()};window.addEventListener("persona:showEventStream",G),window.addEventListener("persona:hideEventStream",F),Ct.push(()=>{window.removeEventListener("persona:showEventStream",G),window.removeEventListener("persona:hideEventStream",F)})}let y=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.showArtifacts()},A=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.hideArtifacts()},I=G=>{let F=G.detail;F!=null&&F.instanceId&&F.instanceId!==l||F!=null&&F.artifact&&qt.upsertArtifact(F.artifact)},R=G=>{let F=G.detail;F!=null&&F.instanceId&&F.instanceId!==l||typeof(F==null?void 0:F.id)=="string"&&qt.selectArtifact(F.id)},B=G=>{let F=G.detail;(!(F!=null&&F.instanceId)||F.instanceId===l)&&qt.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",I),window.addEventListener("persona:selectArtifact",R),window.addEventListener("persona:clearArtifacts",B),Ct.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",I),window.removeEventListener("persona:selectArtifact",R),window.removeEventListener("persona:clearArtifacts",B)})}let Ln=Qu(n.persistState);if(Ln&&C){let l=em(Ln.storage),m=`${Ln.keyPrefix}widget-open`,y=`${Ln.keyPrefix}widget-voice`,A=`${Ln.keyPrefix}widget-voice-mode`;if(l){let I=((Fi=Ln.persist)==null?void 0:Fi.openState)&&l.getItem(m)==="true",R=((Oi=Ln.persist)==null?void 0:Oi.voiceState)&&l.getItem(y)==="true",B=(($i=Ln.persist)==null?void 0:$i.voiceState)&&l.getItem(A)==="true";if(I&&setTimeout(()=>{qt.open(),setTimeout(()=>{var G;if(R||B)qt.startVoiceRecognition();else if((G=Ln.persist)!=null&&G.focusInput){let F=e.querySelector("textarea");F&&F.focus()}},100)},0),(_i=Ln.persist)!=null&&_i.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(ji=Ln.persist)!=null&&ji.voiceState&&(o.on("voice:state",G=>{l.setItem(y,G.active?"true":"false")}),o.on("user:message",G=>{l.setItem(A,G.viaVoice?"true":"false")})),Ln.clearOnChatClear){let G=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(A)},F=()=>G();window.addEventListener("persona:clear-chat",F),Ct.push(()=>{window.removeEventListener("persona:clear-chat",F)})}}}return c&&C&&setTimeout(()=>{qt.open()},0),qt};var tm=(e,r)=>{let t=e.trim(),n=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(n)return Math.max(0,parseFloat(n[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,r*parseFloat(s[1])/100):420},Xd=(e,r)=>{var n,s;let t=(s=(n=r==null?void 0:r.launcher)==null?void 0:n.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},_a=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Zd=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",_a(e)},Fa=e=>{e.style.transition=""},Oa=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},$a=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},na=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},nm=(e,r,t,n,s)=>{s?t.parentElement!==r&&(e.replaceChildren(),r.replaceChildren(t,n),e.appendChild(r)):t.parentElement===r&&(r.replaceChildren(),e.appendChild(t),e.appendChild(n))},rm=(e,r,t,n,s,o)=>{let a=o?r:e;s==="left"?a.firstElementChild!==n&&a.replaceChildren(n,t):a.lastElementChild!==n&&a.replaceChildren(t,n)},Qd=(e,r,t,n,s,o,a)=>{var x,T,C,S,M,H;let i=Pn(o),u=i.reveal==="push";nm(e,r,t,n,u),rm(e,r,t,n,i.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(T=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?T:!0,d=(S=(C=o==null?void 0:o.launcher)==null?void 0:C.mobileBreakpoint)!=null?S:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Oa(r),Fa(n),Zd(n),$a(t),na(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((H=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?H:gn),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",u&&(r.style.display="flex",r.style.flexDirection="column",r.style.width="100%",r.style.height="100%",r.style.minHeight="0",r.style.minWidth="0",r.style.flex="1 1 auto",r.style.alignItems="stretch",r.style.transform="none",r.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Zd(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Oa(r),Fa(n),$a(t),na(s,n);let w=i.animate?"transform 180ms ease":"none",L=i.side==="right"?"translateX(100%)":"translateX(-100%)",W=a?"translateX(0)":L;n.style.display="flex",n.style.flexDirection="column",n.style.flex="none",n.style.position="absolute",n.style.top="0",n.style.bottom="0",n.style.width=i.width,n.style.maxWidth=i.width,n.style.minWidth=i.width,n.style.minHeight="0",n.style.overflow="hidden",n.style.transition=w,n.style.transform=W,n.style.pointerEvents=a?"auto":"none",n.style.zIndex="2",i.side==="right"?(n.style.right="0",n.style.left=""):(n.style.left="0",n.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Fa(n),_a(n),na(s,n);let w=tm(i.width,e.clientWidth),L=Math.max(0,e.clientWidth),W=i.animate?"transform 180ms ease":"none",E=i.side==="right"?a?`translateX(-${w}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${w}px)`;r.style.display="flex",r.style.flexDirection="row",r.style.flex="0 0 auto",r.style.minHeight="0",r.style.minWidth="0",r.style.alignItems="stretch",r.style.height="100%",r.style.width=`${L+w}px`,r.style.transition=W,r.style.transform=E,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${L}px`,t.style.maxWidth=`${L}px`,t.style.minWidth=`${L}px`,n.style.display="flex",n.style.flexDirection="column",n.style.flex="0 0 auto",n.style.flexShrink="0",n.style.width=i.width,n.style.minWidth=i.width,n.style.maxWidth=i.width,n.style.position="relative",n.style.overflow="hidden",n.style.transition="none",n.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Oa(r),_a(n),$a(t),na(s,n);let w=i.reveal==="emerge";w?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let L=a?i.width:"0px",W=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",E=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${L}`,n.style.width=L,n.style.maxWidth=L,n.style.minWidth=L,n.style.minHeight="0",n.style.position="relative",n.style.overflow=w||E?"hidden":"visible",n.style.transition=W,w&&(n.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},om=(e,r)=>{let t=e.ownerDocument.createElement("div");return Xd(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){Xd(t,n)},destroy(){t.remove()}}},sm=(e,r)=>{var M,H,w,L;let{ownerDocument:t}=e,n=e.parentElement;if(!n)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(H=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||H?(L=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?L:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),n.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),Pn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Qd(a,i,u,c,p,r,d)}),f.observe(a))},T=()=>{Qd(a,i,u,c,p,r,d),x()},C=a.ownerDocument.defaultView,S=()=>{T()};return C==null||C.addEventListener("resize",S),Pn(r).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),T(),{mode:"docked",host:p,shell:a,syncWidgetState(W){let E=W.launcherEnabled?W.open:!0;d!==E&&(d=E,T())},updateConfig(W){var E,K;r=W,((K=(E=r==null?void 0:r.launcher)==null?void 0:E.enabled)!=null?K:!0)===!1&&(d=!0),T()},destroy(){C==null||C.removeEventListener("resize",S),g(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Qo=(e,r)=>Jt(r)?sm(e,r):om(e,r);var ja={},am=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let r=document.querySelector(e);if(!r)throw new Error(`Chat widget target "${e}" was not found`);return r}return e},im=()=>{try{if(typeof ja!="undefined"&&ja.url)return new URL("../widget.css",ja.url).href}catch{}return null},ep=(e,r)=>{let t=im(),n=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=r.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=r.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else n();else if(!r.head.querySelector("link[data-persona]")&&t){let o=r.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),r.head.appendChild(o)}},za=e=>{var C;let r=am(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Qo(r,s),a,i=[],u=(S,M)=>{var W,E;let w=!((E=(W=M==null?void 0:M.launcher)==null?void 0:W.enabled)!=null?E:!0)||Jt(M),L=n.createElement("div");if(L.setAttribute("data-persona-root","true"),w&&(L.style.height="100%",L.style.display="flex",L.style.flexDirection="column",L.style.flex="1",L.style.minHeight="0"),t){let K=S.attachShadow({mode:"open"});K.appendChild(L),ep(K,n)}else S.appendChild(L),ep(S,n);return r.id&&L.setAttribute("data-persona-instance",r.id),L},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(S=>S()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let S=u(o.host,s);a=ta(S,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(S=>S()),i=[],a.destroy()};d(),(C=e.onReady)==null||C.call(e);let g=S=>{f(),o.destroy(),o=Qo(r,S),s=S,d()},x={update(S){var L,W,E,K,Q,X;let M={...s,...S,launcher:{...(L=s==null?void 0:s.launcher)!=null?L:{},...(W=S==null?void 0:S.launcher)!=null?W:{},dock:{...(K=(E=s==null?void 0:s.launcher)==null?void 0:E.dock)!=null?K:{},...(X=(Q=S==null?void 0:S.launcher)==null?void 0:Q.dock)!=null?X:{}}}},H=Jt(s),w=Jt(M);if(H!==w){g(M);return}s=M,o.updateConfig(s),a.update(S),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},T=new Proxy(x,{get(S,M,H){if(M==="host")return o.host;if(M in S)return Reflect.get(S,M,H);let w=a[M];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=T),T};var sp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),lm=new Set(["button","a","input","select","textarea","details","summary"]),cm=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),qa=/\b(product|card|item|listing|result)\b/i,Va=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,dm=3e3,pm=100;function ap(e){let r=typeof e.className=="string"?e.className:"";if(qa.test(r)||e.id&&qa.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&qa.test(n.value))return!0}return!1}function ip(e){var r;return Va.test(((r=e.textContent)!=null?r:"").trim())}function lp(e){var t;let r=e.querySelectorAll("a[href]");for(let n=0;n<r.length;n++){let s=(t=r[n].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function um(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function tp(e){let r=e.match(Va);return r?r[0]:null}function np(e){var n,s,o;let r=(n=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?n:e.querySelector("a[href]");if(r&&((s=r.textContent)!=null&&s.trim())){let a=r.getAttribute("href");return{title:r.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function mm(e){let r=[],t=n=>{let s=n.trim();s&&!r.includes(s)&&r.push(s)};return e.querySelectorAll("button").forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(n=>{var s;return t((s=n.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(n=>{var s;t((s=n.value)!=null?s:"")}),r.slice(0,6)}var gm="commerce-card",fm="result-card";function rp(e){return!ap(e)||!ip(e)||!lp(e)&&!um(e)?0:5200}function op(e){var n;return!ap(e)||ip(e)||!lp(e)||((n=e.textContent)!=null?n:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var Ja=[{id:gm,scoreElement(e){return rp(e)},shouldSuppressDescendant(e,r,t){if(r===e||!e.contains(r))return!1;if(t.interactivity==="static"){let n=t.text.trim();return!!(n.length===0||Va.test(n)&&n.length<32)}return!0},formatSummary(e,r){var u,c,p;if(rp(e)===0)return null;let{title:t,href:n}=np(e),s=(p=(c=tp(((u=e.textContent)!=null?u:"").trim()))!=null?c:tp(r.text))!=null?p:"",o=mm(e);return[n&&t?`[${t}](${n})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||r.text.trim().slice(0,120),`selector: ${r.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
100
|
-
`)}},{id:
|
|
101
|
-
`)}}];function
|
|
100
|
+
`}if(!S&&!l){let bn="max-height: -moz-available !important; max-height: stretch !important;",on=m?"":"padding-top: 1.25em !important;",On=m?"":`z-index: ${(po=(zo=r.launcher)==null?void 0:zo.zIndex)!=null?po:vn} !important;`;k.style.cssText+=bn+on+On}Tt()};Zn(),kr(e,r),ca(e,r),da(e,r);let wt=[],$t=null,_t=null;wt.push(()=>{$t==null||$t(),$t=null,_t==null||_t(),_t=null}),Sn&&wt.push(()=>{Sn==null||Sn.disconnect(),Sn=null}),wt.push(()=>{pn==null||pn(),pn=null,rr(),Mt&&(Mt.remove(),Mt=null),gt==null||gt.element.style.removeProperty("width"),gt==null||gt.element.style.removeProperty("maxWidth")}),pe&&wt.push(()=>{X!==null&&(cancelAnimationFrame(X),X=null),Q==null||Q.destroy(),Q=null,de==null||de.destroy(),de=null,Ee=null});let Tn=null,vr=()=>{Tn&&(Tn(),Tn=null),r.colorScheme==="auto"&&(Tn=ta(()=>{kr(e,r)}))};vr(),wt.push(()=>{Tn&&(Tn(),Tn=null)});let Bn=(zi=r.features)==null?void 0:zi.streamAnimation;if(Bn!=null&&Bn.type&&Bn.type!=="none"){let l=sa(Bn.type,Bn.plugins);l&&(Kd(l,e),wt.push(()=>Jd(e)))}let zn=tp(xe),Mn=null,O,qn=!1,Dn=Bd(),Cr=0,ce=na(),un=0,kn=null,or=!1,Hr=!1,ys=4,To=24,bs=80,oo=new Map,ct={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Mo=(Vi=(qi=r.voiceRecognition)==null?void 0:qi.autoResume)!=null?Vi:!1,Nn=l=>{o.emit("voice:state",{active:ct.active,source:l,timestamp:Date.now()})},fn=()=>{f(l=>({...l,voiceState:{active:ct.active,timestamp:Date.now(),manuallyDeactivated:ct.manuallyDeactivated}}))},xs=()=>{var S,M;if(((S=r.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=ai(i.voiceState),m=!!l.active,y=Number((M=l.timestamp)!=null?M:0);ct.manuallyDeactivated=!!l.manuallyDeactivated,m&&Date.now()-y<Lm&&setTimeout(()=>{var B,F;ct.active||(ct.manuallyDeactivated=!1,((F=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:F.type)==="runtype"?O.toggleVoice().then(()=>{ct.active=O.isVoiceActive(),Nn("restore"),O.isVoiceActive()&&Ar()}):Fr("restore"))},1e3)},vs=()=>O?hp(O.getMessages()).filter(l=>!l.__skipPersist):[];function ko(l){if(!(a!=null&&a.save))return;let y={messages:l?hp(l):O?vs():[],metadata:i};try{let S=a.save(y);S instanceof Promise&&S.catch(M=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",M)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let sr=null,Cs=()=>k.querySelector("#persona-scroll-container")||q,Br=()=>{sr!==null&&(cancelAnimationFrame(sr),sr=null),or=!1},Lo=()=>{kn!==null&&(cancelAnimationFrame(kn),kn=null),Hr=!1,Br()},ar=()=>{if(!Zt()||he){mt.parentNode&&mt.remove(),mt.style.display="none";return}mt.parentNode!==D&&D.appendChild(mt),Ce();let l=rs(q)>0;mt.style.display=ce.isFollowing()||!l?"none":""},Io=()=>{ce.pause()&&(Lo(),ar())},wr=()=>{ce.resume(),ar()},Sr=(l=!1)=>{ce.isFollowing()&&(!l&&!qn||(kn!==null&&(cancelAnimationFrame(kn),kn=null),Hr=!0,kn=requestAnimationFrame(()=>{kn=null,Hr=!1,ce.isFollowing()&&ws(Cs(),l?220:140)})))},ws=(l,m=500)=>{let y=l.scrollTop,S=rs(l),M=S-y;if(Math.abs(M)<1){un=l.scrollTop;return}if(Math.abs(M)>=bs){Br(),or=!0,l.scrollTop=S,un=l.scrollTop,or=!1;return}Br();let B=performance.now();or=!0;let F=_=>1-Math.pow(1-_,3),K=_=>{if(!ce.isFollowing()){Br();return}let Se=rs(l);Se!==S&&(S=Se,M=S-y);let ke=_-B,Pe=Math.min(ke/m,1),We=F(Pe),Fe=y+M*We;l.scrollTop=Fe,un=l.scrollTop,Pe<1?sr=requestAnimationFrame(K):(l.scrollTop=S,un=l.scrollTop,sr=null,or=!1)};sr=requestAnimationFrame(K)},Ss=l=>{let m=new Map;l.forEach(y=>{let S=oo.get(y.id);m.set(y.id,{streaming:y.streaming,role:y.role}),!S&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(S!=null&&S.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(S?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),oo.clear(),m.forEach((y,S)=>{oo.set(S,y)})},Dr=(l,m,y)=>{var Pe,We,Fe,Ge,ft,nt;let S=document.createElement("div"),B=(()=>{var $e;let z=s.find(qe=>qe.renderLoadingIndicator);if(z!=null&&z.renderLoadingIndicator)return z.renderLoadingIndicator;if(($e=r.loadingIndicator)!=null&&$e.render)return r.loadingIndicator.render})(),F=(z,$e)=>$e==null?!1:typeof $e=="string"?(z.textContent=$e,!0):(z.appendChild($e),!0),K=new Set;if(m.forEach(z=>{var Vt,rn;K.add(z.id);let $e=Hd(z,Cr),qe=Dd(Dn,z.id,$e);if(qe){S.appendChild(qe.cloneNode(!0));return}let Le=null,Ue=s.find(Be=>!!(z.variant==="reasoning"&&Be.renderReasoning||z.variant==="tool"&&Be.renderToolCall||z.variant==="approval"&&Be.renderApproval||!z.variant&&Be.renderMessage)),Tt=(Vt=r.layout)==null?void 0:Vt.messages;if(Ue)if(z.variant==="reasoning"&&z.reasoning&&Ue.renderReasoning){if(!ie)return;Le=Ue.renderReasoning({message:z,defaultRenderer:()=>Za(z,r),config:r})}else if(z.variant==="tool"&&z.toolCall&&Ue.renderToolCall){if(!be)return;Le=Ue.renderToolCall({message:z,defaultRenderer:()=>Qa(z,r),config:r})}else if(z.variant==="approval"&&z.approval&&Ue.renderApproval){if(r.approval===!1)return;Le=Ue.renderApproval({message:z,defaultRenderer:()=>ei(z,r),config:r})}else Ue.renderMessage&&(Le=Ue.renderMessage({message:z,defaultRenderer:()=>{let Be=vo(z,y,Tt,r.messageActions,ue,{loadingIndicatorRenderer:B,widgetConfig:r});return z.role!=="user"&&ri(Be,z,r,O),Be},config:r}));if(!Le&&z.role==="assistant"&&!z.variant&&r.enableComponentStreaming!==!1&&ga(z)){let hn=fa(z);if(hn){let an=ma(hn,{config:r,message:z,transform:y});if(an)if(r.wrapComponentDirectiveInBubble!==!1){let ut=document.createElement("div");if(ut.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),ut.id=`bubble-${z.id}`,ut.setAttribute("data-message-id",z.id),z.content&&z.content.trim()){let vt=document.createElement("div");vt.className="persona-mb-3 persona-text-sm persona-leading-relaxed",vt.innerHTML=y({text:z.content,message:z,streaming:!!z.streaming,raw:z.rawContent}),ut.appendChild(vt)}ut.appendChild(an),Le=ut}else{let ut=document.createElement("div");if(ut.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",ut.id=`bubble-${z.id}`,ut.setAttribute("data-message-id",z.id),ut.setAttribute("data-persona-component-directive","true"),z.content&&z.content.trim()){let vt=document.createElement("div");vt.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",vt.innerHTML=y({text:z.content,message:z,streaming:!!z.streaming,raw:z.rawContent}),ut.appendChild(vt)}ut.appendChild(an),Le=ut}}}if(!Le)if(z.variant==="reasoning"&&z.reasoning){if(!ie)return;Le=Za(z,r)}else if(z.variant==="tool"&&z.toolCall){if(!be)return;Le=Qa(z,r)}else if(z.variant==="approval"&&z.approval){if(r.approval===!1)return;Le=ei(z,r)}else{let Be=(rn=r.layout)==null?void 0:rn.messages;Be!=null&&Be.renderUserMessage&&z.role==="user"?Le=Be.renderUserMessage({message:z,config:r,streaming:!!z.streaming}):Be!=null&&Be.renderAssistantMessage&&z.role==="assistant"?Le=Be.renderAssistantMessage({message:z,config:r,streaming:!!z.streaming}):Le=vo(z,y,Be,r.messageActions,ue,{loadingIndicatorRenderer:B,widgetConfig:r}),z.role!=="user"&&Le&&ri(Le,z,r,O)}let xt=document.createElement("div");xt.className="persona-flex",xt.id=`wrapper-${z.id}`,xt.setAttribute("data-wrapper-id",z.id),z.role==="user"&&xt.classList.add("persona-justify-end"),(Le==null?void 0:Le.getAttribute("data-persona-component-directive"))==="true"&&xt.classList.add("persona-w-full"),xt.appendChild(Le),Nd(Dn,z.id,$e,xt),S.appendChild(xt)}),(We=(Pe=r.features)==null?void 0:Pe.toolCallDisplay)!=null&&We.grouped){let z=[],$e=[];m.forEach(qe=>{if(qe.variant==="tool"&&qe.toolCall&&be){$e.push(qe);return}$e.length>1&&z.push($e),$e=[]}),$e.length>1&&z.push($e),z.forEach((qe,Le)=>{var an,Kn;let Ue=qe.map(ut=>Array.from(S.children).find(vt=>vt instanceof HTMLElement&&vt.getAttribute("data-wrapper-id")===ut.id)).filter(ut=>!!ut);if(Ue.length<2)return;let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id=`wrapper-tool-group-${Le}-${qe[0].id}`,Tt.setAttribute("data-wrapper-id",`tool-group-${Le}-${qe[0].id}`);let xt=document.createElement("div");xt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",xt.setAttribute("data-persona-tool-group","true");let Vt=document.createElement("div");Vt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let rn=`Called ${qe.length} tools`,Be=(Kn=(an=r.toolCall)==null?void 0:an.renderGroupedSummary)==null?void 0:Kn.call(an,{messages:qe,toolCalls:qe.map(ut=>ut.toolCall).filter(ut=>!!ut),defaultSummary:rn,config:r});F(Vt,Be)||(Vt.textContent=rn);let hn=document.createElement("div");hn.className="persona-tool-group-stack persona-flex persona-flex-col",xt.append(Vt,hn),Tt.appendChild(xt),Ue[0].before(Tt),Ue.forEach((ut,vt)=>{let yn=document.createElement("div");yn.className="persona-tool-group-item persona-relative",yn.setAttribute("data-persona-tool-group-item","true"),vt<Ue.length-1&&yn.setAttribute("data-persona-tool-group-connector","true"),yn.appendChild(ut),hn.appendChild(yn)})})}Fd(Dn,K);let _=m.some(z=>z.role==="assistant"&&z.streaming),Se=m[m.length-1],ke=(Se==null?void 0:Se.role)==="assistant"&&!Se.streaming&&Se.variant!=="approval";if(qn&&m.some(z=>z.role==="user")&&!_&&!ke){let z={config:r,streaming:!0,location:"standalone",defaultRenderer:eo},$e=s.find(Le=>Le.renderLoadingIndicator),qe=null;if($e!=null&&$e.renderLoadingIndicator&&(qe=$e.renderLoadingIndicator(z)),qe===null&&((Fe=r.loadingIndicator)!=null&&Fe.render)&&(qe=r.loadingIndicator.render(z)),qe===null&&(qe=eo()),qe){let Le=document.createElement("div"),Ue=((Ge=r.loadingIndicator)==null?void 0:Ge.showBubble)!==!1;Le.className=Ue?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Le.setAttribute("data-typing-indicator","true"),Le.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",Le.appendChild(qe);let Tt=document.createElement("div");Tt.className="persona-flex",Tt.id="wrapper-typing-indicator",Tt.setAttribute("data-wrapper-id","typing-indicator"),Tt.appendChild(Le),S.appendChild(Tt)}}if(!qn&&m.length>0){let z=m[m.length-1],$e={config:r,lastMessage:z,messageCount:m.length},qe=s.find(Ue=>Ue.renderIdleIndicator),Le=null;if(qe!=null&&qe.renderIdleIndicator&&(Le=qe.renderIdleIndicator($e)),Le===null&&((ft=r.loadingIndicator)!=null&&ft.renderIdle)&&(Le=r.loadingIndicator.renderIdle($e)),Le){let Ue=document.createElement("div"),Tt=((nt=r.loadingIndicator)==null?void 0:nt.showBubble)!==!1;Ue.className=Tt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ue.setAttribute("data-idle-indicator","true"),Ue.appendChild(Le);let xt=document.createElement("div");xt.className="persona-flex",xt.id="wrapper-idle-indicator",xt.setAttribute("data-wrapper-id","idle-indicator"),xt.appendChild(Ue),S.appendChild(xt)}}Rd(l,S)},Nr=()=>{var _,Se,ke,Pe,We;if(!v)return;let l=Jt(r),m=(_=e.ownerDocument.defaultView)!=null?_:window,y=(ke=(Se=r.launcher)==null?void 0:Se.mobileBreakpoint)!=null?ke:640,S=(We=(Pe=r.launcher)==null?void 0:Pe.mobileFullscreen)!=null?We:!0,M=m.innerWidth<=y,B=S&&M&&v,F=$n(r).reveal;P?(k.style.removeProperty("display"),k.style.display=l?"flex":"",k.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-95","persona-opacity-0"),V.classList.add("persona-scale-100","persona-opacity-100"),Ft?Ft.element.style.display="none":Ot&&(Ot.style.display="none")):(l?l&&(F==="overlay"||F==="push")&&!B?(k.style.removeProperty("display"),k.style.display="flex",k.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(k.style.setProperty("display","none","important"),k.classList.remove("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(k.style.display="",k.classList.add("persona-pointer-events-none","persona-opacity-0"),V.classList.remove("persona-scale-100","persona-opacity-100"),V.classList.add("persona-scale-95","persona-opacity-0")),Ft?Ft.element.style.display=l?"none":"":Ot&&(Ot.style.display=l?"none":""))},Nt=(l,m="user")=>{var B,F;if(!v||P===l)return;let y=P;P=l,Nr();let S=(()=>{var Fe,Ge,ft,nt,z,$e,qe;let K=(Ge=(Fe=r.launcher)==null?void 0:Fe.sidebarMode)!=null?Ge:!1,_=(ft=e.ownerDocument.defaultView)!=null?ft:window,Se=(z=(nt=r.launcher)==null?void 0:nt.mobileFullscreen)!=null?z:!0,ke=(qe=($e=r.launcher)==null?void 0:$e.mobileBreakpoint)!=null?qe:640,Pe=_.innerWidth<=ke,We=Jt(r)&&Se&&Pe;return K||Se&&Pe&&v||We})();if(P&&S){if(!$t){let K=e.getRootNode(),_=K instanceof ShadowRoot?K.host:e.closest(".persona-host");_&&($t=Va(_,(F=(B=r.launcher)==null?void 0:B.zIndex)!=null?F:vn))}_t||(_t=Ua(e.ownerDocument))}else P||($t==null||$t(),$t=null,_t==null||_t(),_t=null);P&&(Er(),Sr(!0));let M={open:P,source:m,timestamp:Date.now()};P&&!y?o.emit("widget:opened",M):!P&&y&&o.emit("widget:closed",M),o.emit("widget:state",{open:P,launcherEnabled:v,voiceActive:ct.active,streaming:O.isStreaming()})},so=l=>{Ye(l?"stop":"send"),L&&(L.disabled=l),zn.buttons.forEach(m=>{m.disabled=l}),re.dataset.personaComposerStreaming=l?"true":"false",re.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=l)})},ao=()=>{ct.active||ee&&ee.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>ao(),200)});let Po=()=>{var y,S,M,B,F,K,_,Se,ke,Pe,We;Xt.textContent=(S=(y=r.copy)==null?void 0:y.welcomeTitle)!=null?S:"Hello \u{1F44B}",Qe.textContent=(B=(M=r.copy)==null?void 0:M.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",ee.placeholder=(K=(F=r.copy)==null?void 0:F.inputPlaceholder)!=null?K:"How can I help...";let l=q.querySelector("[data-persona-intro-card]");if(l){let Fe=((_=r.copy)==null?void 0:_.showWelcomeCard)!==!1;l.style.display=Fe?"":"none",Fe?(q.classList.remove("persona-gap-3"),q.classList.add("persona-gap-6")):(q.classList.remove("persona-gap-6"),q.classList.add("persona-gap-3"))}!((ke=(Se=r.sendButton)==null?void 0:Se.useIcon)!=null&&ke)&&!(O!=null&&O.isStreaming())&&(se.textContent=(We=(Pe=r.copy)==null?void 0:Pe.sendButtonLabel)!=null?We:"Send"),ee.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ee.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{f(m=>({...m,sessionId:l}))}});let Qn=null,As=()=>{Qn==null&&(Qn=setInterval(()=>{let l=le.querySelectorAll("[data-tool-elapsed]");if(l.length===0){clearInterval(Qn),Qn=null;return}let m=Date.now();l.forEach(y=>{let S=Number(y.getAttribute("data-tool-elapsed"));S&&(y.textContent=Ns(m-S))})},100))};if(O=new ho(r,{onMessagesChanged(l){Dr(le,l,$),As(),O&&(l.some(M=>M.role==="user")?zn.render([],O,ee,l):zn.render(r.suggestionChips,O,ee,l,r.suggestionChipsConfig)),Sr(!qn),Ss(l);let m=[...l].reverse().find(S=>S.role==="user"),y=ct.lastUserMessageId;m&&m.id!==y&&(ct.lastUserMessageId=m.id,o.emit("user:message",m)),ct.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),ko(l)},onStatusChanged(l){var S;let m=(S=r.statusIndicator)!=null?S:{};Me(Ve,(M=>{var B,F,K,_;return M==="idle"?(B=m.idleText)!=null?B:cn.idle:M==="connecting"?(F=m.connectingText)!=null?F:cn.connecting:M==="connected"?(K=m.connectedText)!=null?K:cn.connected:M==="error"?(_=m.errorText)!=null?_:cn.error:cn[M]})(l),m,l)},onStreamingChanged(l){qn=l,so(l),O&&Dr(le,O.getMessages(),$),l||Sr(!0)},onVoiceStatusChanged(l){var m,y;if(((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":Un(),Ts();break;case"speaking":Un(),Ms();break;default:l==="idle"&&O.isBargeInActive()?(Un(),Ar(),L==null||L.setAttribute("aria-label","End voice session")):(ct.active=!1,Un(),Nn("system"),fn());break}},onArtifactsState(l){jn=l,En()}}),yr.current=O,((Ji=(Ui=r.voiceRecognition)==null?void 0:Ui.provider)==null?void 0:Ji.type)==="runtype")try{O.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&O.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),(de||r.onSSEEvent)&&O.setSSEEventCallback((l,m)=>{var y;(y=r.onSSEEvent)==null||y.call(r,l,m),de==null||de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(m)})}),u&&u.then(l=>{var m;l&&(l.metadata&&(i=ai(l.metadata),E.syncFromMetadata()),(m=l.messages)!=null&&m.length&&O.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Wo=l=>{var M;if(l.preventDefault(),O.isStreaming()){O.cancel();return}let m=ee.value.trim(),y=(M=je==null?void 0:je.hasAttachments())!=null?M:!1;if(!m&&!y)return;let S;y&&(S=[],S.push(...je.getContentParts()),m&&S.push(Yo(m))),ee.value="",ee.style.height="auto",O.sendMessage(m,{contentParts:S}),y&&je.clearAttachments()},Ro=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),se.click())},Ho=async l=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!je)return;let m=Pm(l.clipboardData);m.length!==0&&(l.preventDefault(),await je.handleFiles(m))},mn=null,Ln=!1,ir=null,tt=null,Bo=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Fr=(l="user")=>{var B,F,K,_,Se,ke,Pe;if(Ln||O.isStreaming())return;let m=Bo();if(!m)return;mn=new m;let S=(F=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?F:2e3;mn.continuous=!0,mn.interimResults=!0,mn.lang="en-US";let M=ee.value;mn.onresult=We=>{let Fe="",Ge="";for(let nt=0;nt<We.results.length;nt++){let z=We.results[nt],$e=z[0].transcript;z.isFinal?Fe+=$e+" ":Ge=$e}let ft=M+Fe+Ge;ee.value=ft,ir&&clearTimeout(ir),(Fe||Ge)&&(ir=window.setTimeout(()=>{let nt=ee.value.trim();nt&&mn&&Ln&&(Vn(),ee.value="",ee.style.height="auto",O.sendMessage(nt,{viaVoice:!0}))},S))},mn.onerror=We=>{We.error!=="no-speech"&&Vn()},mn.onend=()=>{if(Ln){let We=ee.value.trim();We&&We!==M.trim()&&(ee.value="",ee.style.height="auto",O.sendMessage(We,{viaVoice:!0})),Vn()}};try{if(mn.start(),Ln=!0,ct.active=!0,l!=="system"&&(ct.manuallyDeactivated=!1),Nn(l),fn(),L){let We=(K=r.voiceRecognition)!=null?K:{};tt={backgroundColor:L.style.backgroundColor,color:L.style.color,borderColor:L.style.borderColor,iconName:(_=We.iconName)!=null?_:"mic",iconSize:parseFloat((Pe=(ke=We.iconSize)!=null?ke:(Se=r.sendButton)==null?void 0:Se.size)!=null?Pe:"40")||24};let Fe=We.recordingBackgroundColor,Ge=We.recordingIconColor,ft=We.recordingBorderColor;if(L.classList.add("persona-voice-recording"),L.style.backgroundColor=Fe!=null?Fe:"var(--persona-voice-recording-bg, #ef4444)",L.style.color=Ge!=null?Ge:"var(--persona-voice-recording-indicator, #ffffff)",Ge){let nt=L.querySelector("svg");nt&&nt.setAttribute("stroke",Ge)}ft&&(L.style.borderColor=ft),L.setAttribute("aria-label","Stop voice recognition")}}catch{Vn("system")}},Vn=(l="user")=>{if(Ln){if(Ln=!1,ir&&(clearTimeout(ir),ir=null),mn){try{mn.stop()}catch{}mn=null}if(ct.active=!1,Nn(l),fn(),L){if(L.classList.remove("persona-voice-recording"),tt){L.style.backgroundColor=tt.backgroundColor,L.style.color=tt.color,L.style.borderColor=tt.borderColor;let m=L.querySelector("svg");m&&m.setAttribute("stroke",tt.color||"currentColor"),tt=null}L.setAttribute("aria-label","Start voice recognition")}}},Es=(l,m)=>{var z,$e,qe,Le,Ue,Tt,xt,Vt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((z=l==null?void 0:l.provider)==null?void 0:z.type)==="runtype";if(!(y||S))return null;let B=h("div","persona-send-button-wrapper"),F=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");F.type="button",F.setAttribute("aria-label","Start voice recognition");let K=($e=l==null?void 0:l.iconName)!=null?$e:"mic",_=(qe=m==null?void 0:m.size)!=null?qe:"40px",Se=(Le=l==null?void 0:l.iconSize)!=null?Le:_,ke=parseFloat(Se)||24,Pe=(Ue=l==null?void 0:l.backgroundColor)!=null?Ue:m==null?void 0:m.backgroundColor,We=(Tt=l==null?void 0:l.iconColor)!=null?Tt:m==null?void 0:m.textColor;F.style.width=Se,F.style.height=Se,F.style.minWidth=Se,F.style.minHeight=Se,F.style.fontSize="18px",F.style.lineHeight="1",We?F.style.color=We:F.style.color="var(--persona-text, #111827)";let Ge=ye(K,ke,We||"currentColor",1.5);Ge?F.appendChild(Ge):F.textContent="\u{1F3A4}",Pe?F.style.backgroundColor=Pe:F.style.backgroundColor="",l!=null&&l.borderWidth&&(F.style.borderWidth=l.borderWidth,F.style.borderStyle="solid"),l!=null&&l.borderColor&&(F.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(F.style.paddingLeft=l.paddingX,F.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(F.style.paddingTop=l.paddingY,F.style.paddingBottom=l.paddingY),B.appendChild(F);let ft=(xt=l==null?void 0:l.tooltipText)!=null?xt:"Start voice recognition";if(((Vt=l==null?void 0:l.showTooltip)!=null?Vt:!1)&&ft){let rn=h("div","persona-send-button-tooltip");rn.textContent=ft,B.appendChild(rn)}return{micButton:F,micButtonWrapper:B}},io=()=>{var m,y,S,M,B;if(!L||tt)return;let l=(m=r.voiceRecognition)!=null?m:{};tt={backgroundColor:L.style.backgroundColor,color:L.style.color,borderColor:L.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((B=(M=l.iconSize)!=null?M:(S=r.sendButton)==null?void 0:S.size)!=null?B:"40")||24}},lo=(l,m)=>{var B,F,K,_,Se;if(!L)return;let y=L.querySelector("svg");y&&y.remove();let S=(Se=tt==null?void 0:tt.iconSize)!=null?Se:parseFloat((_=(K=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?K:(F=r.sendButton)==null?void 0:F.size)!=null?_:"40")||24,M=ye(l,S,m,1.5);M&&L.appendChild(M)},Or=()=>{L&&L.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Ar=()=>{var M;if(!L)return;io();let l=(M=r.voiceRecognition)!=null?M:{},m=l.recordingBackgroundColor,y=l.recordingIconColor,S=l.recordingBorderColor;if(Or(),L.classList.add("persona-voice-recording"),L.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",L.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let B=L.querySelector("svg");B&&B.setAttribute("stroke",y)}S&&(L.style.borderColor=S),L.setAttribute("aria-label","Stop voice recognition")},Ts=()=>{var K,_,Se,ke,Pe,We,Fe,Ge;if(!L)return;io();let l=(K=r.voiceRecognition)!=null?K:{},m=O.getVoiceInterruptionMode(),y=(_=l.processingIconName)!=null?_:"loader",S=(ke=(Se=l.processingIconColor)!=null?Se:tt==null?void 0:tt.color)!=null?ke:"",M=(We=(Pe=l.processingBackgroundColor)!=null?Pe:tt==null?void 0:tt.backgroundColor)!=null?We:"",B=(Ge=(Fe=l.processingBorderColor)!=null?Fe:tt==null?void 0:tt.borderColor)!=null?Ge:"";Or(),L.classList.add("persona-voice-processing"),L.style.backgroundColor=M,L.style.borderColor=B;let F=S||"currentColor";L.style.color=F,lo(y,F),L.setAttribute("aria-label","Processing voice input"),m==="none"&&(L.style.cursor="default")},Ms=()=>{var Se,ke,Pe,We,Fe,Ge,ft,nt,z,$e,qe,Le;if(!L)return;io();let l=(Se=r.voiceRecognition)!=null?Se:{},m=O.getVoiceInterruptionMode(),y=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",S=(ke=l.speakingIconName)!=null?ke:y,M=(Ge=l.speakingIconColor)!=null?Ge:m==="barge-in"?(We=(Pe=l.recordingIconColor)!=null?Pe:tt==null?void 0:tt.color)!=null?We:"":(Fe=tt==null?void 0:tt.color)!=null?Fe:"",B=(z=l.speakingBackgroundColor)!=null?z:m==="barge-in"?(ft=l.recordingBackgroundColor)!=null?ft:"var(--persona-voice-recording-bg, #ef4444)":(nt=tt==null?void 0:tt.backgroundColor)!=null?nt:"",F=(Le=l.speakingBorderColor)!=null?Le:m==="barge-in"?($e=l.recordingBorderColor)!=null?$e:"":(qe=tt==null?void 0:tt.borderColor)!=null?qe:"";Or(),L.classList.add("persona-voice-speaking"),L.style.backgroundColor=B,L.style.borderColor=F;let K=M||"currentColor";L.style.color=K,lo(S,K);let _=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";L.setAttribute("aria-label",_),m==="none"&&(L.style.cursor="default"),m==="barge-in"&&L.classList.add("persona-voice-recording")},Un=()=>{var l,m,y;L&&(Or(),tt&&(L.style.backgroundColor=(l=tt.backgroundColor)!=null?l:"",L.style.color=(m=tt.color)!=null?m:"",L.style.borderColor=(y=tt.borderColor)!=null?y:"",lo(tt.iconName,tt.color||"currentColor"),tt=null),L.style.cursor="",L.setAttribute("aria-label","Start voice recognition"))},$r=()=>{var l,m;if(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"){let y=O.getVoiceStatus(),S=O.getVoiceInterruptionMode();if(S==="none"&&(y==="processing"||y==="speaking"))return;if(S==="cancel"&&(y==="processing"||y==="speaking")){O.stopVoicePlayback();return}if(O.isBargeInActive()){O.stopVoicePlayback(),O.deactivateBargeIn().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,fn(),Nn("user"),Un()});return}O.toggleVoice().then(()=>{ct.active=O.isVoiceActive(),ct.manuallyDeactivated=!O.isVoiceActive(),fn(),Nn("user"),O.isVoiceActive()?Ar():Un()});return}if(Ln){let y=ee.value.trim();ct.manuallyDeactivated=!0,fn(),Vn("user"),y&&(ee.value="",ee.style.height="auto",O.sendMessage(y))}else ct.manuallyDeactivated=!1,fn(),Fr("user")};Qt=$r,L&&(L.addEventListener("click",$r),wt.push(()=>{var l,m;((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?(O.isVoiceActive()&&O.toggleVoice(),Un()):Vn("system"),L&&L.removeEventListener("click",$r)}));let ks=o.on("assistant:complete",()=>{Mo&&(ct.active||ct.manuallyDeactivated||Mo==="assistant"&&!ct.lastUserMessageWasVoice||setTimeout(()=>{var l,m;!ct.active&&!ct.manuallyDeactivated&&(((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?O.toggleVoice().then(()=>{ct.active=O.isVoiceActive(),Nn("auto"),O.isVoiceActive()&&Ar()}):Fr("auto"))},600))});wt.push(ks);let Ls=o.on("action:resubmit",()=>{setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)});wt.push(Ls);let lr=()=>{Nt(!P,"user")},Ft=null,Ot=null;if(v){let l=s.find(m=>m.renderLauncher);if(l!=null&&l.renderLauncher){let m=l.renderLauncher({config:r,defaultRenderer:()=>ls(r,lr).element,onToggle:lr});m&&(Ot=m)}Ot||(Ft=ls(r,lr))}Ft?e.appendChild(Ft.element):Ot&&e.appendChild(Ot),Nr(),zn.render(r.suggestionChips,O,ee,void 0,r.suggestionChipsConfig),Po(),so(O.isStreaming()),Sr(!0),xs(),I&&(v?P&&setTimeout(()=>ao(),200):setTimeout(()=>ao(),0));let Er=()=>{var _,Se,ke,Pe,We,Fe,Ge,ft,nt,z,$e,qe,Le,Ue,Tt,xt,Vt,rn,Be,hn,an,Kn;let l=Jt(r),m=(Se=(_=r.launcher)==null?void 0:_.sidebarMode)!=null?Se:!1,y=l||m||((Pe=(ke=r.launcher)==null?void 0:ke.fullHeight)!=null?Pe:!1),S=(We=e.ownerDocument.defaultView)!=null?We:window,M=(Ge=(Fe=r.launcher)==null?void 0:Fe.mobileFullscreen)!=null?Ge:!0,B=(nt=(ft=r.launcher)==null?void 0:ft.mobileBreakpoint)!=null?nt:640,F=S.innerWidth<=B,K=M&&F&&v;try{if(K){Zn(),kr(e,r);return}if(T&&(T=!1,Zn(),kr(e,r)),!v&&!l){V.style.height="",V.style.width="";return}if(!m&&!l){let ut=($e=(z=r==null?void 0:r.launcher)==null?void 0:z.width)!=null?$e:r==null?void 0:r.launcherWidth,vt=ut!=null?ut:Pn;V.style.width=vt,V.style.maxWidth=vt}if(Xn(),!y){let ut=S.innerHeight,vt=64,yn=(Le=(qe=r.launcher)==null?void 0:qe.heightOffset)!=null?Le:0,cr=Math.max(200,ut-vt),ot=Math.min(640,cr),kt=Math.max(200,ot-yn);V.style.height=`${kt}px`}}finally{if(Ce(),Nr(),P&&v){let vt=((Ue=e.ownerDocument.defaultView)!=null?Ue:window).innerWidth<=((xt=(Tt=r.launcher)==null?void 0:Tt.mobileBreakpoint)!=null?xt:640),yn=(rn=(Vt=r.launcher)==null?void 0:Vt.sidebarMode)!=null?rn:!1,cr=(hn=(Be=r.launcher)==null?void 0:Be.mobileFullscreen)!=null?hn:!0,ot=Jt(r)&&cr&&vt,kt=yn||cr&&vt&&v||ot;if(kt&&!_t){let _r=e.getRootNode(),jr=_r instanceof ShadowRoot?_r.host:e.closest(".persona-host");jr&&!$t&&($t=Va(jr,(Kn=(an=r.launcher)==null?void 0:an.zIndex)!=null?Kn:vn)),_t=Ua(e.ownerDocument)}else kt||($t==null||$t(),$t=null,_t==null||_t(),_t=null)}}};Er();let Do=(Ki=e.ownerDocument.defaultView)!=null?Ki:window;if(Do.addEventListener("resize",Er),wt.push(()=>Do.removeEventListener("resize",Er)),typeof ResizeObserver!="undefined"){let l=new ResizeObserver(()=>{Ce()});l.observe(re),wt.push(()=>l.disconnect())}un=q.scrollTop;let No=q.scrollHeight,Fo=()=>{let l=q.scrollTop,m=q.scrollHeight,y=m<No;No=m;let{action:S,nextLastScrollTop:M}=ra({following:ce.isFollowing(),currentScrollTop:l,lastScrollTop:un,nearBottom:os(q,To),userScrollThreshold:ys,isAutoScrolling:or||Hr||y,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(un=M,S==="resume"){wr();return}S==="pause"&&Io()};q.addEventListener("scroll",Fo,{passive:!0}),wt.push(()=>q.removeEventListener("scroll",Fo));let Oo=l=>{let m=oa({following:ce.isFollowing(),deltaY:l.deltaY,nearBottom:os(q,To),resumeWhenNearBottom:!0});m==="pause"?Io():m==="resume"&&wr()};q.addEventListener("wheel",Oo,{passive:!0}),wt.push(()=>q.removeEventListener("wheel",Oo)),mt.addEventListener("click",()=>{q.scrollTop=q.scrollHeight,un=q.scrollTop,wr(),Sr(!0)}),wt.push(()=>mt.remove()),wt.push(()=>{Lo()});let $o=()=>{fe&&(Mn&&(fe.removeEventListener("click",Mn),Mn=null),v?(fe.style.display="",Mn=()=>{Nt(!1,"user")},fe.addEventListener("click",Mn)):fe.style.display="none")};$o(),(()=>{let{clearChatButton:l}=ae;l&&l.addEventListener("click",()=>{O.clearMessages(),Dn.clear(),wr();try{localStorage.removeItem(Eo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Eo}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Eo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(y){console.error("[AgentWidget] Failed to clear custom localStorage:",y)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),a!=null&&a.clear)try{let y=a.clear();y instanceof Promise&&y.catch(S=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",S)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},E.syncFromMetadata(),de==null||de.clear(),Q==null||Q.update()})})(),ht&&ht.addEventListener("submit",Wo),ee==null||ee.addEventListener("keydown",Ro),ee==null||ee.addEventListener("paste",Ho);let _o="persona-attachment-drop-active",Tr=0,co=()=>{Tr=0,D.classList.remove(_o)},Jn=()=>{var l;return((l=r.attachments)==null?void 0:l.enabled)===!0&&je!==null},ze=l=>{!ba(l.dataTransfer)||!Jn()||(Tr++,Tr===1&&D.classList.add(_o))},b=l=>{!ba(l.dataTransfer)||!Jn()||(Tr--,Tr<=0&&co())},N=l=>{!ba(l.dataTransfer)||!Jn()||(l.preventDefault(),l.dataTransfer.dropEffect="copy")},C=l=>{var y;if(!ba(l.dataTransfer)||!Jn())return;l.preventDefault(),l.stopPropagation(),co();let m=Array.from((y=l.dataTransfer.files)!=null?y:[]);m.length!==0&&je.handleFiles(m)},Y=!0;D.addEventListener("dragenter",ze,Y),D.addEventListener("dragleave",b,Y),e.addEventListener("dragover",N,Y),e.addEventListener("drop",C,Y);let Ae=e.ownerDocument,te=l=>{Jn()&&l.preventDefault()},Ze=l=>{Jn()&&l.preventDefault()};Ae.addEventListener("dragover",te),Ae.addEventListener("drop",Ze),wt.push(()=>{ht&&ht.removeEventListener("submit",Wo),ee==null||ee.removeEventListener("keydown",Ro),ee==null||ee.removeEventListener("paste",Ho)}),wt.push(()=>{D.removeEventListener("dragenter",ze,Y),D.removeEventListener("dragleave",b,Y),e.removeEventListener("dragover",N,Y),e.removeEventListener("drop",C,Y),Ae.removeEventListener("dragover",te),Ae.removeEventListener("drop",Ze),co()}),wt.push(()=>{O.cancel()}),Ft?wt.push(()=>{Ft==null||Ft.destroy()}):Ot&&wt.push(()=>{Ot==null||Ot.remove()});let we={update(l){var tl,nl,rl,ol,sl,al,il,ll,cl,dl,pl,ul,ml,gl,fl,hl,yl,bl,xl,vl,Cl,wl,Sl,Al,El,Tl,Ml,kl,Ll,Il,Pl,Wl,Rl,Hl,Bl,Dl,Nl,Fl,Ol,$l,_l,jl,zl,ql,Vl,Ul,Jl,Kl,Gl,Yl,Xl,Zl,Ql,ec,tc,nc,rc,oc,sc,ac,ic,lc,cc,dc,pc,uc,mc,gc,fc,hc,yc,bc,xc,vc,Cc,wc,Sc,Ac,Ec,Tc,Mc,kc,Lc,Ic,Pc,Wc,Rc,Hc,Bc,Dc,Nc,Fc,Oc,$c,_c,jc,zc,qc,Vc,Uc,Jc,Kc,Gc,Yc,Xc,Zc,Qc,ed,td;let m=r.toolCall,y=r.messageActions,S=(tl=r.layout)==null?void 0:tl.messages,M=r.colorScheme,B=r.loadingIndicator,F=r.iterationDisplay,K=(nl=r.features)==null?void 0:nl.showReasoning,_=(rl=r.features)==null?void 0:rl.showToolCalls,Se=(ol=r.features)==null?void 0:ol.toolCallDisplay,ke=(sl=r.features)==null?void 0:sl.reasoningDisplay;r={...r,...l},Zn(),kr(e,r),ca(e,r),da(e,r),En(),r.colorScheme!==M&&vr();let Pe=ms.getForInstance(r.plugins);s.length=0,s.push(...Pe),v=(il=(al=r.launcher)==null?void 0:al.enabled)!=null?il:!0,w=(cl=(ll=r.launcher)==null?void 0:ll.autoExpand)!=null?cl:!1,ie=(pl=(dl=r.features)==null?void 0:dl.showReasoning)!=null?pl:!0,be=(ml=(ul=r.features)==null?void 0:ul.showToolCalls)!=null?ml:!0,Ne=(fl=(gl=r.features)==null?void 0:gl.scrollToBottom)!=null?fl:{},rt(),ar();let We=pe;if(pe=(yl=(hl=r.features)==null?void 0:hl.showEventStreamToggle)!=null?yl:!1,pe&&!We){if(de||(Ee=new us(Re),de=new ps(He,Ee),Ee.open().then(()=>de==null?void 0:de.restore()).catch(()=>{}),O.setSSEEventCallback((G,yt)=>{var Pt;(Pt=r.onSSEEvent)==null||Pt.call(r,G,yt),de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:G,timestamp:Date.now(),payload:JSON.stringify(yt)})})),!et&&W){let G=(xl=(bl=r.features)==null?void 0:bl.eventStream)==null?void 0:xl.classNames,yt="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(G!=null&&G.toggleButton?" "+G.toggleButton:"");et=h("button",yt),et.style.width="28px",et.style.height="28px",et.style.color=Cn.actionIconColor,et.type="button",et.setAttribute("aria-label","Event Stream"),et.title="Event Stream";let Pt=ye("activity","18px","currentColor",1.5);Pt&&et.appendChild(Pt);let st=ae.clearChatButtonWrapper,Ct=ae.closeButtonWrapper,Ut=st||Ct;Ut&&Ut.parentNode===W?W.insertBefore(et,Ut):W.appendChild(et),et.addEventListener("click",()=>{he?tn():Wn()})}}else!pe&&We&&(tn(),et&&(et.remove(),et=null),de==null||de.clear(),Ee==null||Ee.destroy(),de=null,Ee=null);if(((vl=r.launcher)==null?void 0:vl.enabled)===!1&&Ft&&(Ft.destroy(),Ft=null),((Cl=r.launcher)==null?void 0:Cl.enabled)===!1&&Ot&&(Ot.remove(),Ot=null),((wl=r.launcher)==null?void 0:wl.enabled)!==!1&&!Ft&&!Ot){let G=s.find(yt=>yt.renderLauncher);if(G!=null&&G.renderLauncher){let yt=G.renderLauncher({config:r,defaultRenderer:()=>ls(r,lr).element,onToggle:lr});yt&&(Ot=yt,e.appendChild(Ot))}Ot||(Ft=ls(r,lr),e.appendChild(Ft.element))}Ft&&Ft.update(r),Bt&&((Sl=r.launcher)==null?void 0:Sl.title)!==void 0&&(Bt.textContent=r.launcher.title),Dt&&((Al=r.launcher)==null?void 0:Al.subtitle)!==void 0&&(Dt.textContent=r.launcher.subtitle);let Fe=(El=r.layout)==null?void 0:El.header;if((Fe==null?void 0:Fe.layout)!==R&&W){let G=Fe?bo(r,Fe,{showClose:v,onClose:()=>Nt(!1,"user")}):ur({config:r,showClose:v,onClose:()=>Nt(!1,"user")});W.replaceWith(G.header),W=G.header,Ke=G.iconHolder,Bt=G.headerTitle,Dt=G.headerSubtitle,fe=G.closeButton,R=Fe==null?void 0:Fe.layout}else if(Fe&&(Ke&&(Ke.style.display=Fe.showIcon===!1?"none":""),Bt&&(Bt.style.display=Fe.showTitle===!1?"none":""),Dt&&(Dt.style.display=Fe.showSubtitle===!1?"none":""),fe&&(fe.style.display=Fe.showCloseButton===!1?"none":""),ae.clearChatButtonWrapper)){let G=Fe.showClearChat;if(G!==void 0){ae.clearChatButtonWrapper.style.display=G?"":"none";let{closeButtonWrapper:yt}=ae;yt&&!yt.classList.contains("persona-absolute")&&(G?yt.classList.remove("persona-ml-auto"):yt.classList.add("persona-ml-auto"))}}let ft=((Tl=r.layout)==null?void 0:Tl.showHeader)!==!1;W&&(W.style.display=ft?"":"none");let nt=((Ml=r.layout)==null?void 0:Ml.showFooter)!==!1;re&&(re.style.display=nt?"":"none"),Ce(),ar(),v!==A?v?Nt(w,"auto"):(P=!0,Nr()):w!==j&&Nt(w,"auto"),j=w,A=v,Er(),$o();let qe=JSON.stringify(l.toolCall)!==JSON.stringify(m),Le=JSON.stringify(r.messageActions)!==JSON.stringify(y),Ue=JSON.stringify((kl=r.layout)==null?void 0:kl.messages)!==JSON.stringify(S),Tt=((Ll=r.loadingIndicator)==null?void 0:Ll.render)!==(B==null?void 0:B.render)||((Il=r.loadingIndicator)==null?void 0:Il.renderIdle)!==(B==null?void 0:B.renderIdle)||((Pl=r.loadingIndicator)==null?void 0:Pl.showBubble)!==(B==null?void 0:B.showBubble),xt=r.iterationDisplay!==F,Vt=((Rl=(Wl=r.features)==null?void 0:Wl.showReasoning)!=null?Rl:!0)!==(K!=null?K:!0)||((Bl=(Hl=r.features)==null?void 0:Hl.showToolCalls)!=null?Bl:!0)!==(_!=null?_:!0)||JSON.stringify((Dl=r.features)==null?void 0:Dl.toolCallDisplay)!==JSON.stringify(Se)||JSON.stringify((Nl=r.features)==null?void 0:Nl.reasoningDisplay)!==JSON.stringify(ke);(qe||Le||Ue||Tt||xt||Vt)&&O&&(Cr++,Dr(le,O.getMessages(),$));let Be=(Fl=r.launcher)!=null?Fl:{},hn=(Ol=Be.headerIconHidden)!=null?Ol:!1,an=(_l=($l=r.layout)==null?void 0:$l.header)==null?void 0:_l.showIcon,Kn=hn||an===!1,ut=Be.headerIconName,vt=(jl=Be.headerIconSize)!=null?jl:"48px";if(Ke){let G=D.querySelector(".persona-border-b-persona-divider"),yt=G==null?void 0:G.querySelector(".persona-flex-col");if(Kn)Ke.style.display="none",G&&yt&&!G.contains(yt)&&G.insertBefore(yt,G.firstChild);else{if(Ke.style.display="",Ke.style.height=vt,Ke.style.width=vt,G&&yt&&(G.contains(Ke)?Ke.nextSibling!==yt&&(Ke.remove(),G.insertBefore(Ke,yt)):G.insertBefore(Ke,yt)),ut){let st=parseFloat(vt)||24,Ct=ye(ut,st*.6,"#ffffff",2);Ct?Ke.replaceChildren(Ct):Ke.textContent=(zl=Be.agentIconText)!=null?zl:"\u{1F4AC}"}else if(Be.iconUrl){let st=Ke.querySelector("img");if(st)st.src=Be.iconUrl,st.style.height=vt,st.style.width=vt;else{let Ct=document.createElement("img");Ct.src=Be.iconUrl,Ct.alt="",Ct.className="persona-rounded-xl persona-object-cover",Ct.style.height=vt,Ct.style.width=vt,Ke.replaceChildren(Ct)}}else{let st=Ke.querySelector("svg"),Ct=Ke.querySelector("img");(st||Ct)&&Ke.replaceChildren(),Ke.textContent=(ql=Be.agentIconText)!=null?ql:"\u{1F4AC}"}let Pt=Ke.querySelector("img");Pt&&(Pt.style.height=vt,Pt.style.width=vt)}}let yn=(Ul=(Vl=r.layout)==null?void 0:Vl.header)==null?void 0:Ul.showTitle,cr=(Kl=(Jl=r.layout)==null?void 0:Jl.header)==null?void 0:Kl.showSubtitle;if(Bt&&(Bt.style.display=yn===!1?"none":""),Dt&&(Dt.style.display=cr===!1?"none":""),fe){((Yl=(Gl=r.layout)==null?void 0:Gl.header)==null?void 0:Yl.showCloseButton)===!1?fe.style.display="none":fe.style.display="";let yt=(Xl=Be.closeButtonSize)!=null?Xl:"32px",Pt=(Zl=Be.closeButtonPlacement)!=null?Zl:"inline";fe.style.height=yt,fe.style.width=yt;let{closeButtonWrapper:st}=ae,Ct=Pt==="top-right",Ut=st==null?void 0:st.classList.contains("persona-absolute");if(st&&Ct!==Ut)if(st.remove(),Ct)st.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",D.style.position="relative",D.appendChild(st);else{let dt=(ec=(Ql=Be.clearChat)==null?void 0:Ql.placement)!=null?ec:"inline",Yt=(nc=(tc=Be.clearChat)==null?void 0:tc.enabled)!=null?nc:!0;st.className=Yt&&dt==="inline"?"":"persona-ml-auto";let xn=D.querySelector(".persona-border-b-persona-divider");xn&&xn.appendChild(st)}if(fe.style.color=Be.closeButtonColor||Cn.actionIconColor,Be.closeButtonBackgroundColor?(fe.style.backgroundColor=Be.closeButtonBackgroundColor,fe.classList.remove("hover:persona-bg-gray-100")):(fe.style.backgroundColor="",fe.classList.add("hover:persona-bg-gray-100")),Be.closeButtonBorderWidth||Be.closeButtonBorderColor){let dt=Be.closeButtonBorderWidth||"0px",Yt=Be.closeButtonBorderColor||"transparent";fe.style.border=`${dt} solid ${Yt}`,fe.classList.remove("persona-border-none")}else fe.style.border="",fe.classList.add("persona-border-none");Be.closeButtonBorderRadius?(fe.style.borderRadius=Be.closeButtonBorderRadius,fe.classList.remove("persona-rounded-full")):(fe.style.borderRadius="",fe.classList.add("persona-rounded-full")),Be.closeButtonPaddingX?(fe.style.paddingLeft=Be.closeButtonPaddingX,fe.style.paddingRight=Be.closeButtonPaddingX):(fe.style.paddingLeft="",fe.style.paddingRight=""),Be.closeButtonPaddingY?(fe.style.paddingTop=Be.closeButtonPaddingY,fe.style.paddingBottom=Be.closeButtonPaddingY):(fe.style.paddingTop="",fe.style.paddingBottom="");let ln=(rc=Be.closeButtonIconName)!=null?rc:"x",Gn=(oc=Be.closeButtonIconText)!=null?oc:"\xD7";fe.innerHTML="";let gn=ye(ln,"28px","currentColor",1);gn?fe.appendChild(gn):fe.textContent=Gn;let zt=(sc=Be.closeButtonTooltipText)!=null?sc:"Close chat",In=(ac=Be.closeButtonShowTooltip)!=null?ac:!0;if(fe.setAttribute("aria-label",zt),st&&(st._cleanupTooltip&&(st._cleanupTooltip(),delete st._cleanupTooltip),In&&zt)){let dt=null,Yt=()=>{if(dt||!fe)return;let qr=fe.ownerDocument,Vo=qr.body;if(!Vo)return;dt=er(qr,"div","persona-clear-chat-tooltip"),dt.textContent=zt;let Uo=er(qr,"div");Uo.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Uo);let Vr=fe.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Lr),dt.style.left=`${Vr.left+Vr.width/2}px`,dt.style.top=`${Vr.top-8}px`,dt.style.transform="translate(-50%, -100%)",Vo.appendChild(dt)},xn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};st.addEventListener("mouseenter",Yt),st.addEventListener("mouseleave",xn),fe.addEventListener("focus",Yt),fe.addEventListener("blur",xn),st._cleanupTooltip=()=>{xn(),st&&(st.removeEventListener("mouseenter",Yt),st.removeEventListener("mouseleave",xn)),fe&&(fe.removeEventListener("focus",Yt),fe.removeEventListener("blur",xn))}}}let{clearChatButton:ot,clearChatButtonWrapper:kt}=ae;if(ot){let G=(ic=Be.clearChat)!=null?ic:{},yt=(lc=G.enabled)!=null?lc:!0,Pt=(dc=(cc=r.layout)==null?void 0:cc.header)==null?void 0:dc.showClearChat,st=Pt!==void 0?Pt:yt,Ct=(pc=G.placement)!=null?pc:"inline";if(kt){kt.style.display=st?"":"none";let{closeButtonWrapper:Ut}=ae;Ut&&!Ut.classList.contains("persona-absolute")&&(st?Ut.classList.remove("persona-ml-auto"):Ut.classList.add("persona-ml-auto"));let ln=Ct==="top-right",Gn=kt.classList.contains("persona-absolute");if(ln!==Gn&&st){if(kt.remove(),ln)kt.className="persona-absolute persona-top-4 persona-z-50",kt.style.right="48px",D.style.position="relative",D.appendChild(kt);else{kt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",kt.style.right="";let zt=D.querySelector(".persona-border-b-persona-divider"),In=ae.closeButtonWrapper;zt&&In&&In.parentElement===zt?zt.insertBefore(kt,In):zt&&zt.appendChild(kt)}let gn=ae.closeButtonWrapper;gn&&!gn.classList.contains("persona-absolute")&&(ln?gn.classList.add("persona-ml-auto"):gn.classList.remove("persona-ml-auto"))}}if(st){let Ut=(uc=G.size)!=null?uc:"32px";ot.style.height=Ut,ot.style.width=Ut;let ln=(mc=G.iconName)!=null?mc:"refresh-cw",Gn=(gc=G.iconColor)!=null?gc:"";ot.style.color=Gn||Cn.actionIconColor,ot.innerHTML="";let gn=ye(ln,"20px","currentColor",2);if(gn&&ot.appendChild(gn),G.backgroundColor?(ot.style.backgroundColor=G.backgroundColor,ot.classList.remove("hover:persona-bg-gray-100")):(ot.style.backgroundColor="",ot.classList.add("hover:persona-bg-gray-100")),G.borderWidth||G.borderColor){let dt=G.borderWidth||"0px",Yt=G.borderColor||"transparent";ot.style.border=`${dt} solid ${Yt}`,ot.classList.remove("persona-border-none")}else ot.style.border="",ot.classList.add("persona-border-none");G.borderRadius?(ot.style.borderRadius=G.borderRadius,ot.classList.remove("persona-rounded-full")):(ot.style.borderRadius="",ot.classList.add("persona-rounded-full")),G.paddingX?(ot.style.paddingLeft=G.paddingX,ot.style.paddingRight=G.paddingX):(ot.style.paddingLeft="",ot.style.paddingRight=""),G.paddingY?(ot.style.paddingTop=G.paddingY,ot.style.paddingBottom=G.paddingY):(ot.style.paddingTop="",ot.style.paddingBottom="");let zt=(fc=G.tooltipText)!=null?fc:"Clear chat",In=(hc=G.showTooltip)!=null?hc:!0;if(ot.setAttribute("aria-label",zt),kt&&(kt._cleanupTooltip&&(kt._cleanupTooltip(),delete kt._cleanupTooltip),In&&zt)){let dt=null,Yt=()=>{if(dt||!ot)return;let qr=ot.ownerDocument,Vo=qr.body;if(!Vo)return;dt=er(qr,"div","persona-clear-chat-tooltip"),dt.textContent=zt;let Uo=er(qr,"div");Uo.className="persona-clear-chat-tooltip-arrow",dt.appendChild(Uo);let Vr=ot.getBoundingClientRect();dt.style.position="fixed",dt.style.zIndex=String(Lr),dt.style.left=`${Vr.left+Vr.width/2}px`,dt.style.top=`${Vr.top-8}px`,dt.style.transform="translate(-50%, -100%)",Vo.appendChild(dt)},xn=()=>{dt&&dt.parentNode&&(dt.parentNode.removeChild(dt),dt=null)};kt.addEventListener("mouseenter",Yt),kt.addEventListener("mouseleave",xn),ot.addEventListener("focus",Yt),ot.addEventListener("blur",xn),kt._cleanupTooltip=()=>{xn(),kt&&(kt.removeEventListener("mouseenter",Yt),kt.removeEventListener("mouseleave",xn)),ot&&(ot.removeEventListener("focus",Yt),ot.removeEventListener("blur",xn))}}}}let _r=r.actionParsers&&r.actionParsers.length?r.actionParsers:[gs],jr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[to.message,to.messageAndClick];E=fs({parsers:_r,handlers:jr,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),$=yp(r,E,U),O.updateConfig(r),Dr(le,O.getMessages(),$),zn.render(r.suggestionChips,O,ee,void 0,r.suggestionChipsConfig),Po(),so(O.isStreaming());let Is=((yc=r.voiceRecognition)==null?void 0:yc.enabled)===!0,Ps=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Ws=((xc=(bc=r.voiceRecognition)==null?void 0:bc.provider)==null?void 0:xc.type)==="runtype";if(Is&&(Ps||Ws))if(!L||!ve){let G=Es(r.voiceRecognition,r.sendButton);G&&(L=G.micButton,ve=G.micButtonWrapper,Je.insertBefore(ve,Et),L.addEventListener("click",$r),L.disabled=O.isStreaming())}else{let G=(vc=r.voiceRecognition)!=null?vc:{},yt=(Cc=r.sendButton)!=null?Cc:{},Pt=(wc=G.iconName)!=null?wc:"mic",st=(Sc=yt.size)!=null?Sc:"40px",Ct=(Ac=G.iconSize)!=null?Ac:st,Ut=parseFloat(Ct)||24;L.style.width=Ct,L.style.height=Ct,L.style.minWidth=Ct,L.style.minHeight=Ct;let ln=(Tc=(Ec=G.iconColor)!=null?Ec:yt.textColor)!=null?Tc:"currentColor";L.innerHTML="";let Gn=ye(Pt,Ut,ln,2);Gn?L.appendChild(Gn):L.textContent="\u{1F3A4}";let gn=(Mc=G.backgroundColor)!=null?Mc:yt.backgroundColor;gn?L.style.backgroundColor=gn:L.style.backgroundColor="",ln?L.style.color=ln:L.style.color="var(--persona-text, #111827)",G.borderWidth?(L.style.borderWidth=G.borderWidth,L.style.borderStyle="solid"):(L.style.borderWidth="",L.style.borderStyle=""),G.borderColor?L.style.borderColor=G.borderColor:L.style.borderColor="",G.paddingX?(L.style.paddingLeft=G.paddingX,L.style.paddingRight=G.paddingX):(L.style.paddingLeft="",L.style.paddingRight=""),G.paddingY?(L.style.paddingTop=G.paddingY,L.style.paddingBottom=G.paddingY):(L.style.paddingTop="",L.style.paddingBottom="");let zt=ve==null?void 0:ve.querySelector(".persona-send-button-tooltip"),In=(kc=G.tooltipText)!=null?kc:"Start voice recognition";if(((Lc=G.showTooltip)!=null?Lc:!1)&&In)if(zt)zt.textContent=In,zt.style.display="";else{let Yt=document.createElement("div");Yt.className="persona-send-button-tooltip",Yt.textContent=In,ve==null||ve.insertBefore(Yt,L)}else zt&&(zt.style.display="none");ve.style.display="",L.disabled=O.isStreaming()}else L&&ve&&(ve.style.display="none",((Pc=(Ic=r.voiceRecognition)==null?void 0:Ic.provider)==null?void 0:Pc.type)==="runtype"?O.isVoiceActive()&&O.toggleVoice():Ln&&Vn());if(((Wc=r.attachments)==null?void 0:Wc.enabled)===!0)if(!it||!De){let G=(Rc=r.attachments)!=null?Rc:{},Pt=(Bc=((Hc=r.sendButton)!=null?Hc:{}).size)!=null?Bc:"40px";ne||(ne=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ne.style.display="none",ht.insertBefore(ne,ee)),Z||(Z=document.createElement("input"),Z.type="file",Z.accept=((Dc=G.allowedTypes)!=null?Dc:pr).join(","),Z.multiple=((Nc=G.maxFiles)!=null?Nc:4)>1,Z.style.display="none",Z.setAttribute("aria-label","Attach files"),ht.insertBefore(Z,ee)),it=h("div","persona-send-button-wrapper"),De=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),De.type="button",De.setAttribute("aria-label",(Fc=G.buttonTooltipText)!=null?Fc:"Attach file");let st=(Oc=G.buttonIconName)!=null?Oc:"paperclip",Ct=Pt,Ut=parseFloat(Ct)||40,ln=Math.round(Ut*.6);De.style.width=Ct,De.style.height=Ct,De.style.minWidth=Ct,De.style.minHeight=Ct,De.style.fontSize="18px",De.style.lineHeight="1",De.style.backgroundColor="transparent",De.style.color="var(--persona-primary, #111827)",De.style.border="none",De.style.borderRadius="6px",De.style.transition="background-color 0.15s ease",De.addEventListener("mouseenter",()=>{De.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),De.addEventListener("mouseleave",()=>{De.style.backgroundColor="transparent"});let Gn=ye(st,ln,"currentColor",1.5);Gn?De.appendChild(Gn):De.textContent="\u{1F4CE}",De.addEventListener("click",In=>{In.preventDefault(),Z==null||Z.click()}),it.appendChild(De);let gn=($c=G.buttonTooltipText)!=null?$c:"Attach file",zt=h("div","persona-send-button-tooltip");zt.textContent=gn,it.appendChild(zt),Oe.append(it),!je&&Z&&ne&&(je=Zr.fromConfig(G),je.setPreviewsContainer(ne),Z.addEventListener("change",async()=>{je&&(Z!=null&&Z.files)&&(await je.handleFileSelect(Z.files),Z.value="")})),D.querySelector(".persona-attachment-drop-overlay")||D.appendChild(bp(G.dropOverlay))}else{it.style.display="";let G=(_c=r.attachments)!=null?_c:{};Z&&(Z.accept=((jc=G.allowedTypes)!=null?jc:pr).join(","),Z.multiple=((zc=G.maxFiles)!=null?zc:4)>1),je&&je.updateConfig({allowedTypes:G.allowedTypes,maxFileSize:G.maxFileSize,maxFiles:G.maxFiles})}else it&&(it.style.display="none"),je&&je.clearAttachments(),(qc=D.querySelector(".persona-attachment-drop-overlay"))==null||qc.remove();let qt=(Vc=r.sendButton)!=null?Vc:{},Rs=(Uc=qt.useIcon)!=null?Uc:!1,jo=(Jc=qt.iconText)!=null?Jc:"\u2191",zo=qt.iconName,po=(Kc=qt.tooltipText)!=null?Kc:"Send message",bn=(Gc=qt.showTooltip)!=null?Gc:!1,on=(Yc=qt.size)!=null?Yc:"40px",On=qt.backgroundColor,zr=qt.textColor;if(Rs){if(se.style.width=on,se.style.height=on,se.style.minWidth=on,se.style.minHeight=on,se.style.fontSize="18px",se.style.lineHeight="1",se.innerHTML="",zr?se.style.color=zr:se.style.color="var(--persona-button-primary-fg, #ffffff)",zo){let G=parseFloat(on)||24,yt=(zr==null?void 0:zr.trim())||"currentColor",Pt=ye(zo,G,yt,2);Pt?se.appendChild(Pt):se.textContent=jo}else se.textContent=jo;se.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",On?(se.style.backgroundColor=On,se.classList.remove("persona-bg-persona-primary")):(se.style.backgroundColor="",se.classList.add("persona-bg-persona-primary"))}else se.textContent=(Zc=(Xc=r.copy)==null?void 0:Xc.sendButtonLabel)!=null?Zc:"Send",se.style.width="",se.style.height="",se.style.minWidth="",se.style.minHeight="",se.style.fontSize="",se.style.lineHeight="",se.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",On?(se.style.backgroundColor=On,se.classList.remove("persona-bg-persona-accent")):se.classList.add("persona-bg-persona-accent"),zr?se.style.color=zr:se.classList.add("persona-text-white");qt.borderWidth?(se.style.borderWidth=qt.borderWidth,se.style.borderStyle="solid"):(se.style.borderWidth="",se.style.borderStyle=""),qt.borderColor?se.style.borderColor=qt.borderColor:se.style.borderColor="",qt.paddingX?(se.style.paddingLeft=qt.paddingX,se.style.paddingRight=qt.paddingX):(se.style.paddingLeft="",se.style.paddingRight=""),qt.paddingY?(se.style.paddingTop=qt.paddingY,se.style.paddingBottom=qt.paddingY):(se.style.paddingTop="",se.style.paddingBottom="");let qo=Et==null?void 0:Et.querySelector(".persona-send-button-tooltip");if(bn&&po)if(qo)qo.textContent=po,qo.style.display="";else{let G=document.createElement("div");G.className="persona-send-button-tooltip",G.textContent=po,Et==null||Et.insertBefore(G,se)}else qo&&(qo.style.display="none");let Hs=(Qc=r.layout)==null?void 0:Qc.contentMaxWidth;Hs?(le.style.maxWidth=Hs,le.style.marginLeft="auto",le.style.marginRight="auto",le.style.width="100%",ht&&(ht.style.maxWidth=Hs,ht.style.marginLeft="auto",ht.style.marginRight="auto"),xe&&(xe.style.maxWidth=Hs,xe.style.marginLeft="auto",xe.style.marginRight="auto")):(le.style.maxWidth="",le.style.marginLeft="",le.style.marginRight="",le.style.width="",ht&&(ht.style.maxWidth="",ht.style.marginLeft="",ht.style.marginRight=""),xe&&(xe.style.maxWidth="",xe.style.marginLeft="",xe.style.marginRight=""));let Mr=(ed=r.statusIndicator)!=null?ed:{},ru=(td=Mr.visible)!=null?td:!0;if(Ve.style.display=ru?"":"none",O){let G=O.getStatus();Me(Ve,(Pt=>{var st,Ct,Ut,ln;return Pt==="idle"?(st=Mr.idleText)!=null?st:cn.idle:Pt==="connecting"?(Ct=Mr.connectingText)!=null?Ct:cn.connecting:Pt==="connected"?(Ut=Mr.connectedText)!=null?Ut:cn.connected:Pt==="error"?(ln=Mr.errorText)!=null?ln:cn.error:cn[Pt]})(G),Mr,G)}Ve.classList.remove("persona-text-left","persona-text-center","persona-text-right");let ou=Mr.align==="left"?"persona-text-left":Mr.align==="center"?"persona-text-center":"persona-text-right";Ve.classList.add(ou)},open(){v&&Nt(!0,"api")},close(){v&&Nt(!1,"api")},toggle(){v&&Nt(!P,"api")},clearChat(){dn=!1,O.clearMessages(),Dn.clear(),wr();try{localStorage.removeItem(Eo),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Eo}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Eo)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let m=a.clear();m instanceof Promise&&m.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}i={},E.syncFromMetadata(),de==null||de.clear(),Q==null||Q.update()},setMessage(l){return!ee||O.isStreaming()?!1:(!P&&v&&Nt(!0,"system"),ee.value=l,ee.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(O.isStreaming())return!1;let m=(l==null?void 0:l.trim())||ee.value.trim();return m?(!P&&v&&Nt(!0,"system"),ee.value="",ee.style.height="auto",O.sendMessage(m),!0):!1},startVoiceRecognition(){var m,y;return O.isStreaming()?!1:((y=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:y.type)==="runtype"?(O.isVoiceActive()||(!P&&v&&Nt(!0,"system"),ct.manuallyDeactivated=!1,fn(),O.toggleVoice().then(()=>{ct.active=O.isVoiceActive(),Nn("user"),O.isVoiceActive()&&Ar()})),!0):Ln?!0:Bo()?(!P&&v&&Nt(!0,"system"),ct.manuallyDeactivated=!1,fn(),Fr("user"),!0):!1},stopVoiceRecognition(){var l,m;return((m=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:m.type)==="runtype"?O.isVoiceActive()?(O.toggleVoice().then(()=>{ct.active=!1,ct.manuallyDeactivated=!0,fn(),Nn("user"),Un()}),!0):!1:Ln?(ct.manuallyDeactivated=!0,fn(),Vn("user"),!0):!1},injectMessage(l){return!P&&v&&Nt(!0,"system"),O.injectMessage(l)},injectAssistantMessage(l){!P&&v&&Nt(!0,"system");let m=O.injectAssistantMessage(l);return H&&(H=!1,J&&(clearTimeout(J),J=null),setTimeout(()=>{O&&!O.isStreaming()&&O.continueConversation()},100)),m},injectUserMessage(l){return!P&&v&&Nt(!0,"system"),O.injectUserMessage(l)},injectSystemMessage(l){return!P&&v&&Nt(!0,"system"),O.injectSystemMessage(l)},injectMessageBatch(l){return!P&&v&&Nt(!0,"system"),O.injectMessageBatch(l)},injectTestMessage(l){!P&&v&&Nt(!0,"system"),O.injectTestEvent(l)},async connectStream(l,m){return O.connectStream(l,m)},__pushEventStreamEvent(l){de&&de.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!pe||!de||Wn()},hideEventStream(){he&&tn()},isEventStreamVisible(){return he},showArtifacts(){_n(r)&&(dn=!1,En(),gt==null||gt.setMobileOpen(!0))},hideArtifacts(){_n(r)&&(dn=!0,En())},upsertArtifact(l){return _n(r)?(dn=!1,O.upsertArtifact(l)):null},selectArtifact(l){_n(r)&&O.selectArtifact(l)},clearArtifacts(){_n(r)&&O.clearArtifacts()},focusInput(){return v&&!P||!ee?!1:(ee.focus(),!0)},async resolveApproval(l,m){let S=O.getMessages().find(M=>{var B;return M.variant==="approval"&&((B=M.approval)==null?void 0:B.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return O.resolveApproval(S.approval,m)},getMessages(){return O.getMessages()},getStatus(){return O.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,m){return o.on(l,m)},off(l,m){o.off(l,m)},isOpen(){return v&&P},isVoiceActive(){return ct.active},getState(){return{open:v&&P,launcherEnabled:v,voiceActive:ct.active,streaming:O.isStreaming()}},showCSATFeedback(l){!P&&v&&Nt(!0,"system");let m=le.querySelector(".persona-feedback-container");m&&m.remove();let y=ha({onSubmit:async(S,M)=>{var B;O.isClientTokenMode()&&await O.submitCSATFeedback(S,M),(B=l==null?void 0:l.onSubmit)==null||B.call(l,S,M)},onDismiss:l==null?void 0:l.onDismiss,...l});le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!P&&v&&Nt(!0,"system");let m=le.querySelector(".persona-feedback-container");m&&m.remove();let y=ya({onSubmit:async(S,M)=>{var B;O.isClientTokenMode()&&await O.submitNPSFeedback(S,M),(B=l==null?void 0:l.onSubmit)==null||B.call(l,S,M)},onDismiss:l==null?void 0:l.onDismiss,...l});le.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,m){return O.submitCSATFeedback(l,m)},async submitNPSFeedback(l,m){return O.submitNPSFeedback(l,m)},destroy(){Qn!=null&&(clearInterval(Qn),Qn=null),wt.forEach(l=>l()),k.remove(),Ft==null||Ft.destroy(),Ot==null||Ot.remove(),Mn&&fe.removeEventListener("click",Mn)}};if((((Gi=t==null?void 0:t.debugTools)!=null?Gi:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,m={controller:we,getMessages:we.getMessages,getStatus:we.getStatus,getMetadata:we.getPersistentMetadata,updateMetadata:we.updatePersistentMetadata,clearHistory:()=>we.clearChat(),setVoiceActive:y=>y?we.startVoiceRecognition():we.stopVoiceRecognition()};window.AgentWidgetBrowser=m,wt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&we.focusInput()};if(window.addEventListener("persona:focusInput",m),wt.push(()=>{window.removeEventListener("persona:focusInput",m)}),pe){let K=Se=>{let ke=Se.detail;(!(ke!=null&&ke.instanceId)||ke.instanceId===l)&&we.showEventStream()},_=Se=>{let ke=Se.detail;(!(ke!=null&&ke.instanceId)||ke.instanceId===l)&&we.hideEventStream()};window.addEventListener("persona:showEventStream",K),window.addEventListener("persona:hideEventStream",_),wt.push(()=>{window.removeEventListener("persona:showEventStream",K),window.removeEventListener("persona:hideEventStream",_)})}let y=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&we.showArtifacts()},S=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&we.hideArtifacts()},M=K=>{let _=K.detail;_!=null&&_.instanceId&&_.instanceId!==l||_!=null&&_.artifact&&we.upsertArtifact(_.artifact)},B=K=>{let _=K.detail;_!=null&&_.instanceId&&_.instanceId!==l||typeof(_==null?void 0:_.id)=="string"&&we.selectArtifact(_.id)},F=K=>{let _=K.detail;(!(_!=null&&_.instanceId)||_.instanceId===l)&&we.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",M),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",F),wt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",M),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",F)})}let Xe=Wm(r.persistState);if(Xe&&v){let l=Rm(Xe.storage),m=`${Xe.keyPrefix}widget-open`,y=`${Xe.keyPrefix}widget-voice`,S=`${Xe.keyPrefix}widget-voice-mode`;if(l){let M=((Yi=Xe.persist)==null?void 0:Yi.openState)&&l.getItem(m)==="true",B=((Xi=Xe.persist)==null?void 0:Xi.voiceState)&&l.getItem(y)==="true",F=((Zi=Xe.persist)==null?void 0:Zi.voiceState)&&l.getItem(S)==="true";if(M&&setTimeout(()=>{we.open(),setTimeout(()=>{var K;if(B||F)we.startVoiceRecognition();else if((K=Xe.persist)!=null&&K.focusInput){let _=e.querySelector("textarea");_&&_.focus()}},100)},0),(Qi=Xe.persist)!=null&&Qi.openState&&(o.on("widget:opened",()=>{l.setItem(m,"true")}),o.on("widget:closed",()=>{l.setItem(m,"false")})),(el=Xe.persist)!=null&&el.voiceState&&(o.on("voice:state",K=>{l.setItem(y,K.active?"true":"false")}),o.on("user:message",K=>{l.setItem(S,K.viaVoice?"true":"false")})),Xe.clearOnChatClear){let K=()=>{l.removeItem(m),l.removeItem(y),l.removeItem(S)},_=()=>K();window.addEventListener("persona:clear-chat",_),wt.push(()=>{window.removeEventListener("persona:clear-chat",_)})}}}return c&&v&&setTimeout(()=>{we.open()},0),we};var Hm=(e,n)=>{let t=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(t);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(t);return s?Math.max(0,n*parseFloat(s[1])/100):420},xp=(e,n)=>{var r,s;let t=(s=(r=n==null?void 0:n.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=t?"":"100%",e.style.display=t?"":"flex",e.style.flexDirection=t?"":"column",e.style.flex=t?"":"1 1 auto",e.style.minHeight=t?"":"0"},di=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},vp=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",di(e)},ii=e=>{e.style.transition=""},li=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},ci=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},va=(e,n)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",n.style.alignItems=""},Bm=(e,n,t,r,s)=>{s?t.parentElement!==n&&(e.replaceChildren(),n.replaceChildren(t,r),e.appendChild(n)):t.parentElement===n&&(n.replaceChildren(),e.appendChild(t),e.appendChild(r))},Dm=(e,n,t,r,s,o)=>{let a=o?n:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,t):a.lastElementChild!==r&&a.replaceChildren(t,r)},Cp=(e,n,t,r,s,o,a)=>{var x,E,v,w,I,j;let i=$n(o),u=i.reveal==="push";Bm(e,n,t,r,u),Dm(e,n,t,r,i.side,u),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.minHeight="0",t.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let c=e.ownerDocument.defaultView,p=(E=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?E:!0,d=(w=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileBreakpoint)!=null?w:640,f=c!=null?c.innerWidth<=d:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),li(n),ii(r),vp(r),ci(t),va(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((j=(I=o==null?void 0:o.launcher)==null?void 0:I.zIndex)!=null?j:vn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",u&&(n.style.display="flex",n.style.flexDirection="column",n.style.width="100%",n.style.height="100%",n.style.minHeight="0",n.style.minWidth="0",n.style.flex="1 1 auto",n.style.alignItems="stretch",n.style.transform="none",n.style.transition="none",t.style.flex="1 1 auto",t.style.width="100%",t.style.maxWidth="100%",t.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),vp(r),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",li(n),ii(r),ci(t),va(s,r);let A=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":R;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=A,r.style.transform=T,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",ii(r),di(r),va(s,r);let A=Hm(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),T=i.animate?"transform 180ms ease":"none",P=i.side==="right"?a?`translateX(-${A}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${A}px)`;n.style.display="flex",n.style.flexDirection="row",n.style.flex="0 0 auto",n.style.minHeight="0",n.style.minWidth="0",n.style.alignItems="stretch",n.style.height="100%",n.style.width=`${R+A}px`,n.style.transition=T,n.style.transform=P,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${R}px`,t.style.maxWidth=`${R}px`,t.style.minWidth=`${R}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",li(n),di(r),ci(t),va(s,r);let A=i.reveal==="emerge";A?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",T=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",r.style.position="relative",r.style.overflow=A||P?"hidden":"visible",r.style.transition=T,A&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},Nm=(e,n)=>{let t=e.ownerDocument.createElement("div");return xp(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){xp(t,r)},destroy(){t.remove()}}},Fm=(e,n)=>{var I,j,A,R;let{ownerDocument:t}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=t.createElement("div"),i=t.createElement("div"),u=t.createElement("div"),c=t.createElement("aside"),p=t.createElement("div"),d=(j=(I=n==null?void 0:n.launcher)==null?void 0:I.enabled)==null||j?(R=(A=n==null?void 0:n.launcher)==null?void 0:A.autoExpand)!=null?R:!1:!0;i.dataset.personaDockRole="push-track",u.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",c.appendChild(p),r.insertBefore(a,e),u.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},x=()=>{g(),$n(n).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Cp(a,i,u,c,p,n,d)}),f.observe(a))},E=()=>{Cp(a,i,u,c,p,n,d),x()},v=a.ownerDocument.defaultView,w=()=>{E()};return v==null||v.addEventListener("resize",w),$n(n).reveal==="push"?(i.appendChild(u),i.appendChild(c),a.appendChild(i)):(a.appendChild(u),a.appendChild(c)),E(),{mode:"docked",host:p,shell:a,syncWidgetState(T){let P=T.launcherEnabled?T.open:!0;d!==P&&(d=P,E())},updateConfig(T){var P,H;n=T,((H=(P=n==null?void 0:n.launcher)==null?void 0:P.enabled)!=null?H:!0)===!1&&(d=!0),E()},destroy(){v==null||v.removeEventListener("resize",w),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},hs=(e,n)=>Jt(n)?Fm(e,n):Nm(e,n);var pi={},Om=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let n=document.querySelector(e);if(!n)throw new Error(`Chat widget target "${e}" was not found`);return n}return e},$m=()=>{try{if(typeof pi!="undefined"&&pi.url)return new URL("../widget.css",pi.url).href}catch{}return null},wp=(e,n)=>{let t=$m(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=n.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(t){let s=n.createElement("link");s.rel="stylesheet",s.href=t,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!n.head.querySelector("link[data-persona]")&&t){let o=n.createElement("link");o.rel="stylesheet",o.href=t,o.setAttribute("data-persona","true"),n.head.appendChild(o)}},ui=e=>{var v;let n=Om(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=hs(n,s),a,i=[],u=(w,I)=>{var T,P;let A=!((P=(T=I==null?void 0:I.launcher)==null?void 0:T.enabled)!=null?P:!0)||Jt(I),R=r.createElement("div");if(R.setAttribute("data-persona-root","true"),A&&(R.style.height="100%",R.style.display="flex",R.style.flexDirection="column",R.style.flex="1",R.style.minHeight="0"),t){let H=w.attachShadow({mode:"open"});H.appendChild(R),wp(H,r)}else w.appendChild(R),wp(w,r);return n.id&&R.setAttribute("data-persona-instance",n.id),R},c=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let w=u(o.host,s);a=xa(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};d(),(v=e.onReady)==null||v.call(e);let g=w=>{f(),o.destroy(),o=hs(n,w),s=w,d()},x={update(w){var R,T,P,H,J,U;let I={...s,...w,launcher:{...(R=s==null?void 0:s.launcher)!=null?R:{},...(T=w==null?void 0:w.launcher)!=null?T:{},dock:{...(H=(P=s==null?void 0:s.launcher)==null?void 0:P.dock)!=null?H:{},...(U=(J=w==null?void 0:w.launcher)==null?void 0:J.dock)!=null?U:{}}}},j=Jt(s),A=Jt(I);if(j!==A){g(I);return}s=I,o.updateConfig(s),a.update(w),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},E=new Proxy(x,{get(w,I,j){if(I==="host")return o.host;if(I in w)return Reflect.get(w,I,j);let A=a[I];return typeof A=="function"?A.bind(a):A}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=E),E};var Mp=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),_m=new Set(["button","a","input","select","textarea","details","summary"]),jm=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),mi=/\b(product|card|item|listing|result)\b/i,fi=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,zm=3e3,qm=100;function kp(e){let n=typeof e.className=="string"?e.className:"";if(mi.test(n)||e.id&&mi.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&mi.test(r.value))return!0}return!1}function Lp(e){var n;return fi.test(((n=e.textContent)!=null?n:"").trim())}function Ip(e){var t;let n=e.querySelectorAll("a[href]");for(let r=0;r<n.length;r++){let s=(t=n[r].getAttribute("href"))!=null?t:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Vm(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Sp(e){let n=e.match(fi);return n?n[0]:null}function Ap(e){var r,s,o;let n=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(n&&((s=n.textContent)!=null&&s.trim())){let a=n.getAttribute("href");return{title:n.textContent.trim(),href:a&&a!=="#"?a:null}}let t=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=t==null?void 0:t.textContent)!=null&&o.trim()?{title:t.textContent.trim(),href:null}:{title:"",href:null}}function Um(e){let n=[],t=r=>{let s=r.trim();s&&!n.includes(s)&&n.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return t((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;t((s=r.value)!=null?s:"")}),n.slice(0,6)}var Jm="commerce-card",Km="result-card";function Ep(e){return!kp(e)||!Lp(e)||!Ip(e)&&!Vm(e)?0:5200}function Tp(e){var r;return!kp(e)||Lp(e)||!Ip(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var hi=[{id:Jm,scoreElement(e){return Ep(e)},shouldSuppressDescendant(e,n,t){if(n===e||!e.contains(n))return!1;if(t.interactivity==="static"){let r=t.text.trim();return!!(r.length===0||fi.test(r)&&r.length<32)}return!0},formatSummary(e,n){var u,c,p;if(Ep(e)===0)return null;let{title:t,href:r}=Ap(e),s=(p=(c=Sp(((u=e.textContent)!=null?u:"").trim()))!=null?c:Sp(n.text))!=null?p:"",o=Um(e);return[r&&t?`[${t}](${r})${s?` \u2014 ${s}`:""}`:t?`${t}${s?` \u2014 ${s}`:""}`:s||n.text.trim().slice(0,120),`selector: ${n.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
|
|
101
|
+
`)}},{id:Km,scoreElement(e){return Tp(e)},formatSummary(e,n){if(Tp(e)===0)return null;let{title:t,href:r}=Ap(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
|
|
102
|
+
`)}}];function Gm(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Ym(e){var p,d,f,g,x,E,v,w,I,j,A,R,T;let n=(p=e.options)!=null?p:{},t=(f=(d=n.maxElements)!=null?d:e.maxElements)!=null?f:80,r=(x=(g=n.excludeSelector)!=null?g:e.excludeSelector)!=null?x:".persona-host",s=(v=(E=n.maxTextLength)!=null?E:e.maxTextLength)!=null?v:200,o=(I=(w=n.visibleOnly)!=null?w:e.visibleOnly)!=null?I:!0,a=(j=n.root)!=null?j:e.root,i=(A=n.mode)!=null?A:"structured",u=(R=n.maxCandidates)!=null?R:Math.max(500,t*10),c=(T=e.rules)!=null?T:hi;return i==="simple"&&e.rules&&e.rules.length>0?(Gm(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:u,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function gi(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Xm=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Zm(e){let n=e.tagName.toLowerCase(),t=e.getAttribute("role");return n==="a"&&e.hasAttribute("href")?"navigable":n==="input"||n==="select"||n==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":n==="button"||t==="button"||_m.has(n)||t&&jm.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Pp(e){if(e.hidden)return!1;try{let n=getComputedStyle(e);if(n.display==="none"||n.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Qm(e){let n={},t=e.id;t&&(n.id=t);let r=e.getAttribute("href");r&&(n.href=r);let s=e.getAttribute("aria-label");s&&(n["aria-label"]=s);let o=e.getAttribute("type");o&&(n.type=o);let a=e.getAttribute("value");a&&(n.value=a);let i=e.getAttribute("name");i&&(n.name=i);let u=e.getAttribute("role");u&&(n.role=u);for(let c=0;c<e.attributes.length;c++){let p=e.attributes[c];p.name.startsWith("data-")&&(n[p.name]=p.value)}return n}function yi(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${gi(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Xm){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${gi(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let t=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(t.length>0){let s=`${n}.${t.map(a=>gi(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(i>=0){let u=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(u).length===1)return u}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${n}`)).indexOf(e);if(o>=0)return`${n}:nth-of-type(${o+1})`}return n}function eg(e){return e==="static"?qm:zm}function Wp(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:yi(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:Zm(e),attributes:Qm(e)}}function tg(e,n,t,r){let s=eg(n.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,n,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function ng(e,n){var t;for(let r of e)if(n.el!==r.el&&(t=r.formattingRule)!=null&&t.shouldSuppressDescendant&&r.el.contains(n.el)&&r.formattingRule.shouldSuppressDescendant(r.el,n.el,n.enriched))return!0;return!1}function rg(e,n){let t={doc:n.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,p=c.tagName.toLowerCase();if(Mp.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Pp(c)){i=a.nextNode();continue}let d=Wp(c,e.maxTextLength),f=d.text.length>0,g=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(v=>v==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(d.selector)){i=a.nextNode();continue}r.add(d.selector);let{score:x,formattingRule:E}=tg(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:x,formattingRule:E}),o+=1}i=a.nextNode()}s.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex});let u=[];for(let c of s){if(u.length>=e.maxElements)break;ng(u,c)||u.push(c)}return u.sort((c,p)=>{let d=c.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&p.score!==c.score?p.score-c.score:c.domIndex-p.domIndex}),u.map(c=>{var f;let p;if((f=c.formattingRule)!=null&&f.formatSummary){let g=c.formattingRule.formatSummary(c.el,c.enriched,t);g&&(p=g)}let d={...c.enriched};return p&&(d.formattedSummary=p),d})}function og(e,n){let t=[],r=new Set,s=document.createTreeWalker(n,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let u=o,c=u.tagName.toLowerCase();if(Mp.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(u.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Pp(u)){o=s.nextNode();continue}let p=Wp(u,e.maxTextLength),d=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!d&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),t.push(p))}o=s.nextNode()}let a=[],i=[];for(let u of t)u.interactivity!=="static"?a.push(u):i.push(u);return[...a,...i].slice(0,e.maxElements)}function Rp(e={}){var r;let n=Ym(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?og(n,t):rg(n,t):[]}var Ca=100;function Hp(e,n={}){var o;if(e.length===0)return"No page elements found.";let t=(o=n.mode)!=null?o:"structured",r=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
|
|
102
103
|
${a.map(i=>`- ${i.split(`
|
|
103
104
|
`).join(`
|
|
104
105
|
`)}`).join(`
|
|
105
|
-
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
106
|
+
`)}`)}let s={clickable:[],navigable:[],input:[],static:[]};for(let a of e)t==="structured"&&a.formattedSummary||s[a.interactivity].push(a);if(s.clickable.length>0){let a=s.clickable.map(i=>`- ${i.selector}: "${i.text.substring(0,Ca)}" (clickable)`);r.push(`Interactive elements:
|
|
106
107
|
${a.join(`
|
|
107
|
-
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,
|
|
108
|
+
`)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Ca)}" (navigable)`);r.push(`Navigation links:
|
|
108
109
|
${a.join(`
|
|
109
|
-
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,
|
|
110
|
+
`)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Ca)}" (input)`);r.push(`Form inputs:
|
|
110
111
|
${a.join(`
|
|
111
|
-
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,
|
|
112
|
+
`)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Ca)}"`);r.push(`Content:
|
|
112
113
|
${a.join(`
|
|
113
|
-
`)}`)}return
|
|
114
|
+
`)}`)}return r.join(`
|
|
114
115
|
|
|
115
|
-
`)}var
|
|
116
|
+
`)}var Bp={name:"@runtypelabs/persona",version:"3.17.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./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"},"./testing":{types:"./dist/testing.d.ts",import:"./dist/testing.js",require:"./dist/testing.cjs"},"./animations/glyph-cycle":{types:"./dist/animations/glyph-cycle.d.ts",import:"./dist/animations/glyph-cycle.js",require:"./dist/animations/glyph-cycle.cjs"},"./animations/wipe":{types:"./dist/animations/wipe.d.ts",import:"./dist/animations/wipe.js",require:"./dist/animations/wipe.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 && pnpm run build:testing && pnpm run build:animations","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:testing":"tsup src/testing.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:animations":"tsup src/animations/glyph-cycle.ts src/animations/wipe.ts --format esm,cjs --dts --out-dir dist/animations --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 --minify --sourcemap --splitting false --dts --loader ".css=text" && tsup src/index-global.ts --format iife --global-name AgentWidget --minify --sourcemap --splitting false --out-dir dist --loader ".css=text" && node -e "const fs=require('fs');for(const ext of ['.global.js','.global.js.map']){const from='dist/index-global'+ext;if(fs.existsSync(from))fs.renameSync(from,'dist/index'+ext);}"`,"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 no=Bp.version;function gr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function ag(e){if(e)return{getHeaders:gr(e.getHeaders),onFeedback:gr(e.onFeedback),onCopy:gr(e.onCopy),requestMiddleware:gr(e.requestMiddleware),actionHandlers:gr(e.actionHandlers),actionParsers:gr(e.actionParsers),postprocessMessage:gr(e.postprocessMessage),contextProviders:gr(e.contextProviders),streamParser:gr(e.streamParser)}}var Dp=`({ text, message }: any) => {
|
|
116
117
|
const jsonSource = (message as any).rawContent || text || message.content;
|
|
117
118
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
118
119
|
let cleanJson = jsonSource
|
|
@@ -125,7 +126,7 @@ ${a.join(`
|
|
|
125
126
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
126
127
|
} catch (e) { return null; }
|
|
127
128
|
return null;
|
|
128
|
-
}`,
|
|
129
|
+
}`,Np=`function(ctx) {
|
|
129
130
|
var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
|
|
130
131
|
if (!jsonSource || typeof jsonSource !== 'string') return null;
|
|
131
132
|
var cleanJson = jsonSource
|
|
@@ -138,7 +139,7 @@ ${a.join(`
|
|
|
138
139
|
if (parsed.action) return { type: parsed.action, payload: parsed };
|
|
139
140
|
} catch (e) { return null; }
|
|
140
141
|
return null;
|
|
141
|
-
}`,
|
|
142
|
+
}`,Fp=`(action: any, context: any) => {
|
|
142
143
|
if (action.type !== 'nav_then_click') return;
|
|
143
144
|
const payload = action.payload || action.raw || {};
|
|
144
145
|
const url = payload?.page;
|
|
@@ -155,7 +156,7 @@ ${a.join(`
|
|
|
155
156
|
const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
156
157
|
window.location.href = targetUrl;
|
|
157
158
|
return { handled: true, displayText: text };
|
|
158
|
-
}`,
|
|
159
|
+
}`,Op=`function(action, context) {
|
|
159
160
|
if (action.type !== 'nav_then_click') return;
|
|
160
161
|
var payload = action.payload || action.raw || {};
|
|
161
162
|
var url = payload.page;
|
|
@@ -172,26 +173,26 @@ ${a.join(`
|
|
|
172
173
|
var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
|
|
173
174
|
window.location.href = targetUrl;
|
|
174
175
|
return { handled: true, displayText: text };
|
|
175
|
-
}`,
|
|
176
|
+
}`,ig=`(parsed: any) => {
|
|
176
177
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
177
178
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
178
179
|
if (parsed.action === 'message') return parsed.text || '';
|
|
179
180
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
180
181
|
return parsed.text || null;
|
|
181
|
-
}`,
|
|
182
|
+
}`,lg=`function(parsed) {
|
|
182
183
|
if (!parsed || typeof parsed !== 'object') return null;
|
|
183
184
|
if (parsed.action === 'nav_then_click') return 'Navigating...';
|
|
184
185
|
if (parsed.action === 'message') return parsed.text || '';
|
|
185
186
|
if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
|
|
186
187
|
return parsed.text || null;
|
|
187
|
-
}`;function
|
|
188
|
-
`)}function
|
|
189
|
-
`)}function Rm(e,r){let t=r==null?void 0:r.hooks,n=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&n.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&n.push(` clientToken: "${e.clientToken}",`),e.flowId&&n.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Sr(n,"theme",e.theme," "),e.launcher&&Sr(n,"launcher",e.launcher," "),e.copy&&(n.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{n.push(` ${s}: "${o}",`)}),n.push(" },")),e.sendButton&&(n.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.voiceRecognition&&(n.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"?n.push(` ${s}: ${o},`):typeof o=="number"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.statusIndicator&&(n.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?n.push(` ${s}: "${o}",`):typeof o=="boolean"&&n.push(` ${s}: ${o},`)}),n.push(" },")),e.features&&(n.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{n.push(` ${s}: ${o},`)}),n.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(n.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{n.push(` "${s}",`)}),n.push(" ],")),e.suggestionChipsConfig&&(n.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&n.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&n.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&n.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&n.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),n.push(" },")),n.push(...sa(e," ")),n.push(...aa(e," ",t)),n.push(...ia(e," ")),n.push(...la(e," ")),t!=null&&t.getHeaders&&n.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&n.push(` contextProviders: ${t.contextProviders},`),e.debug&&n.push(` debug: ${e.debug},`),n.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?n.push(` streamParser: ${t.streamParser},`):(n.push(" // Flexible JSON stream parser for handling structured actions"),n.push(` streamParser: () => createFlexibleJsonStreamParser(${km}),`)),t!=null&&t.actionParsers?(n.push(" // Action parsers (custom merged with defaults)"),n.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),n.push(" // Built-in parser for markdown-wrapped JSON"),n.push(` ${gp}`),n.push(" ],")):(n.push(" // Action parsers to detect JSON actions in responses"),n.push(" actionParsers: ["),n.push(" defaultJsonActionParser,"),n.push(" // Parser for markdown-wrapped JSON"),n.push(` ${gp}`),n.push(" ],")),t!=null&&t.actionHandlers?(n.push(" // Action handlers (custom merged with defaults)"),n.push(` actionHandlers: [...(${t.actionHandlers}),`),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Built-in handler for nav_then_click action"),n.push(` ${hp}`),n.push(" ],")):(n.push(" // Action handlers for navigation and other actions"),n.push(" actionHandlers: ["),n.push(" defaultActionHandlers.message,"),n.push(" defaultActionHandlers.messageAndClick,"),n.push(" // Handler for nav_then_click action"),n.push(` ${hp}`),n.push(" ],")),t!=null&&t.postprocessMessage?n.push(` postprocessMessage: ${t.postprocessMessage},`):n.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(n.push(" // Request middleware (custom merged with DOM context)"),n.push(" requestMiddleware: ({ payload, config }) => {"),n.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),n.push(" const merged = customResult || payload;"),n.push(" return {"),n.push(" ...merged,"),n.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),n.push(" };"),n.push(" }")):(n.push(" requestMiddleware: ({ payload }) => {"),n.push(" return {"),n.push(" ...payload,"),n.push(" metadata: collectDOMContext()"),n.push(" };"),n.push(" }")),n.push(" }"),n.push(" });"),n.push(""),n.push(" // Save state on message events"),n.push(" const handleMessage = () => {"),n.push(" const session = handle?.getSession?.();"),n.push(" if (session) {"),n.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),n.push(" messages: session.messages,"),n.push(" timestamp: new Date().toISOString()"),n.push(" }));"),n.push(" }"),n.push(" };"),n.push(""),n.push(" // Clear state on clear chat"),n.push(" const handleClearChat = () => {"),n.push(" localStorage.removeItem(STORAGE_KEY);"),n.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),n.push(" };"),n.push(""),n.push(" window.addEventListener('persona:message', handleMessage);"),n.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),n.push(""),n.push(" // Cleanup on unmount"),n.push(" return () => {"),n.push(" window.removeEventListener('persona:message', handleMessage);"),n.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),n.push(" if (handle) {"),n.push(" handle.destroy();"),n.push(" }"),n.push(" };"),n.push(" }, []);"),n.push(""),n.push(" return null; // Widget injects itself into the DOM"),n.push("}"),n.push(""),n.push("// Usage: Collects DOM context for AI-powered navigation"),n.push("// Features:"),n.push("// - Extracts page elements (products, buttons, links)"),n.push("// - Persists chat history across page loads"),n.push("// - Handles navigation actions (nav_then_click)"),n.push("// - Processes structured JSON actions from AI"),n.push("//"),n.push("// Example usage in Next.js:"),n.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),n.push("//"),n.push("// export default function RootLayout({ children }) {"),n.push("// return ("),n.push('// <html lang="en">'),n.push("// <body>"),n.push("// {children}"),n.push("// <ChatWidgetAdvanced />"),n.push("// </body>"),n.push("// </html>"),n.push("// );"),n.push("// }"),n.join(`
|
|
190
|
-
`)}function
|
|
191
|
-
`)}function
|
|
188
|
+
}`;function cg(e){if(!e)return null;let n=e.toString();return n.includes("createJsonStreamParser")||n.includes("partial-json")?"json":n.includes("createRegexJsonParser")||n.includes("regex")?"regex-json":n.includes("createXmlParser")||n.includes("<text>")?"xml":null}function wa(e){var n,t;return(t=(n=e.parserType)!=null?n:cg(e.streamParser))!=null?t:"plain"}function Sa(e,n){let t=[];return e.toolCall&&(t.push(`${n}toolCall: {`),Object.entries(e.toolCall).forEach(([r,s])=>{typeof s=="string"&&t.push(`${n} ${r}: "${s}",`)}),t.push(`${n}},`)),t}function Aa(e,n,t){let r=[],s=e.messageActions&&Object.entries(e.messageActions).some(([a,i])=>a!=="onFeedback"&&a!=="onCopy"&&i!==void 0),o=(t==null?void 0:t.onFeedback)||(t==null?void 0:t.onCopy);return(s||o)&&(r.push(`${n}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?r.push(`${n} ${a}: "${i}",`):typeof i=="boolean"&&r.push(`${n} ${a}: ${i},`))}),t!=null&&t.onFeedback&&r.push(`${n} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&r.push(`${n} onCopy: ${t.onCopy},`),r.push(`${n}},`)),r}function Ea(e,n){let t=[];if(e.markdown){let r=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(r||s)&&(t.push(`${n}markdown: {`),r&&(t.push(`${n} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`)}),t.push(`${n} },`)),s&&t.push(`${n} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${n}},`))}return t}function Ta(e,n){let t=[];if(e.layout){let r=e.layout.header&&Object.keys(e.layout.header).some(o=>o!=="render"),s=e.layout.messages&&Object.keys(e.layout.messages).some(o=>o!=="renderUserMessage"&&o!=="renderAssistantMessage");(r||s)&&(t.push(`${n}layout: {`),r&&(t.push(`${n} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),s&&(t.push(`${n} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${n} avatar: {`),Object.entries(a).forEach(([i,u])=>{typeof u=="string"?t.push(`${n} ${i}: "${u}",`):typeof u=="boolean"&&t.push(`${n} ${i}: ${u},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([u])=>u!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([u,c])=>{u!=="format"&&(typeof c=="string"?t.push(`${n} ${u}: "${c}",`):typeof c=="boolean"&&t.push(`${n} ${u}: ${c},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function bi(e,n){let t=[];return e&&(e.getHeaders&&t.push(`${n}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${n}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${n}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${n}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${n}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${n}streamParser: ${e.streamParser},`)),t}function $p(e,n,t){Object.entries(n).forEach(([r,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${r}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${r}: {`),$p(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function Wr(e,n,t,r){t&&(e.push(`${r}${n}: {`),$p(e,t,`${r} `),e.push(`${r}},`))}function _p(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:ag(t.hooks)}:void 0;return n==="esm"?dg(r,s):n==="script-installer"?mg(r,s):n==="script-advanced"?fg(r,s):n==="react-component"?pg(r,s):n==="react-advanced"?ug(r,s):gg(r,s)}function dg(e,n){let t=n==null?void 0:n.hooks,r=wa(e),s=r!=="plain",o=["import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","","initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Wr(o,"theme",e.theme," "),e.launcher&&Wr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Sa(e," ")),o.push(...Aa(e," ",t)),o.push(...Ea(e," ")),o.push(...Ta(e," ")),o.push(...bi(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push("});"),o.join(`
|
|
189
|
+
`)}function pg(e,n){let t=n==null?void 0:n.hooks,r=wa(e),s=r!=="plain",o=["// ChatWidget.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import { initAgentWidget, markdownPostprocessor } from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","export function ChatWidget() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Wr(o,"theme",e.theme," "),e.launcher&&Wr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Sa(e," ")),o.push(...Aa(e," ",t)),o.push(...Ea(e," ")),o.push(...Ta(e," ")),o.push(...bi(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push(""),o.push(" // Cleanup on unmount"),o.push(" return () => {"),o.push(" if (handle) {"),o.push(" handle.destroy();"),o.push(" }"),o.push(" };"),o.push(" }, []);"),o.push(""),o.push(" return null; // Widget injects itself into the DOM"),o.push("}"),o.push(""),o.push("// Usage in your app:"),o.push("// import { ChatWidget } from './components/ChatWidget';"),o.push("//"),o.push("// export default function App() {"),o.push("// return ("),o.push("// <div>"),o.push("// {/* Your app content */}"),o.push("// <ChatWidget />"),o.push("// </div>"),o.push("// );"),o.push("// }"),o.join(`
|
|
190
|
+
`)}function ug(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Wr(r,"theme",e.theme," "),e.launcher&&Wr(r,"launcher",e.launcher," "),e.copy&&(r.push(" copy: {"),Object.entries(e.copy).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.sendButton&&(r.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.voiceRecognition&&(r.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"?r.push(` ${s}: ${o},`):typeof o=="number"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.statusIndicator&&(r.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([s,o])=>{typeof o=="string"?r.push(` ${s}: "${o}",`):typeof o=="boolean"&&r.push(` ${s}: ${o},`)}),r.push(" },")),e.features&&(r.push(" features: {"),Object.entries(e.features).forEach(([s,o])=>{r.push(` ${s}: ${o},`)}),r.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(r.push(" suggestionChips: ["),e.suggestionChips.forEach(s=>{r.push(` "${s}",`)}),r.push(" ],")),e.suggestionChipsConfig&&(r.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&r.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&r.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&r.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&r.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),r.push(" },")),r.push(...Sa(e," ")),r.push(...Aa(e," ",t)),r.push(...Ea(e," ")),r.push(...Ta(e," ")),t!=null&&t.getHeaders&&r.push(` getHeaders: ${t.getHeaders},`),t!=null&&t.contextProviders&&r.push(` contextProviders: ${t.contextProviders},`),e.debug&&r.push(` debug: ${e.debug},`),r.push(" initialMessages: loadSavedMessages(),"),t!=null&&t.streamParser?r.push(` streamParser: ${t.streamParser},`):(r.push(" // Flexible JSON stream parser for handling structured actions"),r.push(` streamParser: () => createFlexibleJsonStreamParser(${ig}),`)),t!=null&&t.actionParsers?(r.push(" // Action parsers (custom merged with defaults)"),r.push(` actionParsers: [...(${t.actionParsers}), defaultJsonActionParser,`),r.push(" // Built-in parser for markdown-wrapped JSON"),r.push(` ${Dp}`),r.push(" ],")):(r.push(" // Action parsers to detect JSON actions in responses"),r.push(" actionParsers: ["),r.push(" defaultJsonActionParser,"),r.push(" // Parser for markdown-wrapped JSON"),r.push(` ${Dp}`),r.push(" ],")),t!=null&&t.actionHandlers?(r.push(" // Action handlers (custom merged with defaults)"),r.push(` actionHandlers: [...(${t.actionHandlers}),`),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Built-in handler for nav_then_click action"),r.push(` ${Fp}`),r.push(" ],")):(r.push(" // Action handlers for navigation and other actions"),r.push(" actionHandlers: ["),r.push(" defaultActionHandlers.message,"),r.push(" defaultActionHandlers.messageAndClick,"),r.push(" // Handler for nav_then_click action"),r.push(` ${Fp}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
|
|
191
|
+
`)}function jp(e){var s;let n=wa(e),t=n!=="plain",r={};if(e.apiUrl&&(r.apiUrl=e.apiUrl),e.clientToken&&(r.clientToken=e.clientToken),e.flowId&&(r.flowId=e.flowId),t&&(r.parserType=n),e.theme&&(r.theme=e.theme),e.launcher&&(r.launcher=e.launcher),e.copy&&(r.copy=e.copy),e.sendButton&&(r.sendButton=e.sendButton),e.voiceRecognition&&(r.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(r.statusIndicator=e.statusIndicator),e.features&&(r.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(r.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(r.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(r.debug=e.debug),e.toolCall){let o={};Object.entries(e.toolCall).forEach(([a,i])=>{typeof i=="string"&&(o[a]=i)}),Object.keys(o).length>0&&(r.toolCall=o)}if(e.messageActions){let o={};Object.entries(e.messageActions).forEach(([a,i])=>{a!=="onFeedback"&&a!=="onCopy"&&i!==void 0&&(typeof i=="string"||typeof i=="boolean")&&(o[a]=i)}),Object.keys(o).length>0&&(r.messageActions=o)}if(e.markdown){let o={};e.markdown.options&&(o.options=e.markdown.options),e.markdown.disableDefaultStyles!==void 0&&(o.disableDefaultStyles=e.markdown.disableDefaultStyles),Object.keys(o).length>0&&(r.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,u])=>{i!=="render"&&(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,u])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof u=="object"&&u!==null)a.avatar=u;else if(i==="timestamp"&&typeof u=="object"&&u!==null){let c={};Object.entries(u).forEach(([p,d])=>{p!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[p]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof u=="string"||typeof u=="boolean")&&(a[i]=u)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function mg(e,n){let t=jp(e),r=n!=null&&n.windowKey?{config:t,windowKey:n.windowKey}:t,s=JSON.stringify(r,null,0).replace(/'/g,"'");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${no}/dist/install.global.js" data-config='${s}'></script>`}function gg(e,n){let t=n==null?void 0:n.hooks,r=wa(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${no}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${no}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," var handle = window.AgentWidget.initAgentWidget({"," target: 'body',",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: {"];return e.apiUrl&&o.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&o.push(` clientToken: "${e.clientToken}",`),e.flowId&&o.push(` flowId: "${e.flowId}",`),s&&o.push(` parserType: "${r}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&Wr(o,"theme",e.theme," "),e.launcher&&Wr(o,"launcher",e.launcher," "),e.copy&&(o.push(" copy: {"),Object.entries(e.copy).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.sendButton&&(o.push(" sendButton: {"),Object.entries(e.sendButton).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.voiceRecognition&&(o.push(" voiceRecognition: {"),Object.entries(e.voiceRecognition).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"?o.push(` ${a}: ${i},`):typeof i=="number"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.statusIndicator&&(o.push(" statusIndicator: {"),Object.entries(e.statusIndicator).forEach(([a,i])=>{typeof i=="string"?o.push(` ${a}: "${i}",`):typeof i=="boolean"&&o.push(` ${a}: ${i},`)}),o.push(" },")),e.features&&(o.push(" features: {"),Object.entries(e.features).forEach(([a,i])=>{o.push(` ${a}: ${i},`)}),o.push(" },")),e.suggestionChips&&e.suggestionChips.length>0&&(o.push(" suggestionChips: ["),e.suggestionChips.forEach(a=>{o.push(` "${a}",`)}),o.push(" ],")),e.suggestionChipsConfig&&(o.push(" suggestionChipsConfig: {"),e.suggestionChipsConfig.fontFamily&&o.push(` fontFamily: "${e.suggestionChipsConfig.fontFamily}",`),e.suggestionChipsConfig.fontWeight&&o.push(` fontWeight: "${e.suggestionChipsConfig.fontWeight}",`),e.suggestionChipsConfig.paddingX&&o.push(` paddingX: "${e.suggestionChipsConfig.paddingX}",`),e.suggestionChipsConfig.paddingY&&o.push(` paddingY: "${e.suggestionChipsConfig.paddingY}",`),o.push(" },")),o.push(...Sa(e," ")),o.push(...Aa(e," ",t)),o.push(...Ea(e," ")),o.push(...Ta(e," ")),o.push(...bi(t," ")),e.debug&&o.push(` debug: ${e.debug},`),t!=null&&t.postprocessMessage?o.push(` postprocessMessage: ${t.postprocessMessage}`):o.push(" postprocessMessage: ({ text }) => window.AgentWidget.markdownPostprocessor(text)"),o.push(" }"),o.push(" });"),o.push("</script>"),o.join(`
|
|
192
|
+
`)}function fg(e,n){let t=n==null?void 0:n.hooks,r=jp(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
|
|
192
193
|
`).map((a,i)=>i===0?a:" "+a).join(`
|
|
193
|
-
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${
|
|
194
|
-
`)}var
|
|
194
|
+
`)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${no}/dist';`," var STORAGE_KEY = 'chat-widget-state';"," var PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';",""," // DOM context provider - extracts page elements for AI context"," var domContextProvider = function() {"," var selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," var elements = [];"," Object.entries(selectors).forEach(function(entry) {"," var type = entry[0], selector = entry[1];"," document.querySelectorAll(selector).forEach(function(element) {"," if (!(element instanceof HTMLElement)) return;"," var widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," var text = element.innerText ? element.innerText.trim() : '';"," if (!text) return;",""," var selectorString = element.id ? '#' + element.id :",` element.getAttribute('data-testid') ? '[data-testid="' + element.getAttribute('data-testid') + '"]' :`,` element.getAttribute('data-product-id') ? '[data-product-id="' + element.getAttribute('data-product-id') + '"]' :`," element.tagName.toLowerCase();",""," var elementData = {"," type: type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }"," elements.push(elementData);"," });"," });",""," var counts = elements.reduce(function(acc, el) {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {});",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };"," };",""," // Load CSS dynamically"," var loadCSS = function() {"," if (document.querySelector('link[data-persona]')) return;"," var link = document.createElement('link');"," link.rel = 'stylesheet';"," link.href = CDN_BASE + '/widget.css';"," link.setAttribute('data-persona', 'true');"," document.head.appendChild(link);"," };",""," // Load JS dynamically"," var loadJS = function(callback) {"," if (window.AgentWidget) { callback(); return; }"," var script = document.createElement('script');"," script.src = CDN_BASE + '/index.global.js';"," script.onload = callback;"," script.onerror = function() { console.error('Failed to load AgentWidget'); };"," document.head.appendChild(script);"," };",""," // Create widget config with advanced features"," var createWidgetConfig = function(agentWidget) {"," var widgetConfig = Object.assign({}, CONFIG);",""];return t!=null&&t.getHeaders&&(o.push(` widgetConfig.getHeaders = ${t.getHeaders};`),o.push("")),t!=null&&t.contextProviders&&(o.push(` widgetConfig.contextProviders = ${t.contextProviders};`),o.push("")),t!=null&&t.streamParser?o.push(` widgetConfig.streamParser = ${t.streamParser};`):(o.push(" // Flexible JSON stream parser for handling structured actions"),o.push(" widgetConfig.streamParser = function() {"),o.push(` return agentWidget.createFlexibleJsonStreamParser(${lg});`),o.push(" };")),o.push(""),t!=null&&t.actionParsers?(o.push(" // Action parsers (custom merged with defaults)"),o.push(` var customParsers = ${t.actionParsers};`),o.push(" widgetConfig.actionParsers = customParsers.concat(["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Np}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Np}`),o.push(" ];")),o.push(""),t!=null&&t.actionHandlers?(o.push(" // Action handlers (custom merged with defaults)"),o.push(` var customHandlers = ${t.actionHandlers};`),o.push(" widgetConfig.actionHandlers = customHandlers.concat(["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Op}`),o.push(" ]);")):(o.push(" // Action handlers for navigation and other actions"),o.push(" widgetConfig.actionHandlers = ["),o.push(" agentWidget.defaultActionHandlers.message,"),o.push(" agentWidget.defaultActionHandlers.messageAndClick,"),o.push(` ${Op}`),o.push(" ];")),o.push(""),t!=null&&t.requestMiddleware?(o.push(" // Request middleware (custom merged with DOM context)"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(` var customResult = (${t.requestMiddleware})(ctx);`),o.push(" var merged = customResult || ctx.payload;"),o.push(" return Object.assign({}, merged, { metadata: Object.assign({}, merged.metadata, domContextProvider()) });"),o.push(" };")):(o.push(" // Send DOM context with each request"),o.push(" widgetConfig.requestMiddleware = function(ctx) {"),o.push(" return Object.assign({}, ctx.payload, { metadata: domContextProvider() });"),o.push(" };")),o.push(""),t!=null&&t.postprocessMessage?o.push(` widgetConfig.postprocessMessage = ${t.postprocessMessage};`):(o.push(" // Markdown postprocessor"),o.push(" widgetConfig.postprocessMessage = function(ctx) {"),o.push(" return agentWidget.markdownPostprocessor(ctx.text);"),o.push(" };")),o.push(""),(t!=null&&t.onFeedback||t!=null&&t.onCopy)&&(o.push(" // Message action callbacks"),o.push(" widgetConfig.messageActions = widgetConfig.messageActions || {};"),t!=null&&t.onFeedback&&o.push(` widgetConfig.messageActions.onFeedback = ${t.onFeedback};`),t!=null&&t.onCopy&&o.push(` widgetConfig.messageActions.onCopy = ${t.onCopy};`),o.push("")),o.push(" return widgetConfig;"," };",""," // Initialize widget"," var init = function() {"," var agentWidget = window.AgentWidget;"," if (!agentWidget) {"," console.error('AgentWidget not loaded');"," return;"," }",""," var widgetConfig = createWidgetConfig(agentWidget);",""," // Load saved state"," var savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," var parsed = JSON.parse(savedState);"," widgetConfig.initialMessages = parsed.messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }",""," // Initialize widget"," var handle = agentWidget.initAgentWidget({"," target: 'body',"," useShadowDom: false,",...n!=null&&n.windowKey?[` windowKey: '${n.windowKey}',`]:[]," config: widgetConfig"," });",""," // Save state on message events"," window.addEventListener('persona:message', function() {"," var session = handle.getSession ? handle.getSession() : null;"," if (session) {"," localStorage.setItem(STORAGE_KEY, JSON.stringify({"," messages: session.messages,"," timestamp: new Date().toISOString()"," }));"," }"," });",""," // Clear state on clear chat"," window.addEventListener('persona:clear-chat', function() {"," localStorage.removeItem(STORAGE_KEY);"," localStorage.removeItem(PROCESSED_ACTIONS_KEY);"," });"," };",""," // Wait for framework hydration to complete (Next.js, Nuxt, etc.)"," // This prevents the framework from removing dynamically added CSS during reconciliation"," var waitForHydration = function(callback) {"," var executed = false;"," "," var execute = function() {"," if (executed) return;"," executed = true;"," callback();"," };",""," var afterDom = function() {"," // Strategy 1: Use requestIdleCallback if available (best for detecting idle after hydration)"," if (typeof requestIdleCallback !== 'undefined') {"," requestIdleCallback(function() {"," // Double requestAnimationFrame ensures at least one full paint cycle completed"," requestAnimationFrame(function() {"," requestAnimationFrame(execute);"," });"," }, { timeout: 3000 }); // Max wait 3 seconds, then proceed anyway"," } else {"," // Strategy 2: Fallback for Safari (no requestIdleCallback)"," // 300ms is typically enough for hydration on most pages"," setTimeout(execute, 300);"," }"," };",""," if (document.readyState === 'loading') {"," document.addEventListener('DOMContentLoaded', afterDom);"," } else {"," // DOM already ready, but still wait for potential hydration"," afterDom();"," }"," };",""," // Boot sequence: wait for hydration, then load CSS and JS, then initialize"," // This prevents Next.js/Nuxt/etc. from removing dynamically added CSS during reconciliation"," waitForHydration(function() {"," loadCSS();"," loadJS(function() {"," init();"," });"," });","})();","</script>"),o.join(`
|
|
195
|
+
`)}var zp={desktop:{w:1280,h:800},mobile:{w:390,h:844}},qp=.1,Vp=.15,Up=1.5,xi=24,Jp=40,hg=`
|
|
195
196
|
/* \u2500\u2500 Root \u2500\u2500 */
|
|
196
197
|
.persona-dc-root {
|
|
197
198
|
display: flex;
|
|
@@ -342,7 +343,7 @@ ${a.join(`
|
|
|
342
343
|
.persona-dc-stage {
|
|
343
344
|
height: 550px;
|
|
344
345
|
min-height: 400px;
|
|
345
|
-
padding: ${
|
|
346
|
+
padding: ${xi}px;
|
|
346
347
|
overflow: auto;
|
|
347
348
|
background: #f0f1f3;
|
|
348
349
|
background-image: radial-gradient(circle, #e0e1e5 1px, transparent 1px);
|
|
@@ -432,5 +433,5 @@ ${a.join(`
|
|
|
432
433
|
min-height: 300px;
|
|
433
434
|
}
|
|
434
435
|
}
|
|
435
|
-
`;function Fm(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=Nm,document.head.appendChild(e)}function Om(e,r){let t=e.clientWidth-Ka*2-Ep,n=e.clientHeight-Ka*2-Ep;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function $m(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function Tp(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");Fm();let p=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,g=null,x=1,T=!1,C=h("div","persona-dc-root"),S=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),H=h("div","persona-dc-toolbar-trail"),w=It({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Be(-1)}),L=h("div");L.style.position="relative";let W=h("button","persona-dc-title-btn");W.type="button",W.setAttribute("aria-expanded","false"),W.setAttribute("aria-haspopup","listbox");let E=h("span","persona-dc-title-text"),K=h("span","persona-dc-title-chevron"),Q=ye("chevron-down",12,"currentColor",2);Q&&K.appendChild(Q),W.append(E,K);let X=h("div","persona-dc-dropdown");X.setAttribute("role","listbox"),X.style.display="none";let O=!1;function oe(){X.innerHTML="";for(let N=0;N<t.length;N++){let J=t[N],ce=h("button","persona-dc-dropdown-item");ce.type="button",ce.setAttribute("role","option"),ce.setAttribute("aria-current",N===p?"true":"false");let fe=h("span");if(fe.textContent=J.title,ce.appendChild(fe),J.description){let te=h("span","persona-dc-dropdown-desc");te.textContent=J.description,ce.appendChild(te)}ce.addEventListener("click",()=>{ae(),st(N)}),X.appendChild(ce)}}function Ee(){O=!O,X.style.display=O?"":"none",W.setAttribute("aria-expanded",O?"true":"false"),O&&oe()}function ae(){O&&(O=!1,X.style.display="none",W.setAttribute("aria-expanded","false"))}W.addEventListener("click",N=>{N.stopPropagation(),Ee()});let we=()=>ae();document.addEventListener("click",we),L.append(W,X);let $e=It({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Be(1)}),he=h("span","persona-dc-counter");M.append(w,L,$e,he);let We=null;i&&(We=Jo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:N=>{d=N,V.dataset.device=d,g=null,z()}}),H.appendChild(We.element));let Re=null;if(a){let N=h("div","persona-dc-zoom-controls"),J=It({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let te=g!=null?g:x;g=Math.max(Sp,te-wp),z()}});Re=h("span","persona-dc-zoom-level"),Re.title="Reset to 100%",Re.style.cursor="pointer",Re.addEventListener("click",()=>{g=1,z()});let ce=It({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let te=g!=null?g:x;g=Math.min(Ap,te+wp),z()}}),fe=It({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,z()}});N.append(J,Re,ce,fe),H.appendChild(N)}if(u){let N=h("div","persona-dc-separator");H.appendChild(N);let J=Jo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:ce=>{f=ce,V.dataset.colorScheme=f,He()}});H.appendChild(J.element)}let ie=h("div","persona-dc-separator");H.appendChild(ie);let Z=It({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});H.appendChild(Z),S.append(M,H);let me=h("div","persona-dc-stage"),V=h("div","persona-dc-iframe-wrapper");V.dataset.device=d,V.dataset.colorScheme=f;let re=h("iframe","persona-dc-iframe");re.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),re.setAttribute("loading","lazy"),re.title=t[p].title,V.appendChild(re),me.appendChild(V),C.append(S,me),e.appendChild(C);function He(){var N;try{let J=(N=re.contentDocument)==null?void 0:N.body;if(!J)return;f==="dark"?J.classList.add("theme-dark"):J.classList.remove("theme-dark")}catch{}}re.addEventListener("load",()=>He());function ge(){let N=t[p];E.textContent=N.title,he.textContent=`${p+1} / ${t.length}`,re.title=N.title}function Be(N){let J=((p+N)%t.length+t.length)%t.length;st(J)}function st(N){N<0||N>=t.length||(p=N,re.src=t[p].url,ge(),c==null||c(p,t[p]))}function z(){var ce;if(T)return;let N=(ce=Cp[d])!=null?ce:Cp.desktop;x=Om(me,N);let J=Math.max(Sp,Math.min(Ap,g!=null?g:x));$m(V,re,N,J,d),Re&&(Re.textContent=`${Math.round(J*100)}%`)}let U=new ResizeObserver(()=>z());U.observe(me),ge(),re.src=t[p].url,requestAnimationFrame(()=>z());function se(){T||(T=!0,U.disconnect(),document.removeEventListener("click",we),C.remove())}return{element:C,goTo:st,next:()=>Be(1),prev:()=>Be(-1),getIndex:()=>p,setDevice(N){d=N,V.dataset.device=N,We==null||We.setSelected(N),g=null,z()},setColorScheme(N){f=N,V.dataset.colorScheme=N},setZoom(N){g=N,z()},destroy:se}}function Mp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function kp(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Lp(e){return{name:"@persona/brand",version:"1.0.0",transform(r){var n;let t={...r.palette};return(n=e.colors)!=null&&n.primary&&(t.colors={...t.colors,primary:{50:Yn(e.colors.primary,.95),100:Yn(e.colors.primary,.9),200:Yn(e.colors.primary,.8),300:Yn(e.colors.primary,.7),400:Yn(e.colors.primary,.6),500:e.colors.primary,600:Yn(e.colors.primary,.8),700:Yn(e.colors.primary,.7),800:Yn(e.colors.primary,.6),900:Yn(e.colors.primary,.5),950:Yn(e.colors.primary,.45)}}),{...r,palette:t}}}}function Ip(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Pp(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Yn(e,r){let t=parseInt(e.slice(1,3),16),n=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-r)),a=Math.round(n+(255-n)*(1-r)),i=Math.round(s+(255-s)*(1-r));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Wp(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var _m={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},Rp={components:{panel:{borderRadius:"0",shadow:"none"}}},Xa={id:"shop",label:"Shopping Assistant",config:{theme:_m,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:An},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Za={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Rp}},Qa={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Rp}},ei={shop:Xa,minimal:Za,fullscreen:Qa};function Hp(e){return ei[e]}var jm=za;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,validateImageFile,validateTheme});
|
|
436
|
+
`;function yg(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=hg,document.head.appendChild(e)}function bg(e,n){let t=e.clientWidth-xi*2-Jp,r=e.clientHeight-xi*2-Jp;return t<=0||r<=0?1:Math.min(t/n.w,r/n.h,1)}function xg(e,n,t,r,s){e.style.width=`${t.w*r}px`,e.style.height=`${t.h*r}px`,e.style.borderRadius=s==="mobile"?`${32*r}px`:"10px",n.style.width=`${t.w}px`,n.style.height=`${t.h}px`,n.style.transformOrigin="top left",n.style.transform=`scale(${r})`}function Kp(e,n){let{items:t,initialIndex:r=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:u=!0,onChange:c}=n;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");yg();let p=Math.max(0,Math.min(r,t.length-1)),d=s,f=o,g=null,x=1,E=!1,v=h("div","persona-dc-root"),w=h("div","persona-dc-toolbar"),I=h("div","persona-dc-toolbar-lead"),j=h("div","persona-dc-toolbar-trail"),A=Ht({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>Te(-1)}),R=h("div");R.style.position="relative";let T=h("button","persona-dc-title-btn");T.type="button",T.setAttribute("aria-expanded","false"),T.setAttribute("aria-haspopup","listbox");let P=h("span","persona-dc-title-text"),H=h("span","persona-dc-title-chevron"),J=ye("chevron-down",12,"currentColor",2);J&&H.appendChild(J),T.append(P,H);let U=h("div","persona-dc-dropdown");U.setAttribute("role","listbox"),U.style.display="none";let $=!1;function ie(){U.innerHTML="";for(let D=0;D<t.length;D++){let q=t[D],le=h("button","persona-dc-dropdown-item");le.type="button",le.setAttribute("role","option"),le.setAttribute("aria-current",D===p?"true":"false");let xe=h("span");if(xe.textContent=q.title,le.appendChild(xe),q.description){let ee=h("span","persona-dc-dropdown-desc");ee.textContent=q.description,le.appendChild(ee)}le.addEventListener("click",()=>{pe(),Me(D)}),U.appendChild(le)}}function be(){$=!$,U.style.display=$?"":"none",T.setAttribute("aria-expanded",$?"true":"false"),$&&ie()}function pe(){$&&($=!1,U.style.display="none",T.setAttribute("aria-expanded","false"))}T.addEventListener("click",D=>{D.stopPropagation(),be()});let Ne=()=>pe();document.addEventListener("click",Ne),R.append(T,U);let me=Ht({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>Te(1)}),Re=h("span","persona-dc-counter");I.append(A,R,me,Re);let Ee=null;i&&(Ee=ds({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:D=>{d=D,X.dataset.device=d,g=null,k()}}),j.appendChild(Ee.element));let He=null;if(a){let D=h("div","persona-dc-zoom-controls"),q=Ht({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let ee=g!=null?g:x;g=Math.max(Vp,ee-qp),k()}});He=h("span","persona-dc-zoom-level"),He.title="Reset to 100%",He.style.cursor="pointer",He.addEventListener("click",()=>{g=1,k()});let le=Ht({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let ee=g!=null?g:x;g=Math.min(Up,ee+qp),k()}}),xe=Ht({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{g=null,k()}});D.append(q,He,le,xe),j.appendChild(D)}if(u){let D=h("div","persona-dc-separator");j.appendChild(D);let q=ds({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:le=>{f=le,X.dataset.colorScheme=f,ue()}});j.appendChild(q.element)}let de=h("div","persona-dc-separator");j.appendChild(de);let Q=Ht({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[p].url,"_blank")}});j.appendChild(Q),w.append(I,j);let he=h("div","persona-dc-stage"),X=h("div","persona-dc-iframe-wrapper");X.dataset.device=d,X.dataset.colorScheme=f;let ge=h("iframe","persona-dc-iframe");ge.setAttribute("sandbox","allow-scripts allow-same-origin allow-forms"),ge.setAttribute("loading","lazy"),ge.title=t[p].title,X.appendChild(ge),he.appendChild(X),v.append(w,he),e.appendChild(v);function ue(){var D;try{let q=(D=ge.contentDocument)==null?void 0:D.body;if(!q)return;f==="dark"?q.classList.add("theme-dark"):q.classList.remove("theme-dark")}catch{}}ge.addEventListener("load",()=>ue());function oe(){let D=t[p];P.textContent=D.title,Re.textContent=`${p+1} / ${t.length}`,ge.title=D.title}function Te(D){let q=((p+D)%t.length+t.length)%t.length;Me(q)}function Me(D){D<0||D>=t.length||(p=D,ge.src=t[p].url,oe(),c==null||c(p,t[p]))}function k(){var le;if(E)return;let D=(le=zp[d])!=null?le:zp.desktop;x=bg(he,D);let q=Math.max(Vp,Math.min(Up,g!=null?g:x));xg(X,ge,D,q,d),He&&(He.textContent=`${Math.round(q*100)}%`)}let V=new ResizeObserver(()=>k());V.observe(he),oe(),ge.src=t[p].url,requestAnimationFrame(()=>k());function ae(){E||(E=!0,V.disconnect(),document.removeEventListener("click",Ne),v.remove())}return{element:v,goTo:Me,next:()=>Te(1),prev:()=>Te(-1),getIndex:()=>p,setDevice(D){d=D,X.dataset.device=D,Ee==null||Ee.setSelected(D),g=null,k()},setColorScheme(D){f=D,X.dataset.colorScheme=D},setZoom(D){g=D,k()},destroy:ae}}function Gp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function Yp(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function Xp(e){return{name:"@persona/brand",version:"1.0.0",transform(n){var r;let t={...n.palette};return(r=e.colors)!=null&&r.primary&&(t.colors={...t.colors,primary:{50:tr(e.colors.primary,.95),100:tr(e.colors.primary,.9),200:tr(e.colors.primary,.8),300:tr(e.colors.primary,.7),400:tr(e.colors.primary,.6),500:e.colors.primary,600:tr(e.colors.primary,.8),700:tr(e.colors.primary,.7),800:tr(e.colors.primary,.6),900:tr(e.colors.primary,.5),950:tr(e.colors.primary,.45)}}),{...n,palette:t}}}}function Zp(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function Qp(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function tr(e,n){let t=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(t+(255-t)*(1-n)),a=Math.round(r+(255-r)*(1-n)),i=Math.round(s+(255-s)*(1-n));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function eu(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var vg={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},tu={components:{panel:{borderRadius:"0",shadow:"none"}}},vi={id:"shop",label:"Shopping Assistant",config:{theme:vg,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:Pn},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},Ci={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:tu}},wi={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:tu}},Si={shop:vi,minimal:Ci,fullscreen:wi};function nu(e){return Si[e]}var Cg=ui;0&&(module.exports={AgentWidgetClient,AgentWidgetSession,AttachmentManager,DEFAULT_COMPONENTS,DEFAULT_FLOATING_LAUNCHER_MAX_WIDTH,DEFAULT_FLOATING_LAUNCHER_WIDTH,DEFAULT_PALETTE,DEFAULT_SEMANTIC,DEFAULT_WIDGET_CONFIG,PRESETS,PRESET_FULLSCREEN,PRESET_MINIMAL,PRESET_SHOP,THEME_ZONES,VERSION,accessibilityPlugin,animationsPlugin,applyThemeVariables,attachHeaderToContainer,brandPlugin,buildComposer,buildDefaultHeader,buildHeader,buildHeaderWithLayout,buildMinimalHeader,collectEnrichedPageContext,componentRegistry,createActionManager,createAgentExperience,createBestAvailableVoiceProvider,createBubbleWithLayout,createCSATFeedback,createComboButton,createComponentMiddleware,createComponentStreamParser,createDefaultSanitizer,createDemoCarousel,createDirectivePostprocessor,createDropdownMenu,createFlexibleJsonStreamParser,createIconButton,createImagePart,createJsonStreamParser,createLabelButton,createLocalStorageAdapter,createMarkdownProcessor,createMarkdownProcessorFromConfig,createMessageActions,createNPSFeedback,createPlainTextParser,createPlugin,createRegexJsonParser,createStandardBubble,createTextPart,createTheme,createThemeObserver,createToggleGroup,createTypingIndicator,createVoiceProvider,createWidgetHostLayout,createXmlParser,defaultActionHandlers,defaultJsonActionParser,defaultParseRules,detectColorScheme,directivePostprocessor,escapeHtml,extractComponentDirectiveFromMessage,fileToImagePart,formatEnrichedContext,generateAssistantMessageId,generateCodeSnippet,generateMessageId,generateStableSelector,generateUserMessageId,getActiveTheme,getColorScheme,getDisplayText,getHeaderLayout,getImageParts,getPreset,hasComponentDirective,hasImages,headerLayouts,highContrastPlugin,initAgentWidget,isComponentDirectiveType,isDockedMountMode,isVoiceSupported,listRegisteredStreamAnimations,markdownPostprocessor,mergeWithDefaults,normalizeContent,pluginRegistry,reducedMotionPlugin,registerStreamAnimationPlugin,renderComponentDirective,renderLoadingIndicatorWithFallback,resolveDockConfig,resolveSanitizer,resolveTokens,themeToCssVariables,unregisterStreamAnimationPlugin,validateImageFile,validateTheme});
|
|
436
437
|
//# sourceMappingURL=index.cjs.map
|