@runtypelabs/persona 2.3.1 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +222 -5
  2. package/dist/index.cjs +42 -42
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +832 -571
  5. package/dist/index.d.ts +832 -571
  6. package/dist/index.global.js +88 -88
  7. package/dist/index.global.js.map +1 -1
  8. package/dist/index.js +42 -42
  9. package/dist/index.js.map +1 -1
  10. package/dist/widget.css +257 -67
  11. package/package.json +2 -4
  12. package/src/components/artifact-card.ts +39 -5
  13. package/src/components/artifact-pane.ts +68 -127
  14. package/src/components/composer-builder.ts +3 -23
  15. package/src/components/header-builder.ts +29 -34
  16. package/src/components/header-layouts.ts +109 -41
  17. package/src/components/launcher.ts +10 -7
  18. package/src/components/message-bubble.ts +7 -11
  19. package/src/components/panel.ts +4 -4
  20. package/src/defaults.ts +22 -93
  21. package/src/index.ts +20 -7
  22. package/src/presets.ts +66 -51
  23. package/src/runtime/host-layout.test.ts +333 -0
  24. package/src/runtime/host-layout.ts +346 -27
  25. package/src/runtime/init.test.ts +113 -8
  26. package/src/runtime/init.ts +1 -1
  27. package/src/styles/widget.css +257 -67
  28. package/src/types/theme.ts +76 -0
  29. package/src/types.ts +86 -97
  30. package/src/ui.docked.test.ts +203 -7
  31. package/src/ui.ts +125 -92
  32. package/src/utils/artifact-gate.ts +1 -1
  33. package/src/utils/buttons.ts +417 -0
  34. package/src/utils/code-generators.test.ts +43 -7
  35. package/src/utils/code-generators.ts +9 -25
  36. package/src/utils/deep-merge.ts +26 -0
  37. package/src/utils/dock.ts +18 -5
  38. package/src/utils/dropdown.ts +178 -0
  39. package/src/utils/theme.test.ts +90 -15
  40. package/src/utils/theme.ts +20 -46
  41. package/src/utils/tokens.ts +108 -11
  42. package/src/styles/tailwind.css +0 -20
  43. package/src/utils/migration.ts +0 -220
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=e==null?void 0:e.markedOptions,t=new Ac({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=Ec(e==null?void 0:e.renderer);return r&&t.use({renderer:r}),a=>t.parse(a)},lr=e=>e?Ao({markedOptions:e.options,renderer:e.renderer}):Ao(),Tc=Ao(),Ki=e=>Tc(e),_r=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),Yi=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),Ji=e=>`%%FORM_PLACEHOLDER_${e}%%`,Gi=(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=Ji(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=Ji(n.length);return n.push({token:o,type:s}),o}),t},Mc=e=>{let n=lr(e);return t=>{let r=[],s=Gi(t,r),o=n(s);return r.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),g=`<div class="persona-form-directive" data-tv-form="${Yi(i)}"></div>`;o=o.replace(d,g)}),o}},kc=e=>{let n=[],t=Gi(e,n),r=Ki(t);return n.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${Yi(o)}"></div>`;r=r.replace(a,d)}),r};import Lc from"dompurify";var Pc={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"]},Ic=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,Xi=()=>{let e=Lc(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:")&&!Ic.test(r)&&(t.attrValue="",t.keepAttr=!1)}}),n=>e.sanitize(n,Pc)},jr=e=>e===!1?null:typeof e=="function"?e:Xi();import{parse as Zi,STR as Qi,OBJ as el}from"partial-json";var Eo=e=>e.replace(/\\n/g,`
2
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Vr=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)}},Wc=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`},tl=e=>e.status==="complete"?Wc(e):e.status==="pending"?"Waiting":"",Rc=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 nl=e=>e.status==="complete"?Rc(e):"Using tool...",Hc=()=>{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()=>{}}},To=e=>{try{let n=JSON.parse(e);if(n&&typeof n=="object"&&typeof n.text=="string")return n.text}catch{return null}return null},Go=()=>{let e={processChunk:n=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Xo=()=>{var n;let e=Hc();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)}},Zo=()=>{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=Zi(t,Qi|el);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Eo(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Eo(s.text)))}catch{}return n=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},Bc=e=>{let n=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Eo(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Eo(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=Zi(o,Qi|el),d=s(i);d!==null&&(n=d)}catch{}return t=o.length,{text:n||"",raw:o}},close:()=>{}}},Qo=()=>{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 Fc="https://api.runtype.com/v1/dispatch",es="https://api.runtype.com",ts=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 $c(e){switch(e){case"json":return Zo;case"regex-json":return Xo;case"xml":return Qo;default:return Go}}var cr=class{constructor(n={}){this.config=n;this.clientSession=null;this.sessionInitPromise=null;var t,r,s;this.apiUrl=(t=n.apiUrl)!=null?t:Fc,this.headers={"Content-Type":"application/json",...n.headers},this.debug=!!n.debug,this.createStreamParser=(r=n.streamParser)!=null?r:$c(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$/,""))||es;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$/,""))||es}/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 d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(n.messages),g=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:n.messages.filter(ts).map(m=>{var C,v,E;return{id:m.id,role:m.role,content:(E=(v=(C=m.contentParts)!=null?C:m.llmContent)!=null?v:m.rawContent)!=null?E:m.content}}),...n.assistantMessageId&&{assistantMessageId:n.assistantMessageId},...g&&Object.keys(g).length>0&&{metadata:g},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:r.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let v=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:v}),v}if(f.status===429){let v=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:v}),v}let C=new Error(m.error||"Failed to send message");throw t({type:"error",error:C}),C}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,n.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(n,t){let r=new AbortController;n.signal&&n.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let 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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal: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 d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal: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$/,""))||es}/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(ts).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(ts).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){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(n);if(a===null)return!1;let i=()=>{if(r.current)return r.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return r.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(r.current&&(r.current.streaming=!1,s(r.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(n,t,r){var ut,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J,_,xe,Le,He,pt,ve,Ce,Be,ue,bt,Zt,un,gn,ro,Pn,Zn,Qe,mn,In,ln,Cr,fn,dt,nn,wn,wr,Qn,Sr,Nn,hn,On,xt,yn,Ar,Wn,bn,H,Rn,Hn,Er,Sn,Dn,Tr,An,En,er,tr,oo,so,ao,Mr,nr,Ue,kr,rn,Kt,io,lo,Lr,_n,Tn,co,po,uo,Jo,jn,rr,gt,or,sr,Pr,Ir,Wr,Rr,Ut,Qt,Mn,Re,Hr,Vn,cn,go,ar,ir,Un,Bn,mo,fo,dn,qn,ho;let s=n.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,g=Q=>{let Fe=Q.reasoning?{...Q.reasoning,chunks:[...Q.reasoning.chunks]}:void 0,we=Q.toolCall?{...Q.toolCall,chunks:Q.toolCall.chunks?[...Q.toolCall.chunks]:void 0}:void 0,$e=Q.tools?Q.tools.map(vt=>({...vt,chunks:vt.chunks?[...vt.chunks]:void 0})):void 0;return{...Q,reasoning:Fe,toolCall:we,tools:$e}},p=Q=>{t({type:"message",message:g(Q)})},f=null,m={current:null},C=new Map,v=new Map,E={lastId:null,byStep:new Map},x={lastId:null,byCall:new Map},k=Q=>{if(Q==null)return null;try{return String(Q)}catch{return null}},q=Q=>{var Fe,we,$e,vt,Ot;return k((Ot=(vt=($e=(we=(Fe=Q.stepId)!=null?Fe:Q.step_id)!=null?we:Q.step)!=null?$e:Q.parentId)!=null?vt:Q.flowStepId)!=null?Ot:Q.flow_step_id)},M=Q=>{var Fe,we,$e,vt,Ot,Ct,b;return k((b=(Ct=(Ot=(vt=($e=(we=(Fe=Q.callId)!=null?Fe:Q.call_id)!=null?we:Q.requestId)!=null?$e:Q.request_id)!=null?vt:Q.toolCallId)!=null?Ot:Q.tool_call_id)!=null?Ct:Q.stepId)!=null?b:Q.step_id)},N=()=>f||(f={id:r!=null?r:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),w=(Q,Fe)=>{E.lastId=Fe,Q&&E.byStep.set(Q,Fe)},F=(Q,Fe)=>{var Ot;let we=(Ot=Q.reasoningId)!=null?Ot:Q.id,$e=q(Q);if(we){let Ct=String(we);return w($e,Ct),Ct}if($e){let Ct=E.byStep.get($e);if(Ct)return E.lastId=Ct,Ct}if(E.lastId&&!Fe)return E.lastId;if(!Fe)return null;let vt=`reason-${c()}`;return w($e,vt),vt},re=Q=>{let Fe=C.get(Q);if(Fe)return Fe;let we={id:`reason-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Q,status:"streaming",chunks:[]}};return C.set(Q,we),p(we),we},Y=(Q,Fe)=>{x.lastId=Fe,Q&&x.byCall.set(Q,Fe)},ae=new Set,z=new Map,ge=new Set,Ie=new Map,Xe=Q=>{if(!Q)return!1;let Fe=Q.replace(/_+/g,"_").replace(/^_|_$/g,"");return Fe==="emit_artifact_markdown"||Fe==="emit_artifact_component"},ye=(Q,Fe)=>{var Ot;let we=(Ot=Q.toolId)!=null?Ot:Q.id,$e=M(Q);if(we){let Ct=String(we);return Y($e,Ct),Ct}if($e){let Ct=x.byCall.get($e);if(Ct)return x.lastId=Ct,Ct}if(x.lastId&&!Fe)return x.lastId;if(!Fe)return null;let vt=`tool-${c()}`;return Y($e,vt),vt},ee=Q=>{let Fe=v.get(Q);if(Fe)return Fe;let we={id:`tool-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Q,status:"pending"}};return v.set(Q,we),p(we),we},te=Q=>{if(typeof Q=="number"&&Number.isFinite(Q))return Q;if(typeof Q=="string"){let Fe=Number(Q);if(!Number.isNaN(Fe)&&Number.isFinite(Fe))return Fe;let we=Date.parse(Q);if(!Number.isNaN(we))return we}return Date.now()},D=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},U=new Map,oe=new Map,he=null,ht=new Map,at=(ut=this.config.iterationDisplay)!=null?ut:"separate";for(;;){let{done:Q,value:Fe}=await s.read();if(Q)break;a+=o.decode(Fe,{stream:!0});let we=a.split(`
1
+ import{Marked as Ic}from"marked";var Wc=e=>{if(e)return e},Lo=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new Ic({gfm:(s=r==null?void 0:r.gfm)!=null?s:!0,breaks:(o=r==null?void 0:r.breaks)!=null?o:!0,pedantic:r==null?void 0:r.pedantic,silent:r==null?void 0:r.silent}),n=Wc(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},fr=e=>e?Lo({markedOptions:e.options,renderer:e.renderer}):Lo(),Rc=Lo(),nl=e=>Rc(e),Jr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),rl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),tl=e=>`%%FORM_PLACEHOLDER_${e}%%`,ol=(e,r)=>{let t=e;return t=t.replace(/<Directive>([\s\S]*?)<\/Directive>/gi,(n,s)=>{try{let o=JSON.parse(s.trim());if(o&&typeof o=="object"&&o.component==="form"&&o.type){let a=tl(r.length);return r.push({token:a,type:String(o.type)}),a}}catch{return n}return n}),t=t.replace(/<Form\s+type="([^"]+)"\s*\/>/gi,(n,s)=>{let o=tl(r.length);return r.push({token:o,type:s}),o}),t},Hc=e=>{let r=fr(e);return t=>{let n=[],s=ol(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let d=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${rl(i)}"></div>`;o=o.replace(d,u)}),o}},Bc=e=>{let r=[],t=ol(e,r),n=nl(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),d=`<div class="persona-form-directive" data-tv-form="${rl(o)}"></div>`;n=n.replace(a,d)}),n};import Dc from"dompurify";var Nc={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"]},Oc=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,sl=()=>{let e=Dc(typeof window!="undefined"?window:void 0);return e.addHook("uponSanitizeAttribute",(r,t)=>{if(t.attrName==="src"||t.attrName==="href"){let n=t.attrValue;n.toLowerCase().startsWith("data:")&&!Oc.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Nc)},Kr=e=>e===!1?null:typeof e=="function"?e:sl();import{parse as al,STR as il,OBJ as ll}from"partial-json";var Po=e=>e.replace(/\\n/g,`
2
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Yr=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)}},Fc=e=>{var a,i;let r=(a=e.completedAt)!=null?a:Date.now(),t=(i=e.startedAt)!=null?i:r,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,r-t))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},cl=e=>e.status==="complete"?Fc(e):e.status==="pending"?"Waiting":"",$c=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 dl=e=>e.status==="complete"?$c(e):"Using tool...",_c=()=>{let e=null,r=0,t=n=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=n.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=n.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 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()=>{}}},Io=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},os=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ss=()=>{var r;let e=_c();return{processChunk:async t=>{let n=t.trim();return!n.startsWith("{")&&!n.startsWith("[")?null:e.processChunk(t)},getExtractedText:e.getExtractedText.bind(e),close:(r=e.close)==null?void 0:r.bind(e)}},as=()=>{let e=null,r=0;return{getExtractedText:()=>e,processChunk:t=>{let n=t.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;if(t.length<=r)return e!==null||e===""?{text:e||"",raw:t}:null;try{let s=al(t,il|ll);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Po(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Po(s.text)))}catch{}return r=t.length,e!==null?{text:e,raw:t}:null},close:()=>{}}},jc=e=>{let r=null,t=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Po(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Po(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=al(o,il|ll),d=s(i);d!==null&&(r=d)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},is=()=>{let e=null;return{processChunk:r=>{if(!r.trim().startsWith("<"))return null;let n=r.match(/<text[^>]*>([\s\S]*?)<\/text>/);return n&&n[1]?(e=n[1],{text:e,raw:r}):null},getExtractedText:()=>e}};var zc="https://api.runtype.com/v1/dispatch",ls="https://api.runtype.com",cs=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 qc(e){switch(e){case"json":return as;case"regex-json":return ss;case"xml":return is;default:return os}}var hr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:zc,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:qc(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$/,""))||ls;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$/,""))||ls}/v1/client/feedback`}async sendFeedback(r){var o,a;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(r.type)&&!r.messageId)throw new Error(`messageId is required for ${r.type} feedback type`);if(r.type==="csat"&&(r.rating===void 0||r.rating<1||r.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(r.type==="nps"&&(r.rating===void 0||r.rating<0||r.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",r);let s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(r)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,messageId:r,type:t})}async submitCSATFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"csat",rating:r,comment:t})}async submitNPSFeedback(r,t){let n=this.getClientSession();if(!n)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:n.sessionId,type:"nps",rating:r,comment:t})}async dispatch(r,t){return this.isAgentMode()?this.dispatchAgent(r,t):this.isClientTokenMode()?this.dispatchClientToken(r,t):this.dispatchProxy(r,t)}async dispatchClientToken(r,t){var s,o,a,i;let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clientSession=null,(o=(s=this.config).onSessionExpired)==null||o.call(s);let m=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:m}),m}let c=await this.buildPayload(r.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([m])=>m!=="sessionId"&&m!=="session_id")):void 0,p={sessionId:d.sessionId,messages:r.messages.filter(cs).map(m=>{var x,b,S;return{id:m.id,role:m.role,content:(S=(b=(x=m.contentParts)!=null?x:m.llmContent)!=null?b:m.rawContent)!=null?S:m.content}}),...r.assistantMessageId&&{assistantMessageId:r.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}};this.debug&&console.debug("[AgentWidgetClient] client token dispatch",p);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(p),signal:n.signal});if(!f.ok){let m=await f.json().catch(()=>({error:"Chat request failed"}));if(f.status===401){this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a);let b=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:b}),b}if(f.status===429){let b=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:b}),b}let x=new Error(m.error||"Failed to send message");throw t({type:"error",error:x}),x}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(r,t){let n=new AbortController;r.signal&&r.signal.addEventListener("abort",()=>n.abort()),t({type:"status",status:"connecting"});let s=await this.buildAgentPayload(r.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:n.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(r,t,n){t({type:"status",status:"connected"});try{await this.streamResponse(r,t,n)}finally{t({type:"status",status:"idle"})}}async resolveApproval(r,t){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ls}/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(cs).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(cs).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){if(!this.parseSSEEvent)return!1;try{let a=await this.parseSSEEvent(r);if(a===null)return!1;let i=()=>{if(n.current)return n.current;let d={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o()};return n.current=d,s(d),d};if(a.text!==void 0){let d=i();d.content+=a.text,s(d)}return a.done&&(n.current&&(n.current.streaming=!1,s(n.current)),t({type:"status",status:"idle"})),a.error&&t({type:"error",error:new Error(a.error)}),!0}catch(a){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",a),!1}}async streamResponse(r,t,n){var gt,Tt,se,re,Ue,z,te,de,Qe,G,Y,tt,Ne,je,Mt,qt,ue,Ye,ke,ot,Ve,nt,Rt,Ht,kt,N,X,_,be,xe,Ae,Ee,st,Be,We,ze,pe,Ft,xn,Un,Dn,ar,Nn,Tn,Xe,tn,un,K,Mn,on,pt,sn,kn,kr,ir,Lr,Vn,vn,Jn,bt,Cn,Pr,On,wn,D,Fn,$n,Ir,Ln,Kn,Wr,Pn,In,lr,cr,lo,co,po,Rr,dr,qe,Hr,an,Gt,uo,go,Br,Yn,Wn,mo,fo,ho,ts,Gn,Xn,mt,pr,ur,Dr,Nr,Or,Fr,Jt,nn,Rn,De,$r,Zn,gn,yo,gr,mr,Qn,_n,bo,xo,mn,er,vo;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,c=()=>i+d++,u=Z=>{let Oe=Z.reasoning?{...Z.reasoning,chunks:[...Z.reasoning.chunks]}:void 0,Te=Z.toolCall?{...Z.toolCall,chunks:Z.toolCall.chunks?[...Z.toolCall.chunks]:void 0}:void 0,Fe=Z.tools?Z.tools.map(xt=>({...xt,chunks:xt.chunks?[...xt.chunks]:void 0})):void 0;return{...Z,reasoning:Oe,toolCall:Te,tools:Fe}},p=Z=>{t({type:"message",message:u(Z)})},f=null,m={current:null},x=new Map,b=new Map,S={lastId:null,byStep:new Map},v={lastId:null,byCall:new Map},T=Z=>{if(Z==null)return null;try{return String(Z)}catch{return null}},F=Z=>{var Oe,Te,Fe,xt,$t;return T(($t=(xt=(Fe=(Te=(Oe=Z.stepId)!=null?Oe:Z.step_id)!=null?Te:Z.step)!=null?Fe:Z.parentId)!=null?xt:Z.flowStepId)!=null?$t:Z.flow_step_id)},w=Z=>{var Oe,Te,Fe,xt,$t,vt,C;return T((C=(vt=($t=(xt=(Fe=(Te=(Oe=Z.callId)!=null?Oe:Z.call_id)!=null?Te:Z.requestId)!=null?Fe:Z.request_id)!=null?xt:Z.toolCallId)!=null?$t:Z.tool_call_id)!=null?vt:Z.stepId)!=null?C:Z.step_id)},P=()=>f||(f={id:n!=null?n:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c()},p(f),f),W=(Z,Oe)=>{S.lastId=Oe,Z&&S.byStep.set(Z,Oe)},R=(Z,Oe)=>{var $t;let Te=($t=Z.reasoningId)!=null?$t:Z.id,Fe=F(Z);if(Te){let vt=String(Te);return W(Fe,vt),vt}if(Fe){let vt=S.byStep.get(Fe);if(vt)return S.lastId=vt,vt}if(S.lastId&&!Oe)return S.lastId;if(!Oe)return null;let xt=`reason-${c()}`;return W(Fe,xt),xt},U=Z=>{let Oe=x.get(Z);if(Oe)return Oe;let Te={id:`reason-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Z,status:"streaming",chunks:[]}};return x.set(Z,Te),p(Te),Te},ve=(Z,Oe)=>{v.lastId=Oe,Z&&v.byCall.set(Z,Oe)},le=new Set,q=new Map,ee=new Set,Ce=new Map,we=Z=>{if(!Z)return!1;let Oe=Z.replace(/_+/g,"_").replace(/^_|_$/g,"");return Oe==="emit_artifact_markdown"||Oe==="emit_artifact_component"},ye=(Z,Oe)=>{var $t;let Te=($t=Z.toolId)!=null?$t:Z.id,Fe=w(Z);if(Te){let vt=String(Te);return ve(Fe,vt),vt}if(Fe){let vt=v.byCall.get(Fe);if(vt)return v.lastId=vt,vt}if(v.lastId&&!Oe)return v.lastId;if(!Oe)return null;let xt=`tool-${c()}`;return ve(Fe,xt),xt},ce=Z=>{let Oe=b.get(Z);if(Oe)return Oe;let Te={id:`tool-${Z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Z,status:"pending"}};return b.set(Z,Te),p(Te),Te},Q=Z=>{if(typeof Z=="number"&&Number.isFinite(Z))return Z;if(typeof Z=="string"){let Oe=Number(Z);if(!Number.isNaN(Oe)&&Number.isFinite(Oe))return Oe;let Te=Date.parse(Z);if(!Number.isNaN(Te))return Te}return Date.now()},J=Z=>{if(typeof Z=="string")return Z;if(Z==null)return"";try{return JSON.stringify(Z)}catch{return String(Z)}},V=new Map,ne=new Map,fe=null,wt=new Map,ut=(gt=this.config.iterationDisplay)!=null?gt:"separate";for(;;){let{done:Z,value:Oe}=await s.read();if(Z)break;a+=o.decode(Oe,{stream:!0});let Te=a.split(`
5
5
 
6
- `);a=(Wt=we.pop())!=null?Wt:"";for(let $e of we){let vt=$e.split(`
7
- `),Ot="message",Ct="";for(let T of vt)T.startsWith("event:")?Ot=T.replace("event:","").trim():T.startsWith("data:")&&(Ct+=T.replace("data:","").trim());if(!Ct)continue;let b;try{b=JSON.parse(Ct)}catch(T){t({type:"error",error:T instanceof Error?T:new Error("Failed to parse chat stream payload")});continue}let De=Ot!=="message"?Ot:(de=b.type)!=null?de:"message";if((ie=this.onSSEEvent)==null||ie.call(this,De,b),this.parseSSEEvent){m.current=f;let T=await this.handleCustomSSEEvent(b,t,m,p,c);if(m.current&&!f&&(f=m.current),T)continue}if(De==="reason_start"){let T=(qe=F(b,!0))!=null?qe:`reason-${c()}`,A=re(T);A.reasoning=(j=A.reasoning)!=null?j:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(be=A.reasoning.startedAt)!=null?be:te((G=b.startedAt)!=null?G:b.timestamp),A.reasoning.completedAt=void 0,A.reasoning.durationMs=void 0,A.streaming=!0,A.reasoning.status="streaming",p(A)}else if(De==="reason_delta"||De==="reason_chunk"){let T=(X=(ze=F(b,!1))!=null?ze:F(b,!0))!=null?X:`reason-${c()}`,A=re(T);A.reasoning=(K=A.reasoning)!=null?K:{id:T,status:"streaming",chunks:[]},A.reasoning.startedAt=(We=A.reasoning.startedAt)!=null?We:te((tt=b.startedAt)!=null?tt:b.timestamp);let W=(_t=(Tt=(Ve=b.reasoningText)!=null?Ve:b.text)!=null?Tt:b.delta)!=null?_t:"";if(W&&b.hidden!==!0&&A.reasoning.chunks.push(String(W)),A.reasoning.status=b.done?"complete":"streaming",b.done){A.reasoning.completedAt=te((ce=b.completedAt)!=null?ce:b.timestamp);let le=(Je=A.reasoning.startedAt)!=null?Je:Date.now();A.reasoning.durationMs=Math.max(0,((Me=A.reasoning.completedAt)!=null?Me:Date.now())-le)}A.streaming=A.reasoning.status!=="complete",p(A)}else if(De==="reason_complete"){let T=(je=(nt=F(b,!1))!=null?nt:F(b,!0))!=null?je:`reason-${c()}`,A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=te((Ze=b.completedAt)!=null?Ze:b.timestamp);let le=(Rt=A.reasoning.startedAt)!=null?Rt:Date.now();A.reasoning.durationMs=Math.max(0,((Ht=A.reasoning.completedAt)!=null?Ht:Date.now())-le),A.streaming=!1,p(A)}let W=q(b);W&&E.byStep.delete(W)}else if(De==="tool_start"){let T=(Mt=ye(b,!0))!=null?Mt:`tool-${c()}`,A=(B=b.toolName)!=null?B:b.name;if(Xe(A)){ae.add(T);continue}let W=ee(T),le=(Z=W.toolCall)!=null?Z:{id:T,status:"pending"};le.name=A!=null?A:le.name,le.status="running",b.args!==void 0?le.args=b.args:b.parameters!==void 0&&(le.args=b.parameters),le.startedAt=(_=le.startedAt)!=null?_:te((J=b.startedAt)!=null?J:b.timestamp),le.completedAt=void 0,le.durationMs=void 0,W.toolCall=le,W.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(W.agentMetadata={executionId:(xe=Se==null?void 0:Se.executionId)!=null?xe:b.executionId,iteration:(Le=Se==null?void 0:Se.iteration)!=null?Le:b.iteration}),p(W)}else if(De==="tool_chunk"||De==="tool_delta"){let T=(pt=(He=ye(b,!1))!=null?He:ye(b,!0))!=null?pt:`tool-${c()}`;if(ae.has(T))continue;let A=ee(T),W=(ve=A.toolCall)!=null?ve:{id:T,status:"running"};W.startedAt=(Be=W.startedAt)!=null?Be:te((Ce=b.startedAt)!=null?Ce:b.timestamp);let le=(Zt=(bt=(ue=b.text)!=null?ue:b.delta)!=null?bt:b.message)!=null?Zt:"";le&&(W.chunks=(un=W.chunks)!=null?un:[],W.chunks.push(String(le))),W.status="running",A.toolCall=W,A.streaming=!0;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(Pn=A.agentMetadata)!=null?Pn:{executionId:(gn=Se==null?void 0:Se.executionId)!=null?gn:b.executionId,iteration:(ro=Se==null?void 0:Se.iteration)!=null?ro:b.iteration}),p(A)}else if(De==="tool_complete"){let T=(Qe=(Zn=ye(b,!1))!=null?Zn:ye(b,!0))!=null?Qe:`tool-${c()}`;if(ae.has(T)){ae.delete(T);continue}let A=ee(T),W=(mn=A.toolCall)!=null?mn:{id:T,status:"running"};W.status="complete",b.result!==void 0&&(W.result=b.result),typeof b.duration=="number"&&(W.duration=b.duration),W.completedAt=te((In=b.completedAt)!=null?In:b.timestamp);let le=(ln=b.duration)!=null?ln:b.executionTime;if(typeof le=="number")W.durationMs=le;else{let kt=(Cr=W.startedAt)!=null?Cr:Date.now();W.durationMs=Math.max(0,((fn=W.completedAt)!=null?fn:Date.now())-kt)}A.toolCall=W,A.streaming=!1;let Se=b.agentContext;(Se||b.executionId)&&(A.agentMetadata=(wn=A.agentMetadata)!=null?wn:{executionId:(dt=Se==null?void 0:Se.executionId)!=null?dt:b.executionId,iteration:(nn=Se==null?void 0:Se.iteration)!=null?nn:b.iteration}),p(A);let ot=M(b);ot&&x.byCall.delete(ot)}else if(De==="step_chunk"||De==="step_delta"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=N(),le=(Nn=(Sr=(Qn=(wr=b.text)!=null?wr:b.delta)!=null?Qn:b.content)!=null?Sr:b.chunk)!=null?Nn:"";if(le){let ot=((hn=oe.get(W.id))!=null?hn:"")+le;W.rawContent=ot,U.has(W.id)||U.set(W.id,this.createStreamParser());let kt=U.get(W.id),wt=ot.trim().startsWith("{")||ot.trim().startsWith("[");if(wt&&oe.set(W.id,ot),kt.__isPlainTextParser===!0){W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W);continue}let Lt=kt.processChunk(ot);if(Lt instanceof Promise)Lt.then(st=>{var At;let lt=typeof st=="string"?st:(At=st==null?void 0:st.text)!=null?At:null;if(lt!==null&&lt.trim()!==""){let ct=f;ct&&ct.id===W.id&&(ct.content=lt,p(ct))}else if(!wt&&!ot.trim().startsWith("<")){let ct=f;ct&&ct.id===W.id&&(ct.content+=le,oe.delete(ct.id),U.delete(ct.id),ct.rawContent=void 0,p(ct))}}).catch(()=>{W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W)});else{let st=typeof Lt=="string"?Lt:(On=Lt==null?void 0:Lt.text)!=null?On:null;st!==null&&st.trim()!==""?(W.content=st,p(W)):!wt&&!ot.trim().startsWith("<")&&(W.content+=le,oe.delete(W.id),U.delete(W.id),W.rawContent=void 0,p(W))}}if(b.isComplete){let Se=(yn=(xt=b.result)==null?void 0:xt.response)!=null?yn:W.content;if(Se){let ot=oe.get(W.id),kt=ot!=null?ot:D(Se);W.rawContent=kt;let wt=U.get(W.id),Bt=null,Lt=!1;if(wt&&(Bt=wt.getExtractedText(),Bt===null&&(Bt=To(kt)),Bt===null)){let st=wt.processChunk(kt);st instanceof Promise?(Lt=!0,st.then(lt=>{var ct;let At=typeof lt=="string"?lt:(ct=lt==null?void 0:lt.text)!=null?ct:null;if(At!==null){let Ft=f;Ft&&Ft.id===W.id&&(Ft.content=At,Ft.streaming=!1,U.delete(Ft.id),oe.delete(Ft.id),p(Ft))}})):Bt=typeof st=="string"?st:(Ar=st==null?void 0:st.text)!=null?Ar:null}if(!Lt){Bt!==null&&Bt.trim()!==""?W.content=Bt:oe.has(W.id)||(W.content=D(Se));let st=U.get(W.id);if(st){let lt=(Wn=st.close)==null?void 0:Wn.call(st);lt instanceof Promise&&lt.catch(()=>{}),U.delete(W.id)}oe.delete(W.id),W.streaming=!1,p(W)}}}}else if(De==="step_complete"){let T=b.stepType,A=b.executionType;if(T==="tool"||A==="context")continue;let W=(bn=b.result)==null?void 0:bn.response,le=N();if(W!=null){let Se=U.get(le.id),ot=!1,kt=!1;if(Se){let wt=Se.getExtractedText(),Bt=oe.get(le.id),Lt=Bt!=null?Bt:D(W);if(le.rawContent=Lt,wt!==null&&wt.trim()!=="")le.content=wt,ot=!0;else{let st=To(Lt);if(st!==null)le.content=st,ot=!0;else{let lt=Se.processChunk(Lt);if(lt instanceof Promise)kt=!0,lt.then(At=>{var Ft;let ct=typeof At=="string"?At:(Ft=At==null?void 0:At.text)!=null?Ft:null;if(ct!==null&&ct.trim()!==""){let Yt=f;Yt&&Yt.id===le.id&&(Yt.content=ct,Yt.streaming=!1,U.delete(Yt.id),oe.delete(Yt.id),p(Yt))}else{let Yt=Se.getExtractedText(),on=f;on&&on.id===le.id&&(Yt!==null&&Yt.trim()!==""?on.content=Yt:oe.has(on.id)||(on.content=D(W)),on.streaming=!1,U.delete(on.id),oe.delete(on.id),p(on))}});else{let At=typeof lt=="string"?lt:(H=lt==null?void 0:lt.text)!=null?H:null;if(At!==null&&At.trim()!=="")le.content=At,ot=!0;else{let ct=Se.getExtractedText();ct!==null&&ct.trim()!==""&&(le.content=ct,ot=!0)}}}}}if(!kt){if(!le.rawContent){let wt=oe.get(le.id);le.rawContent=wt!=null?wt:D(W)}if(!ot&&!oe.has(le.id)&&(le.content=D(W)),Se){let wt=(Rn=Se.close)==null?void 0:Rn.call(Se);wt instanceof Promise&&wt.catch(()=>{})}U.delete(le.id),oe.delete(le.id),le.streaming=!1,p(le)}}else U.delete(le.id),oe.delete(le.id),le.streaming=!1,p(le)}else if(De==="flow_complete"){let T=(Hn=b.result)==null?void 0:Hn.response;if(T!=null){let A=N(),W=oe.get(A.id),le=W!=null?W:D(T);A.rawContent=le;let Se=D(T),ot=U.get(A.id);if(ot){let Bt=To(le);if(Bt!==null)Se=Bt;else{let Lt=ot.processChunk(le);Lt instanceof Promise&&Lt.then(lt=>{var ct;let At=typeof lt=="string"?lt:(ct=lt==null?void 0:lt.text)!=null?ct:null;if(At!==null){let Ft=f;Ft&&Ft.id===A.id&&(Ft.content=At,Ft.streaming=!1,p(Ft))}});let st=ot.getExtractedText();st!==null&&(Se=st)}}U.delete(A.id),oe.delete(A.id);let kt=Se!==A.content,wt=A.streaming!==!1;kt&&(A.content=Se),A.streaming=!1,(kt||wt)&&p(A)}else if(f!==null){let A=f;U.delete(A.id),oe.delete(A.id),A.streaming!==!1&&(A.streaming=!1,p(A))}t({type:"status",status:"idle"})}else if(De==="agent_start")he={executionId:b.executionId,agentId:(Er=b.agentId)!=null?Er:"virtual",agentName:(Sn=b.agentName)!=null?Sn:"",status:"running",currentIteration:0,maxTurns:(Dn=b.maxTurns)!=null?Dn:1,startedAt:te(b.startedAt)};else if(De==="agent_iteration_start"){if(he&&(he.currentIteration=b.iteration),at==="separate"&&b.iteration>1){let T=f;T&&(T.streaming=!1,p(T),ht.set(b.iteration-1,T),f=null)}}else if(De!=="agent_turn_start"){if(De==="agent_turn_delta"){if(b.contentType==="text"){let T=N();T.content+=(Tr=b.delta)!=null?Tr:"",T.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId,agentName:he==null?void 0:he.agentName},p(T)}else if(b.contentType==="thinking"){let T=(An=b.turnId)!=null?An:`agent-think-${b.iteration}`,A=re(T);A.reasoning=(En=A.reasoning)!=null?En:{id:T,status:"streaming",chunks:[]},A.reasoning.chunks.push((er=b.delta)!=null?er:""),A.agentMetadata={executionId:b.executionId,iteration:b.iteration,turnId:b.turnId},p(A)}else if(b.contentType==="tool_input"){let T=(tr=b.toolCallId)!=null?tr:x.lastId;if(T){let A=v.get(T);A!=null&&A.toolCall&&(A.toolCall.chunks=(oo=A.toolCall.chunks)!=null?oo:[],A.toolCall.chunks.push((so=b.delta)!=null?so:""),p(A))}}}else if(De==="agent_turn_complete"){let T=b.turnId;if(T){let A=C.get(T);if(A!=null&&A.reasoning){A.reasoning.status="complete",A.reasoning.completedAt=te(b.completedAt);let W=(ao=A.reasoning.startedAt)!=null?ao:Date.now();A.reasoning.durationMs=Math.max(0,((Mr=A.reasoning.completedAt)!=null?Mr:Date.now())-W),A.streaming=!1,p(A)}}}else if(De==="agent_tool_start"){let T=(nr=b.toolCallId)!=null?nr:`agent-tool-${c()}`;Y(M(b),T);let A=ee(T),W=(Ue=A.toolCall)!=null?Ue:{id:T,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};W.name=(rn=(kr=b.toolName)!=null?kr:b.name)!=null?rn:W.name,W.status="running",b.parameters!==void 0&&(W.args=b.parameters),W.startedAt=te((Kt=b.startedAt)!=null?Kt:b.timestamp),A.toolCall=W,A.streaming=!0,A.agentMetadata={executionId:b.executionId,iteration:b.iteration},p(A)}else if(De==="agent_tool_delta"){let T=(io=b.toolCallId)!=null?io:x.lastId;if(T){let A=(lo=v.get(T))!=null?lo:ee(T);A.toolCall&&(A.toolCall.chunks=(Lr=A.toolCall.chunks)!=null?Lr:[],A.toolCall.chunks.push((_n=b.delta)!=null?_n:""),A.toolCall.status="running",A.streaming=!0,p(A))}}else if(De==="agent_tool_complete"){let T=(Tn=b.toolCallId)!=null?Tn:x.lastId;if(T){let A=(co=v.get(T))!=null?co:ee(T);if(A.toolCall){A.toolCall.status="complete",b.result!==void 0&&(A.toolCall.result=b.result),typeof b.executionTime=="number"&&(A.toolCall.durationMs=b.executionTime),A.toolCall.completedAt=te((po=b.completedAt)!=null?po:b.timestamp),A.streaming=!1,p(A);let W=M(b);W&&x.byCall.delete(W)}}}else if(De!=="agent_iteration_complete"){if(De==="agent_reflection"||De==="agent_reflect"){let T=`agent-reflection-${b.executionId}-${b.iteration}`,A={id:T,role:"assistant",content:(uo=b.reflection)!=null?uo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:T,status:"complete",chunks:[(Jo=b.reflection)!=null?Jo:""]},agentMetadata:{executionId:b.executionId,iteration:b.iteration}};p(A)}else if(De==="agent_complete"){he&&(he.status=b.success?"complete":"error",he.completedAt=te(b.completedAt),he.stopReason=b.stopReason);let T=f;T&&(T.streaming=!1,p(T)),t({type:"status",status:"idle"})}else if(De==="agent_error"){let T=typeof b.error=="string"?b.error:(rr=(jn=b.error)==null?void 0:jn.message)!=null?rr:"Agent execution error";b.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",T):t({type:"error",error:new Error(T)})}else if(De!=="agent_ping")if(De==="agent_approval_start"){let T=(gt=b.approvalId)!=null?gt:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(or=he==null?void 0:he.agentId)!=null?or:"virtual",executionId:(Pr=(sr=b.executionId)!=null?sr:he==null?void 0:he.executionId)!=null?Pr:"",toolName:(Ir=b.toolName)!=null?Ir:"",toolType:b.toolType,description:(Rr=b.description)!=null?Rr:`Execute ${(Wr=b.toolName)!=null?Wr:"tool"}`,parameters:b.parameters}};p(A)}else if(De==="step_await"&&b.awaitReason==="approval_required"){let T=(Ut=b.approvalId)!=null?Ut:`approval-${c()}`,A={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:"pending",agentId:(Qt=he==null?void 0:he.agentId)!=null?Qt:"virtual",executionId:(Re=(Mn=b.executionId)!=null?Mn:he==null?void 0:he.executionId)!=null?Re:"",toolName:(Hr=b.toolName)!=null?Hr:"",toolType:b.toolType,description:(cn=b.description)!=null?cn:`Execute ${(Vn=b.toolName)!=null?Vn:"tool"}`,parameters:b.parameters}};p(A)}else if(De==="agent_approval_complete"){let T=b.approvalId;if(T){let W={id:`approval-${T}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:T,status:(go=b.decision)!=null?go:"approved",agentId:(ar=he==null?void 0:he.agentId)!=null?ar:"virtual",executionId:(Un=(ir=b.executionId)!=null?ir:he==null?void 0:he.executionId)!=null?Un:"",toolName:(Bn=b.toolName)!=null?Bn:"",description:(mo=b.description)!=null?mo:"",resolvedAt:Date.now()}};p(W)}}else if(De==="artifact_start"||De==="artifact_delta"||De==="artifact_update"||De==="artifact_complete"){if(De==="artifact_start"){let T=b.artifactType,A=String(b.id),W=typeof b.title=="string"?b.title:void 0;if(t({type:"artifact_start",id:A,artifactType:T,title:W,component:typeof b.component=="string"?b.component:void 0}),Ie.set(A,{markdown:"",title:W}),!ge.has(A)){ge.add(A);let le={id:`artifact-ref-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:A,title:W,artifactType:T,status:"streaming"}})};z.set(A,le),p(le)}}else if(De==="artifact_delta"){let T=String(b.id),A=typeof b.delta=="string"?b.delta:String((fo=b.delta)!=null?fo:"");t({type:"artifact_delta",id:T,artDelta:A});let W=Ie.get(T);W&&(W.markdown+=A)}else if(De==="artifact_update"){let T=b.props&&typeof b.props=="object"&&!Array.isArray(b.props)?b.props:{};t({type:"artifact_update",id:String(b.id),props:T,component:typeof b.component=="string"?b.component:void 0})}else if(De==="artifact_complete"){let T=String(b.id);t({type:"artifact_complete",id:T});let A=z.get(T);if(A){A.streaming=!1;try{let W=JSON.parse((dn=A.rawContent)!=null?dn:"{}");if(W.props){W.props.status="complete";let le=Ie.get(T);le!=null&&le.markdown&&(W.props.markdown=le.markdown)}A.rawContent=JSON.stringify(W)}catch{}Ie.delete(T),p(A),z.delete(T)}}}else if(De==="transcript_insert"){let T=b.message;if(!T||typeof T!="object")continue;let A=String((qn=T.id)!=null?qn:`msg-${c()}`),W=T.role,Se={id:A,role:W==="user"?"user":W==="system"?"system":"assistant",content:typeof T.content=="string"?T.content:"",rawContent:typeof T.rawContent=="string"?T.rawContent:void 0,createdAt:typeof T.createdAt=="string"?T.createdAt:new Date().toISOString(),streaming:T.streaming===!0,...typeof T.variant=="string"?{variant:T.variant}:{},sequence:c()};if(p(Se),Se.rawContent)try{let ot=JSON.parse(Se.rawContent),kt=(ho=ot==null?void 0:ot.props)==null?void 0:ho.artifactId;typeof kt=="string"&&ge.add(kt)}catch{}f=null,m.current=null,U.delete(A),oe.delete(A)}else De==="error"&&b.error&&t({type:"error",error:b.error instanceof Error?b.error:new Error(String(b.error))})}}}}}};function Nc(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`msg_${e}_${n}`}function Ur(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`usr_${e}_${n}`}function dr(){let e=Date.now().toString(36),n=Math.random().toString(36).substring(2,10);return`ast_${e}_${n}`}var Mo="[Image]";function Oc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Dc(e){return typeof e=="string"?e:e.filter(n=>n.type==="text").map(n=>n.text).join("")}function _c(e){return typeof e=="string"?!1:e.some(n=>n.type==="image")}function jc(e){return typeof e=="string"?[]:e.filter(n=>n.type==="image")}function ns(e){return{type:"text",text:e}}function Vc(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 Uc(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 qc(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 rl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zc=["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"],kn=[...rl,...zc];function Jc(e){return rl.includes(e)||e.startsWith("image/")}function ko(e){return Jc(e.type)}async function ol(e){return new Promise((n,t)=>{let r=new FileReader;r.onload=()=>{let s=r.result;ko(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 sl(e,n=kn,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 Kc(e){let n=e.split(".");return n.length>1?n.pop().toLowerCase():""}function al(e,n){let t=Kc(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 Lo=class{constructor(n=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=n}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let r=t.AudioContext||t.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let n=this.ctx;return n.state==="suspended"&&n.resume(),n}enqueue(n){if(n.length===0)return;let t=n;if(this.remainder){let d=new Uint8Array(this.remainder.length+n.length);d.set(this.remainder),d.set(n,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let r=this.ensureContext(),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 d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let n of this.activeSources)try{n.stop(),n.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(n){this.finishedCallbacks.push(n)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let n=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of n)t()}}pcmToFloat32(n){let t=Math.floor(n.length/2),r=new Float32Array(t),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 Po=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 g=0;g<a.length;g++)i+=a[g]*a[g];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var qr=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 Po;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,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let g=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let C=!1,v=x=>{C||(C=!0,clearTimeout(E),m(new Error(x)))},E=setTimeout(()=>v("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{C||(C=!0,clearTimeout(E),f())},{once:!0}),this.ws.addEventListener("error",()=>{v("WebSocket connection failed to "+g+"."+p)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!C){let k=x.code!==1006?` (code ${x.code})`:"";v("WebSocket connection failed"+k+"."+p)}},{once:!0})}),this.sendHeartbeat()}catch(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 Lo(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,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let g=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:g});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(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),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(n){this.resultCallbacks.push(n)}onError(n){this.errorCallbacks.push(n)}onStatusChange(n){this.statusCallbacks.push(n)}onProcessingStart(n){this.processingStartCallbacks.push(n)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(n=>n.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(n=>n("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var Gn=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(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(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 pr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new qr(e.runtype);case"browser":if(!Gn.isSupported())throw new Error("Browser speech recognition not supported");return new Gn(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function rs(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return pr({type:"runtype",runtype:e.runtype});if(Gn.isSupported())return pr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Io(e){try{return rs(e),!0}catch{return!1}}var zr=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,d;n.type==="message"?(this.upsertMessage(n.message),(t=n.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?n.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=n.message.agentMetadata.iteration):this.agentExecution={executionId:n.message.agentMetadata.executionId,agentId:"",agentName:(r=n.message.agentMetadata.agentName)!=null?r:"",status:"running",currentIteration:(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"),(d=(i=this.callbacks).onError)==null||d.call(i,n.error)):(n.type==="artifact_start"||n.type==="artifact_delta"||n.type==="artifact_update"||n.type==="artifact_complete")&&this.applyArtifactStreamEvent(n)};var r;this.messages=[...(r=n.initialMessages)!=null?r:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new cr(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 Io((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=pr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(r=a.processingText)!=null?r:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let g=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=g.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var g,p,f,m,C,v;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((g=c.transcript)!=null&&g.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let E=(v=this.pendingVoiceAssistantMessageId)!=null?v:(C=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:C.id;E&&this.ttsSpokenMessageIds.add(E)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var g,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(g=this.callbacks).onVoiceStatusChanged)==null||p.call(g,c)}),this.voiceProvider.connect()}catch(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,d,c,g;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let n=this.config.voiceRecognition.provider;switch(n.type){case"runtype":return{type:"runtype",runtype:{agentId:((r=n.runtype)==null?void 0:r.agentId)||"",clientToken:((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:(d=n.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=n.browser)==null?void 0:c.language)||"en-US",continuous:(g=n.browser)==null?void 0:g.continuous}};default:return}}async initClientSession(){var n,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(n=this.callbacks).onError)==null||t.call(n,r instanceof Error?r:new Error(String(r))),null}}setClientSession(n){if(this.clientSession=n,n.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:n.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var n;return(n=this.clientSession)!=null?n:this.client.getClientSession()}isSessionValid(){let n=this.getClientSession();return n?new Date<n.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(n,t){return this.client.submitMessageFeedback(n,t)}async submitCSATFeedback(n,t){return this.client.submitCSATFeedback(n,t)}async submitNPSFeedback(n,t){return this.client.submitNPSFeedback(n,t)}updateConfig(n){let t=this.client.getSSEEventCallback();this.config={...this.config,...n},this.client=new cr(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:d,streaming:c=!1,voiceProcessing:g}=n,f={id:a!=null?a:t==="user"?Ur():t==="assistant"?dr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...g!==void 0&&{voiceProcessing:g}};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:d,createdAt:c,sequence:g,streaming:p=!1}=r,m={id:d!=null?d:s==="user"?Ur():s==="assistant"?dr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:g!=null?g:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(n,t){var c,g,p,f,m;let r=n.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Ur(),o=dr(),a={id:s,role:"user",content:r||Mo,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(C){let v=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));if(!v){let E={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(E)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(C instanceof Error?(p=(g=this.callbacks).onError)==null||p.call(g,C):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(C))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=dr();this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:n},this.handleEvent)}catch(c){let g={id:n,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(g),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.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 d,c,g;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 p;if(i?p=await i({approvalId:n.id,executionId:n.executionId,agentId:n.agentId,toolName:n.toolName},t):p=await this.client.resolveApproval({agentId:n.agentId,executionId:n.executionId,approvalId:n.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);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(p){(g=(c=this.callbacks).onError)==null||g.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var n;this.stopSpeaking(),(n=this.abortController)==null||n.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(n){return this.artifacts.get(n)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(n){this.selectedArtifactId=n,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(n){var 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 d,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=(d=t.sequence)!=null?d: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},vn=(e,n,t)=>{let r=e.createElement(n);return t&&(r.className=t),r};import*as Yc from"lucide";var me=(e,n=24,t="currentColor",r=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=Yc[s];return o?Gc(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 Gc(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 d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,g])=>{c!=="stroke"&&d.setAttribute(c,String(g))}),s.appendChild(d)}}}),s}var Wo={allowedTypes:kn,maxFileSize:10*1024*1024,maxFiles:4};function Xc(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Zc(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 ur=class e{constructor(n={}){this.attachments=[];this.previewsContainer=null;var t,r,s;this.config={allowedTypes:(t=n.allowedTypes)!=null?t:Wo.allowedTypes,maxFileSize:(r=n.maxFileSize)!=null?r:Wo.maxFileSize,maxFiles:(s=n.maxFiles)!=null?s:Wo.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:Wo.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,d;if(n.length){for(let c of n){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let g=sl(c,this.config.allowedTypes,this.config.maxFileSize);if(!g.valid){let p=(s=g.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await ol(c),f=ko(c)?URL.createObjectURL(c):null,m={id:Xc(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(n){var o,a,i;let t=this.attachments.findIndex(d=>d.id===n);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let 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=ko(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=Zc(n.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=al(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=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(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 il={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},ll={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},cl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}}};function dl(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."))?dl(e,r):r}function os(e){let n={};function t(r,s){for(let[o,a]of Object.entries(r)){let i=`${s}.${o}`;if(typeof a=="string"){let d=dl(e,a);d!==void 0&&(n[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),n}function pl(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 ul(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]=ul(o,s):t[r]=s}return t}function Qc(e,n){return n?ul(e,n):e}function Jr(e,n={}){var s,o,a,i,d,c,g,p,f,m,C,v,E;let t={palette:il,semantic:ll,components:cl},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,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(g=e==null?void 0:e.semantic)==null?void 0:g.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(C=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:C.feedback}},spacing:{...t.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...t.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:Qc(t.components,e==null?void 0:e.components)};if(n.validate!==!1){let x=pl(r);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(k=>k.message).join(", ")}`)}if(n.plugins)for(let x of n.plugins)r=x.transform(r);return r}function ss(e){var g,p,f,m,C,v,E,x,k,q,M,N,w,F,re,Y,ae,z,ge,Ie,Xe,ye,ee,te,D,U,oe,he,ht,at,ut,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J;let n=os(e),t={};for(let[_,xe]of Object.entries(n)){let Le=_.replace(/\./g,"-");t[`--persona-${Le}`]=xe.value}t["--persona-primary"]=(g=t["--persona-semantic-colors-primary"])!=null?g:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(p=t["--persona-semantic-colors-secondary"])!=null?p:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(f=t["--persona-semantic-colors-accent"])!=null?f:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(m=t["--persona-semantic-colors-surface"])!=null?m:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(C=t["--persona-semantic-colors-background"])!=null?C:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(v=t["--persona-semantic-colors-container"])!=null?v:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(E=t["--persona-semantic-colors-text"])!=null?E:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(x=t["--persona-semantic-colors-text-muted"])!=null?x:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(M=t["--persona-semantic-colors-divider"])!=null?M:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(N=t["--persona-components-voice-recording-indicator"])!=null?N:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(w=t["--persona-components-voice-recording-background"])!=null?w:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(re=t["--persona-components-voice-speaking-icon"])!=null?re:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Y=t["--persona-components-approval-requested-background"])!=null?Y: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"]=(z=t["--persona-components-approval-requested-text"])!=null?z:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ge=t["--persona-components-approval-approve-background"])!=null?ge:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Ie=t["--persona-components-approval-deny-background"])!=null?Ie:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(Xe=t["--persona-components-attachment-image-background"])!=null?Xe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ye=t["--persona-components-attachment-image-border"])!=null?ye:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ee=t["--persona-semantic-typography-fontFamily"])!=null?ee:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(te=t["--persona-semantic-typography-fontSize"])!=null?te:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(D=t["--persona-semantic-typography-fontWeight"])!=null?D:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(U=t["--persona-semantic-typography-lineHeight"])!=null?U:t["--persona-palette-typography-lineHeight-normal"],t["--persona-radius-sm"]=(oe=t["--persona-palette-radius-sm"])!=null?oe:"0.125rem",t["--persona-radius-md"]=(he=t["--persona-palette-radius-md"])!=null?he:"0.375rem",t["--persona-radius-lg"]=(ht=t["--persona-palette-radius-lg"])!=null?ht:"0.5rem",t["--persona-radius-xl"]=(at=t["--persona-palette-radius-xl"])!=null?at:"0.75rem",t["--persona-launcher-radius"]=(Wt=(ut=t["--persona-components-launcher-borderRadius"])!=null?ut:t["--persona-palette-radius-full"])!=null?Wt:"9999px",t["--persona-button-radius"]=(ie=(de=t["--persona-components-button-primary-borderRadius"])!=null?de:t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-panel-radius"]=(j=(qe=t["--persona-components-panel-borderRadius"])!=null?qe:t["--persona-radius-xl"])!=null?j:"0.75rem",t["--persona-input-radius"]=(be=(G=t["--persona-components-input-borderRadius"])!=null?G:t["--persona-radius-lg"])!=null?be:"0.5rem",t["--persona-message-user-radius"]=(X=(ze=t["--persona-components-message-user-borderRadius"])!=null?ze:t["--persona-radius-lg"])!=null?X:"0.5rem",t["--persona-message-assistant-radius"]=(tt=(K=t["--persona-components-message-assistant-borderRadius"])!=null?K:t["--persona-radius-lg"])!=null?tt:"0.5rem",t["--persona-header-bg"]=(We=t["--persona-components-header-background"])!=null?We:t["--persona-surface"],t["--persona-header-border"]=(Ve=t["--persona-components-header-border"])!=null?Ve:t["--persona-divider"],t["--persona-message-user-bg"]=(Tt=t["--persona-components-message-user-background"])!=null?Tt:t["--persona-accent"],t["--persona-message-user-text"]=(_t=t["--persona-components-message-user-text"])!=null?_t:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(ce=t["--persona-components-message-user-shadow"])!=null?ce:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Je=t["--persona-components-message-assistant-background"])!=null?Je:t["--persona-surface"],t["--persona-message-assistant-text"]=(Me=t["--persona-components-message-assistant-text"])!=null?Me:t["--persona-text"],t["--persona-message-assistant-border"]=(nt=t["--persona-components-message-assistant-border"])!=null?nt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(je=t["--persona-components-message-assistant-shadow"])!=null?je:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Ze=t["--persona-components-toolBubble-shadow"])!=null?Ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Rt=t["--persona-components-reasoningBubble-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Ht=t["--persona-components-composer-shadow"])!=null?Ht:"none",t["--persona-md-inline-code-bg"]=(Mt=t["--persona-components-markdown-inlineCode-background"])!=null?Mt:t["--persona-container"],t["--persona-md-inline-code-color"]=(B=t["--persona-components-markdown-inlineCode-foreground"])!=null?B:t["--persona-text"],t["--persona-md-link-color"]=(J=(Z=t["--persona-components-markdown-link-foreground"])!=null?Z:t["--persona-accent"])!=null?J:"#3b82f6";let r=t["--persona-components-markdown-heading-h1-fontSize"];r&&(t["--persona-md-h1-size"]=r);let s=t["--persona-components-markdown-heading-h1-fontWeight"];s&&(t["--persona-md-h1-weight"]=s);let o=t["--persona-components-markdown-heading-h2-fontSize"];o&&(t["--persona-md-h2-size"]=o);let a=t["--persona-components-markdown-heading-h2-fontWeight"];a&&(t["--persona-md-h2-weight"]=a);let i=t["--persona-components-markdown-prose-fontFamily"];i&&i!=="inherit"&&(t["--persona-md-prose-font-family"]=i);let d=e.components,c=d==null?void 0:d.artifact;if(c!=null&&c.toolbar){let _=c.toolbar;_.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=_.iconHoverColor),_.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=_.iconHoverBackground),_.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=_.iconPadding),_.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=_.iconBorderRadius),_.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=_.iconBorder),_.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=_.toggleGroupGap),_.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=_.toggleBorderRadius),_.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=_.copyBackground),_.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=_.copyBorder),_.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=_.copyColor),_.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=_.copyBorderRadius),_.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=_.copyPadding),_.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=_.copyMenuBackground),_.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=_.copyMenuBorder),_.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=_.copyMenuShadow),_.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=_.copyMenuBorderRadius),_.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=_.copyMenuItemHoverBackground)}if(c!=null&&c.tab){let _=c.tab;_.background&&(t["--persona-artifact-tab-bg"]=_.background),_.activeBackground&&(t["--persona-artifact-tab-active-bg"]=_.activeBackground),_.activeBorder&&(t["--persona-artifact-tab-active-border"]=_.activeBorder),_.borderRadius&&(t["--persona-artifact-tab-radius"]=_.borderRadius),_.textColor&&(t["--persona-artifact-tab-color"]=_.textColor)}if(c!=null&&c.pane){let _=c.pane;_.toolbarBackground&&(t["--persona-artifact-toolbar-bg"]=_.toolbarBackground)}return t}var ed={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 as={primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.accent.600",surface:"palette.colors.gray.50",muted:"palette.colors.gray.500",container:"palette.colors.gray.100",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",messageBorder:"palette.colors.gray.200",inputBackground:"palette.colors.gray.50",callToAction:"palette.colors.gray.900",callToActionBackground:"palette.colors.gray.50",sendButtonBackgroundColor:"semantic.colors.primary",sendButtonTextColor:"semantic.colors.textInverse",sendButtonBorderColor:"semantic.colors.primary",closeButtonColor:"palette.colors.gray.500",closeButtonBackgroundColor:"transparent",clearChatIconColor:"palette.colors.gray.500",clearChatBackgroundColor:"transparent",micIconColor:"palette.colors.gray.900",micBackgroundColor:"transparent",recordingIconColor:"palette.colors.white",recordingBackgroundColor:"palette.colors.error.500",tooltipBackground:"palette.colors.gray.900",tooltipForeground:"palette.colors.white"},gl={radiusSm:"palette.radius.md",radiusMd:"palette.radius.lg",radiusLg:"palette.radius.xl",launcherRadius:"palette.radius.full",buttonRadius:"palette.radius.full"};function is(e,n={}){if(!e)return{};let t={palette:{colors:{primary:{},gray:{},secondary:{},accent:{},success:{},warning:{},error:{}}},semantic:{colors:{interactive:{},feedback:{}}}};for(let[r,s]of Object.entries(e))if(s)if(r in as){let o=as[r],[a,i,d,c]=o.split(".");if(a==="palette"&&i==="colors"){let g=d;t.palette.colors[g]&&(t.palette.colors[g][c||"500"]=s)}else if(a==="semantic"){let g=o.replace("semantic.colors.","").split(".");g.length===1?t.semantic.colors[g[0]]=s:t.semantic.colors[g[0]]={...t.semantic.colors[g[0]],[g[1]]:s}}}else if(r in gl){t.palette.radius||(t.palette.radius={});let o=r.replace("radius","").toLowerCase();t.palette.radius[o||"md"]=s}else r==="inputFontFamily"?(t.palette.typography||(t.palette.typography={fontFamily:{}}),t.palette.typography.fontFamily={sans:s==="sans-serif"?"system-ui, sans-serif":void 0,serif:s==="serif"?"Georgia, serif":void 0,mono:s==="mono"?"monospace":void 0}):r==="inputFontWeight"?(t.palette.typography||(t.palette.typography={fontWeight:{}}),t.palette.typography.fontWeight={normal:s}):r==="panelBorder"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.border=s):r==="panelShadow"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.shadow=s):r==="panelBorderRadius"?(t.components||(t.components={}),t.components.panel||(t.components.panel={}),t.components.panel.borderRadius=s):r==="messageUserShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.user||(t.components.message.user={}),t.components.message.user.shadow=s):r==="messageAssistantShadow"?(t.components||(t.components={}),t.components.message||(t.components.message={}),t.components.message.assistant||(t.components.message.assistant={}),t.components.message.assistant.shadow=s):r==="toolBubbleShadow"?(t.components||(t.components={}),t.components.toolBubble||(t.components.toolBubble={}),t.components.toolBubble.shadow=s):r==="reasoningBubbleShadow"?(t.components||(t.components={}),t.components.reasoningBubble||(t.components.reasoningBubble={}),t.components.reasoningBubble.shadow=s):r==="composerShadow"&&(t.components||(t.components={}),t.components.composer||(t.components.composer={}),t.components.composer.shadow=s);return n.warn!==!1&&console.warn("[Persona Widget] v1 theme configuration detected. v1 themes are deprecated in v2.0.0. Please migrate to the new semantic token system. See https://persona.sh/docs/v2-migration for guidance."),t}function td(e){let n=[],t=e;if(!t)return{valid:!0,warnings:[]};let r=new Set(["panelBorder","panelShadow","panelBorderRadius","messageUserShadow","messageAssistantShadow","toolBubbleShadow","reasoningBubbleShadow","composerShadow"]),s=Object.keys(t).filter(o=>!(o in as||o in gl||o==="inputFontFamily"||o==="inputFontWeight"||o.startsWith("panel")||r.has(o)));return s.length>0&&n.push(`The following v1 theme properties have no v2 equivalent and will be ignored: ${s.join(", ")}`),{valid:!0,warnings:n}}var nd={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},ls=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),cs=(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];ls(o)&&ls(s)?t[r]=cs(o,s):t[r]=s}return t},rd=e=>ls(e)&&("palette"in e||"semantic"in e||"components"in e),ml=e=>{if(!e)return;let n=is(e,{warn:!1});return rd(e)?cs(n,e):n},Ro=()=>{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"},od=e=>{var t;let n=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return n==="light"?"light":n==="dark"?"dark":Ro()},fl=e=>od(e),sd=e=>Jr(e),ad=e=>{var t;let n=Jr(void 0,{validate:!1});return Jr({...e,palette:{...n.palette,colors:{...nd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},hl=e=>{let n=fl(e),t=ml(e==null?void 0:e.theme),r=ml(e==null?void 0:e.darkTheme);return n==="dark"?ad(cs(t,r)):sd(t)},id=e=>ss(e),Xn=(e,n)=>{var o;let t=hl(n),r=id(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)},ds=e=>{let n=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Ro())});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(Ro());t.addEventListener?(t.addEventListener("change",r),n.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),n.push(()=>t.removeListener(r)))}return()=>{n.forEach(t=>t())}};import{Idiomorph as ld}from"idiomorph";var yl=(e,n,t={})=>{let{preserveTypingAnimation:r=!0}=t;ld.morph(e,n.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&r&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function bl(e,n){var t,r,s,o,a,i,d,c,g,p,f,m,C,v,E,x,k,q;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:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(g=(c=e.llmContent)==null?void 0:c.length)!=null?g:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(C=(m=e.toolCall)==null?void 0:m.status)!=null?C:"",(x=(E=(v=e.reasoning)==null?void 0:v.chunks)==null?void 0:E.length)!=null?x:0,(q=(k=e.contentParts)==null?void 0:k.length)!=null?q:0,n].join("\0")}function xl(){return new Map}function vl(e,n,t){let r=e.get(n);return r&&r.fingerprint===t?r.wrapper:null}function Cl(e,n,t,r){e.set(n,{fingerprint:t,wrapper:r})}function wl(e,n){for(let t of e.keys())n.has(t)||e.delete(t)}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var cd={side:"right",width:"420px",collapsedWidth:"72px"},Jt=e=>{var n,t;return((t=(n=e==null?void 0:e.launcher)==null?void 0:n.mountMode)!=null?t:"floating")==="docked"},Kr=e=>{var n,t;return{...cd,...(t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock)!=null?t:{}}};var pn={"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 Yr=(e,n)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(Tt=Te.pop())!=null?Tt:"";for(let Fe of Te){let xt=Fe.split(`
7
+ `),$t="message",vt="";for(let M of xt)M.startsWith("event:")?$t=M.replace("event:","").trim():M.startsWith("data:")&&(vt+=M.replace("data:","").trim());if(!vt)continue;let C;try{C=JSON.parse(vt)}catch(M){t({type:"error",error:M instanceof Error?M:new Error("Failed to parse chat stream payload")});continue}let _e=$t!=="message"?$t:(se=C.type)!=null?se:"message";if((re=this.onSSEEvent)==null||re.call(this,_e,C),this.parseSSEEvent){m.current=f;let M=await this.handleCustomSSEEvent(C,t,m,p,c);if(m.current&&!f&&(f=m.current),M)continue}if(_e==="reason_start"){let M=(Ue=R(C,!0))!=null?Ue:`reason-${c()}`,E=U(M);E.reasoning=(z=E.reasoning)!=null?z:{id:M,status:"streaming",chunks:[]},E.reasoning.startedAt=(de=E.reasoning.startedAt)!=null?de:Q((te=C.startedAt)!=null?te:C.timestamp),E.reasoning.completedAt=void 0,E.reasoning.durationMs=void 0,E.streaming=!0,E.reasoning.status="streaming",p(E)}else if(_e==="reason_delta"||_e==="reason_chunk"){let M=(G=(Qe=R(C,!1))!=null?Qe:R(C,!0))!=null?G:`reason-${c()}`,E=U(M);E.reasoning=(Y=E.reasoning)!=null?Y:{id:M,status:"streaming",chunks:[]},E.reasoning.startedAt=(Ne=E.reasoning.startedAt)!=null?Ne:Q((tt=C.startedAt)!=null?tt:C.timestamp);let H=(qt=(Mt=(je=C.reasoningText)!=null?je:C.text)!=null?Mt:C.delta)!=null?qt:"";if(H&&C.hidden!==!0&&E.reasoning.chunks.push(String(H)),E.reasoning.status=C.done?"complete":"streaming",C.done){E.reasoning.completedAt=Q((ue=C.completedAt)!=null?ue:C.timestamp);let ie=(Ye=E.reasoning.startedAt)!=null?Ye:Date.now();E.reasoning.durationMs=Math.max(0,((ke=E.reasoning.completedAt)!=null?ke:Date.now())-ie)}E.streaming=E.reasoning.status!=="complete",p(E)}else if(_e==="reason_complete"){let M=(Ve=(ot=R(C,!1))!=null?ot:R(C,!0))!=null?Ve:`reason-${c()}`,E=x.get(M);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=Q((nt=C.completedAt)!=null?nt:C.timestamp);let ie=(Rt=E.reasoning.startedAt)!=null?Rt:Date.now();E.reasoning.durationMs=Math.max(0,((Ht=E.reasoning.completedAt)!=null?Ht:Date.now())-ie),E.streaming=!1,p(E)}let H=F(C);H&&S.byStep.delete(H)}else if(_e==="tool_start"){let M=(kt=ye(C,!0))!=null?kt:`tool-${c()}`,E=(N=C.toolName)!=null?N:C.name;if(we(E)){le.add(M);continue}let H=ce(M),ie=(X=H.toolCall)!=null?X:{id:M,status:"pending"};ie.name=E!=null?E:ie.name,ie.status="running",C.args!==void 0?ie.args=C.args:C.parameters!==void 0&&(ie.args=C.parameters),ie.startedAt=(be=ie.startedAt)!=null?be:Q((_=C.startedAt)!=null?_:C.timestamp),ie.completedAt=void 0,ie.durationMs=void 0,H.toolCall=ie,H.streaming=!0;let Me=C.agentContext;(Me||C.executionId)&&(H.agentMetadata={executionId:(xe=Me==null?void 0:Me.executionId)!=null?xe:C.executionId,iteration:(Ae=Me==null?void 0:Me.iteration)!=null?Ae:C.iteration}),p(H)}else if(_e==="tool_chunk"||_e==="tool_delta"){let M=(st=(Ee=ye(C,!1))!=null?Ee:ye(C,!0))!=null?st:`tool-${c()}`;if(le.has(M))continue;let E=ce(M),H=(Be=E.toolCall)!=null?Be:{id:M,status:"running"};H.startedAt=(ze=H.startedAt)!=null?ze:Q((We=C.startedAt)!=null?We:C.timestamp);let ie=(xn=(Ft=(pe=C.text)!=null?pe:C.delta)!=null?Ft:C.message)!=null?xn:"";ie&&(H.chunks=(Un=H.chunks)!=null?Un:[],H.chunks.push(String(ie))),H.status="running",E.toolCall=H,E.streaming=!0;let Me=C.agentContext;(Me||C.executionId)&&(E.agentMetadata=(Nn=E.agentMetadata)!=null?Nn:{executionId:(Dn=Me==null?void 0:Me.executionId)!=null?Dn:C.executionId,iteration:(ar=Me==null?void 0:Me.iteration)!=null?ar:C.iteration}),p(E)}else if(_e==="tool_complete"){let M=(Xe=(Tn=ye(C,!1))!=null?Tn:ye(C,!0))!=null?Xe:`tool-${c()}`;if(le.has(M)){le.delete(M);continue}let E=ce(M),H=(tn=E.toolCall)!=null?tn:{id:M,status:"running"};H.status="complete",C.result!==void 0&&(H.result=C.result),typeof C.duration=="number"&&(H.duration=C.duration),H.completedAt=Q((un=C.completedAt)!=null?un:C.timestamp);let ie=(K=C.duration)!=null?K:C.executionTime;if(typeof ie=="number")H.durationMs=ie;else{let Lt=(Mn=H.startedAt)!=null?Mn:Date.now();H.durationMs=Math.max(0,((on=H.completedAt)!=null?on:Date.now())-Lt)}E.toolCall=H,E.streaming=!1;let Me=C.agentContext;(Me||C.executionId)&&(E.agentMetadata=(kn=E.agentMetadata)!=null?kn:{executionId:(pt=Me==null?void 0:Me.executionId)!=null?pt:C.executionId,iteration:(sn=Me==null?void 0:Me.iteration)!=null?sn:C.iteration}),p(E);let at=w(C);at&&v.byCall.delete(at)}else if(_e==="step_chunk"||_e==="step_delta"){let M=C.stepType,E=C.executionType;if(M==="tool"||E==="context")continue;let H=P(),ie=(Vn=(Lr=(ir=(kr=C.text)!=null?kr:C.delta)!=null?ir:C.content)!=null?Lr:C.chunk)!=null?Vn:"";if(ie){let at=((vn=ne.get(H.id))!=null?vn:"")+ie;H.rawContent=at,V.has(H.id)||V.set(H.id,this.createStreamParser());let Lt=V.get(H.id),Ct=at.trim().startsWith("{")||at.trim().startsWith("[");if(Ct&&ne.set(H.id,at),Lt.__isPlainTextParser===!0){H.content+=ie,ne.delete(H.id),V.delete(H.id),H.rawContent=void 0,p(H);continue}let Pt=Lt.processChunk(at);if(Pt instanceof Promise)Pt.then(it=>{var At;let ct=typeof it=="string"?it:(At=it==null?void 0:it.text)!=null?At:null;if(ct!==null&&ct.trim()!==""){let dt=f;dt&&dt.id===H.id&&(dt.content=ct,p(dt))}else if(!Ct&&!at.trim().startsWith("<")){let dt=f;dt&&dt.id===H.id&&(dt.content+=ie,ne.delete(dt.id),V.delete(dt.id),dt.rawContent=void 0,p(dt))}}).catch(()=>{H.content+=ie,ne.delete(H.id),V.delete(H.id),H.rawContent=void 0,p(H)});else{let it=typeof Pt=="string"?Pt:(Jn=Pt==null?void 0:Pt.text)!=null?Jn:null;it!==null&&it.trim()!==""?(H.content=it,p(H)):!Ct&&!at.trim().startsWith("<")&&(H.content+=ie,ne.delete(H.id),V.delete(H.id),H.rawContent=void 0,p(H))}}if(C.isComplete){let Me=(Cn=(bt=C.result)==null?void 0:bt.response)!=null?Cn:H.content;if(Me){let at=ne.get(H.id),Lt=at!=null?at:J(Me);H.rawContent=Lt;let Ct=V.get(H.id),Bt=null,Pt=!1;if(Ct&&(Bt=Ct.getExtractedText(),Bt===null&&(Bt=Io(Lt)),Bt===null)){let it=Ct.processChunk(Lt);it instanceof Promise?(Pt=!0,it.then(ct=>{var dt;let At=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(At!==null){let Dt=f;Dt&&Dt.id===H.id&&(Dt.content=At,Dt.streaming=!1,V.delete(Dt.id),ne.delete(Dt.id),p(Dt))}})):Bt=typeof it=="string"?it:(Pr=it==null?void 0:it.text)!=null?Pr:null}if(!Pt){Bt!==null&&Bt.trim()!==""?H.content=Bt:ne.has(H.id)||(H.content=J(Me));let it=V.get(H.id);if(it){let ct=(On=it.close)==null?void 0:On.call(it);ct instanceof Promise&&ct.catch(()=>{}),V.delete(H.id)}ne.delete(H.id),H.streaming=!1,p(H)}}}}else if(_e==="step_complete"){let M=C.stepType,E=C.executionType;if(M==="tool"||E==="context")continue;let H=(wn=C.result)==null?void 0:wn.response,ie=P();if(H!=null){let Me=V.get(ie.id),at=!1,Lt=!1;if(Me){let Ct=Me.getExtractedText(),Bt=ne.get(ie.id),Pt=Bt!=null?Bt:J(H);if(ie.rawContent=Pt,Ct!==null&&Ct.trim()!=="")ie.content=Ct,at=!0;else{let it=Io(Pt);if(it!==null)ie.content=it,at=!0;else{let ct=Me.processChunk(Pt);if(ct instanceof Promise)Lt=!0,ct.then(At=>{var Dt;let dt=typeof At=="string"?At:(Dt=At==null?void 0:At.text)!=null?Dt:null;if(dt!==null&&dt.trim()!==""){let Xt=f;Xt&&Xt.id===ie.id&&(Xt.content=dt,Xt.streaming=!1,V.delete(Xt.id),ne.delete(Xt.id),p(Xt))}else{let Xt=Me.getExtractedText(),ln=f;ln&&ln.id===ie.id&&(Xt!==null&&Xt.trim()!==""?ln.content=Xt:ne.has(ln.id)||(ln.content=J(H)),ln.streaming=!1,V.delete(ln.id),ne.delete(ln.id),p(ln))}});else{let At=typeof ct=="string"?ct:(D=ct==null?void 0:ct.text)!=null?D:null;if(At!==null&&At.trim()!=="")ie.content=At,at=!0;else{let dt=Me.getExtractedText();dt!==null&&dt.trim()!==""&&(ie.content=dt,at=!0)}}}}}if(!Lt){if(!ie.rawContent){let Ct=ne.get(ie.id);ie.rawContent=Ct!=null?Ct:J(H)}if(!at&&!ne.has(ie.id)&&(ie.content=J(H)),Me){let Ct=(Fn=Me.close)==null?void 0:Fn.call(Me);Ct instanceof Promise&&Ct.catch(()=>{})}V.delete(ie.id),ne.delete(ie.id),ie.streaming=!1,p(ie)}}else V.delete(ie.id),ne.delete(ie.id),ie.streaming=!1,p(ie)}else if(_e==="flow_complete"){let M=($n=C.result)==null?void 0:$n.response;if(M!=null){let E=P(),H=ne.get(E.id),ie=H!=null?H:J(M);E.rawContent=ie;let Me=J(M),at=V.get(E.id);if(at){let Bt=Io(ie);if(Bt!==null)Me=Bt;else{let Pt=at.processChunk(ie);Pt instanceof Promise&&Pt.then(ct=>{var dt;let At=typeof ct=="string"?ct:(dt=ct==null?void 0:ct.text)!=null?dt:null;if(At!==null){let Dt=f;Dt&&Dt.id===E.id&&(Dt.content=At,Dt.streaming=!1,p(Dt))}});let it=at.getExtractedText();it!==null&&(Me=it)}}V.delete(E.id),ne.delete(E.id);let Lt=Me!==E.content,Ct=E.streaming!==!1;Lt&&(E.content=Me),E.streaming=!1,(Lt||Ct)&&p(E)}else if(f!==null){let E=f;V.delete(E.id),ne.delete(E.id),E.streaming!==!1&&(E.streaming=!1,p(E))}t({type:"status",status:"idle"})}else if(_e==="agent_start")fe={executionId:C.executionId,agentId:(Ir=C.agentId)!=null?Ir:"virtual",agentName:(Ln=C.agentName)!=null?Ln:"",status:"running",currentIteration:0,maxTurns:(Kn=C.maxTurns)!=null?Kn:1,startedAt:Q(C.startedAt)};else if(_e==="agent_iteration_start"){if(fe&&(fe.currentIteration=C.iteration),ut==="separate"&&C.iteration>1){let M=f;M&&(M.streaming=!1,p(M),wt.set(C.iteration-1,M),f=null)}}else if(_e!=="agent_turn_start"){if(_e==="agent_turn_delta"){if(C.contentType==="text"){let M=P();M.content+=(Wr=C.delta)!=null?Wr:"",M.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:fe==null?void 0:fe.agentName},p(M)}else if(C.contentType==="thinking"){let M=(Pn=C.turnId)!=null?Pn:`agent-think-${C.iteration}`,E=U(M);E.reasoning=(In=E.reasoning)!=null?In:{id:M,status:"streaming",chunks:[]},E.reasoning.chunks.push((lr=C.delta)!=null?lr:""),E.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},p(E)}else if(C.contentType==="tool_input"){let M=(cr=C.toolCallId)!=null?cr:v.lastId;if(M){let E=b.get(M);E!=null&&E.toolCall&&(E.toolCall.chunks=(lo=E.toolCall.chunks)!=null?lo:[],E.toolCall.chunks.push((co=C.delta)!=null?co:""),p(E))}}}else if(_e==="agent_turn_complete"){let M=C.turnId;if(M){let E=x.get(M);if(E!=null&&E.reasoning){E.reasoning.status="complete",E.reasoning.completedAt=Q(C.completedAt);let H=(po=E.reasoning.startedAt)!=null?po:Date.now();E.reasoning.durationMs=Math.max(0,((Rr=E.reasoning.completedAt)!=null?Rr:Date.now())-H),E.streaming=!1,p(E)}}}else if(_e==="agent_tool_start"){let M=(dr=C.toolCallId)!=null?dr:`agent-tool-${c()}`;ve(w(C),M);let E=ce(M),H=(qe=E.toolCall)!=null?qe:{id:M,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};H.name=(an=(Hr=C.toolName)!=null?Hr:C.name)!=null?an:H.name,H.status="running",C.parameters!==void 0&&(H.args=C.parameters),H.startedAt=Q((Gt=C.startedAt)!=null?Gt:C.timestamp),E.toolCall=H,E.streaming=!0,E.agentMetadata={executionId:C.executionId,iteration:C.iteration},p(E)}else if(_e==="agent_tool_delta"){let M=(uo=C.toolCallId)!=null?uo:v.lastId;if(M){let E=(go=b.get(M))!=null?go:ce(M);E.toolCall&&(E.toolCall.chunks=(Br=E.toolCall.chunks)!=null?Br:[],E.toolCall.chunks.push((Yn=C.delta)!=null?Yn:""),E.toolCall.status="running",E.streaming=!0,p(E))}}else if(_e==="agent_tool_complete"){let M=(Wn=C.toolCallId)!=null?Wn:v.lastId;if(M){let E=(mo=b.get(M))!=null?mo:ce(M);if(E.toolCall){E.toolCall.status="complete",C.result!==void 0&&(E.toolCall.result=C.result),typeof C.executionTime=="number"&&(E.toolCall.durationMs=C.executionTime),E.toolCall.completedAt=Q((fo=C.completedAt)!=null?fo:C.timestamp),E.streaming=!1,p(E);let H=w(C);H&&v.byCall.delete(H)}}}else if(_e!=="agent_iteration_complete"){if(_e==="agent_reflection"||_e==="agent_reflect"){let M=`agent-reflection-${C.executionId}-${C.iteration}`,E={id:M,role:"assistant",content:(ho=C.reflection)!=null?ho:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:M,status:"complete",chunks:[(ts=C.reflection)!=null?ts:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};p(E)}else if(_e==="agent_complete"){fe&&(fe.status=C.success?"complete":"error",fe.completedAt=Q(C.completedAt),fe.stopReason=C.stopReason);let M=f;M&&(M.streaming=!1,p(M)),t({type:"status",status:"idle"})}else if(_e==="agent_error"){let M=typeof C.error=="string"?C.error:(Xn=(Gn=C.error)==null?void 0:Gn.message)!=null?Xn:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",M):t({type:"error",error:new Error(M)})}else if(_e!=="agent_ping")if(_e==="agent_approval_start"){let M=(mt=C.approvalId)!=null?mt:`approval-${c()}`,E={id:`approval-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:M,status:"pending",agentId:(pr=fe==null?void 0:fe.agentId)!=null?pr:"virtual",executionId:(Dr=(ur=C.executionId)!=null?ur:fe==null?void 0:fe.executionId)!=null?Dr:"",toolName:(Nr=C.toolName)!=null?Nr:"",toolType:C.toolType,description:(Fr=C.description)!=null?Fr:`Execute ${(Or=C.toolName)!=null?Or:"tool"}`,parameters:C.parameters}};p(E)}else if(_e==="step_await"&&C.awaitReason==="approval_required"){let M=(Jt=C.approvalId)!=null?Jt:`approval-${c()}`,E={id:`approval-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:M,status:"pending",agentId:(nn=fe==null?void 0:fe.agentId)!=null?nn:"virtual",executionId:(De=(Rn=C.executionId)!=null?Rn:fe==null?void 0:fe.executionId)!=null?De:"",toolName:($r=C.toolName)!=null?$r:"",toolType:C.toolType,description:(gn=C.description)!=null?gn:`Execute ${(Zn=C.toolName)!=null?Zn:"tool"}`,parameters:C.parameters}};p(E)}else if(_e==="agent_approval_complete"){let M=C.approvalId;if(M){let H={id:`approval-${M}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:M,status:(yo=C.decision)!=null?yo:"approved",agentId:(gr=fe==null?void 0:fe.agentId)!=null?gr:"virtual",executionId:(Qn=(mr=C.executionId)!=null?mr:fe==null?void 0:fe.executionId)!=null?Qn:"",toolName:(_n=C.toolName)!=null?_n:"",description:(bo=C.description)!=null?bo:"",resolvedAt:Date.now()}};p(H)}}else if(_e==="artifact_start"||_e==="artifact_delta"||_e==="artifact_update"||_e==="artifact_complete"){if(_e==="artifact_start"){let M=C.artifactType,E=String(C.id),H=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:E,artifactType:M,title:H,component:typeof C.component=="string"?C.component:void 0}),Ce.set(E,{markdown:"",title:H}),!ee.has(E)){ee.add(E);let ie={id:`artifact-ref-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:E,title:H,artifactType:M,status:"streaming"}})};q.set(E,ie),p(ie)}}else if(_e==="artifact_delta"){let M=String(C.id),E=typeof C.delta=="string"?C.delta:String((xo=C.delta)!=null?xo:"");t({type:"artifact_delta",id:M,artDelta:E});let H=Ce.get(M);H&&(H.markdown+=E)}else if(_e==="artifact_update"){let M=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:M,component:typeof C.component=="string"?C.component:void 0})}else if(_e==="artifact_complete"){let M=String(C.id);t({type:"artifact_complete",id:M});let E=q.get(M);if(E){E.streaming=!1;try{let H=JSON.parse((mn=E.rawContent)!=null?mn:"{}");if(H.props){H.props.status="complete";let ie=Ce.get(M);ie!=null&&ie.markdown&&(H.props.markdown=ie.markdown)}E.rawContent=JSON.stringify(H)}catch{}Ce.delete(M),p(E),q.delete(M)}}}else if(_e==="transcript_insert"){let M=C.message;if(!M||typeof M!="object")continue;let E=String((er=M.id)!=null?er:`msg-${c()}`),H=M.role,Me={id:E,role:H==="user"?"user":H==="system"?"system":"assistant",content:typeof M.content=="string"?M.content:"",rawContent:typeof M.rawContent=="string"?M.rawContent:void 0,createdAt:typeof M.createdAt=="string"?M.createdAt:new Date().toISOString(),streaming:M.streaming===!0,...typeof M.variant=="string"?{variant:M.variant}:{},sequence:c()};if(p(Me),Me.rawContent)try{let at=JSON.parse(Me.rawContent),Lt=(vo=at==null?void 0:at.props)==null?void 0:vo.artifactId;typeof Lt=="string"&&ee.add(Lt)}catch{}f=null,m.current=null,V.delete(E),ne.delete(E)}else _e==="error"&&C.error&&t({type:"error",error:C.error instanceof Error?C.error:new Error(String(C.error))})}}}}}};function Uc(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Gr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function yr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Wo="[Image]";function Vc(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Jc(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function Kc(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function Yc(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function ds(e){return{type:"text",text:e}}function Gc(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 Xc(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 Zc(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 pl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Qc=["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"],Hn=[...pl,...Qc];function ed(e){return pl.includes(e)||e.startsWith("image/")}function Ro(e){return ed(e.type)}async function ul(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ro(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 gl(e,r=Hn,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 td(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function ml(e,r){let t=td(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 Ho=class{constructor(r=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=r}ensureContext(){if(!this.ctx){let t=typeof window!="undefined"?window:void 0;if(!t)throw new Error("AudioPlaybackManager requires a browser environment");let n=t.AudioContext||t.webkitAudioContext;this.ctx=new n({sampleRate:this.sampleRate})}let r=this.ctx;return r.state==="suspended"&&r.resume(),r}enqueue(r){if(r.length===0)return;let t=r;if(this.remainder){let d=new Uint8Array(this.remainder.length+r.length);d.set(this.remainder),d.set(r,this.remainder.length),t=d,this.remainder=null}if(t.length%2!==0&&(this.remainder=new Uint8Array([t[t.length-1]]),t=t.subarray(0,t.length-1)),t.length===0)return;let n=this.ensureContext(),s=this.pcmToFloat32(t),o=n.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=n.createBufferSource();a.buffer=o,a.connect(n.destination);let i=n.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){this.streamEnded=!0,this.checkFinished()}flush(){for(let r of this.activeSources)try{r.stop(),r.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.remainder=null}isPlaying(){return this.playing}onFinished(r){this.finishedCallbacks.push(r)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let r=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let t of r)t()}}pcmToFloat32(r){let t=Math.floor(r.length/2),n=new Float32Array(t),s=new DataView(r.buffer,r.byteOffset,r.byteLength);for(let o=0;o<t;o++){let a=s.getInt16(o*2,!0);n[o]=a/32768}return n}};var Bo=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 u=0;u<a.length;u++)i+=a[u]*a[u];let d=Math.sqrt(i/a.length);(n==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Xr=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 Bo;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var r,t,n;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(r=this.config)==null?void 0:r.host,i=(t=this.config)==null?void 0:t.agentId,d=(n=this.config)==null?void 0:n.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let c=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,p=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let x=!1,b=v=>{x||(x=!0,clearTimeout(S),m(new Error(v)))},S=setTimeout(()=>b("WebSocket connection timed out."+p),1e4);this.ws.addEventListener("open",()=>{x||(x=!0,clearTimeout(S),f())},{once:!0}),this.ws.addEventListener("error",()=>{b("WebSocket connection failed to "+u+"."+p)},{once:!0}),this.ws.addEventListener("close",v=>{if(!v.wasClean&&!x){let T=v.code!==1006?` (code ${v.code})`:"";b("WebSocket connection failed"+T+"."+p)}},{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 Ho(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(t=>t("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(t=>t("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(r))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(r=>r("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var r,t,n,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let c=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(c)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(t=(r=this.config)==null?void 0:r.pauseDuration)!=null?t:2e3,d=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=c=>{c.data.size>0&&this.audioChunks.push(c.data)},this.mediaRecorder.onstop=async()=>{var c;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let u=((c=this.mediaRecorder)==null?void 0:c.mimeType)||"audio/webm",p=new Blob(this.audioChunks,{type:u});await this.sendAudio(p),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await d.play()}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}onProcessingStart(r){this.processingStartCallbacks.push(r)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(r=>r("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var rr=class{constructor(r={}){this.config=r;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(r=>r("connected"))}async startListening(){var r,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let n=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!n)throw new Error("Browser speech recognition not supported");this.recognition=new n,this.recognition.lang=((r=this.config)==null?void 0:r.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(n){throw this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error")),n}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(r=>r("idle"))}onResult(r){this.resultCallbacks.push(r)}onError(r){this.errorCallbacks.push(r)}onStatusChange(r){this.statusCallbacks.push(r)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(r=>r("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function br(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xr(e.runtype);case"browser":if(!rr.isSupported())throw new Error("Browser speech recognition not supported");return new rr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ps(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return br({type:"runtype",runtype:e.runtype});if(rr.isSupported())return br({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Do(e){try{return ps(e),!0}catch{return!1}}var Zr=class e{constructor(r={},t){this.config=r;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.handleEvent=r=>{var t,n,s,o,a,i,d;r.type==="message"?(this.upsertMessage(r.message),(t=r.message.agentMetadata)!=null&&t.executionId&&(this.agentExecution?r.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=r.message.agentMetadata.iteration):this.agentExecution={executionId:r.message.agentMetadata.executionId,agentId:"",agentName:(n=r.message.agentMetadata.agentName)!=null?n:"",status:"running",currentIteration:(s=r.message.agentMetadata.iteration)!=null?s:0,maxTurns:0})):r.type==="status"?(this.setStatus(r.status),r.status==="connecting"?this.setStreaming(!0):(r.status==="idle"||r.status==="error")&&(this.setStreaming(!1),this.abortController=null,((o=this.agentExecution)==null?void 0:o.status)==="running"&&(this.agentExecution.status=r.status==="error"?"error":"complete"))):r.type==="error"?(this.setStatus("error"),this.setStreaming(!1),this.abortController=null,((a=this.agentExecution)==null?void 0:a.status)==="running"&&(this.agentExecution.status="error"),(d=(i=this.callbacks).onError)==null||d.call(i,r.error)):(r.type==="artifact_start"||r.type==="artifact_delta"||r.type==="artifact_update"||r.type==="artifact_complete")&&this.applyArtifactStreamEvent(r)};var n;this.messages=[...(n=r.initialMessages)!=null?n:[]].map(s=>{var o;return{...s,sequence:(o=s.sequence)!=null?o:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new hr(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 Do((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=br(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",d=(s=a.processingErrorText)!=null?s:"Voice processing failed. Please try again.";this.voiceProvider.onProcessingStart&&this.voiceProvider.onProcessingStart(()=>{let c=this.injectMessage({role:"user",content:i,streaming:!1,voiceProcessing:!0});this.pendingVoiceUserMessageId=c.id;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}),this.voiceProvider.onResult(c=>{var u,p,f,m,x,b;if(c.provider==="browser")c.text&&c.text.trim()&&this.sendMessage(c.text,{viaVoice:!0});else if(c.provider==="runtype"){this.pendingVoiceUserMessageId&&((u=c.transcript)!=null&&u.trim())?this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c.transcript.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(p=c.transcript)!=null&&p.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let S=(b=this.pendingVoiceAssistantMessageId)!=null?b:(x=[...this.messages].reverse().find(v=>v.role==="assistant"))==null?void 0:x.id;S&&this.ttsSpokenMessageIds.add(S)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,p;this.voiceStatus=c,this.voiceActive=c==="listening",(p=(u=this.callbacks).onVoiceStatusChanged)==null||p.call(u,c)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(r){console.error("Failed to start voice:",r)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,n,s,o,a,i,d,c,u;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let r=this.config.voiceRecognition.provider;switch(r.type){case"runtype":return{type:"runtype",runtype:{agentId:((n=r.runtype)==null?void 0:n.agentId)||"",clientToken:((s=r.runtype)==null?void 0:s.clientToken)||"",host:(o=r.runtype)==null?void 0:o.host,voiceId:(a=r.runtype)==null?void 0:a.voiceId,pauseDuration:(i=r.runtype)==null?void 0:i.pauseDuration,silenceThreshold:(d=r.runtype)==null?void 0:d.silenceThreshold}};case"browser":return{type:"browser",browser:{language:((c=r.browser)==null?void 0:c.language)||"en-US",continuous:(u=r.browser)==null?void 0:u.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 hr(this.config),t&&this.client.setSSEEventCallback(t)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(r){this.handleEvent(r)}injectMessage(r){let{role:t,content:n,llmContent:s,contentParts:o,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Gr():t==="assistant"?yr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...s!==void 0&&{llmContent:s},...o!==void 0&&{contentParts:o},...u!==void 0&&{voiceProcessing:u}};return this.upsertMessage(f),f}injectAssistantMessage(r){return this.injectMessage({...r,role:"assistant"})}injectUserMessage(r){return this.injectMessage({...r,role:"user"})}injectSystemMessage(r){return this.injectMessage({...r,role:"system"})}injectMessageBatch(r){let t=[];for(let n of r){let{role:s,content:o,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:p=!1}=n,m={id:d!=null?d:s==="user"?Gr():s==="assistant"?yr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:s,content:o,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:p,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i}};t.push(m)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}async sendMessage(r,t){var c,u,p,f,m;let n=r.trim();if(!n&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort();let s=Gr(),o=yr(),a={id:s,role:"user",content:n||Wo,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(x){let b=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!b){let S={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(S)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(x instanceof Error?(p=(u=this.callbacks).onError)==null||p.call(u,x):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(x))))}}async continueConversation(){var s,o,a,i,d;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=yr();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 u={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(u),this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,c instanceof Error?(a=(o=this.callbacks).onError)==null||a.call(o,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c)))}}async connectStream(r,t){var s,o,a;if(this.streaming)return;(s=this.abortController)==null||s.abort();let n=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(r,this.handleEvent,t==null?void 0:t.assistantMessageId)}catch(i){this.setStatus("error"),this.setStreaming(!1),this.abortController=null,(a=(o=this.callbacks).onError)==null||a.call(o,i instanceof Error?i:new Error(String(i)))}}async resolveApproval(r,t){var d,c,u;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 p;if(i?p=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):p=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),p){let f=null;if(p instanceof Response){if(!p.ok){let m=await p.json().catch(()=>null);throw new Error((d=m==null?void 0:m.error)!=null?d:`Approval request failed: ${p.status}`)}f=p.body}else p instanceof ReadableStream&&(f=p);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(p){(u=(c=this.callbacks).onError)==null||u.call(c,p instanceof Error?p:new Error(String(p)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var d,c;let s=new Date(t.createdAt).getTime(),o=new Date(n.createdAt).getTime();if(!Number.isNaN(s)&&!Number.isNaN(o)&&s!==o)return s-o;let a=(d=t.sequence)!=null?d:0,i=(c=n.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(n.id)})}};var h=(e,r)=>{let t=document.createElement(e);return r&&(t.className=r),t},An=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as nd from"lucide";var me=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=nd[s];return o?rd(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 rd(e,r,t,n){if(!e||!Array.isArray(e))return null;let s=document.createElementNS("http://www.w3.org/2000/svg","svg");return s.setAttribute("width",String(r)),s.setAttribute("height",String(r)),s.setAttribute("viewBox","0 0 24 24"),s.setAttribute("fill","none"),s.setAttribute("stroke",t),s.setAttribute("stroke-width",String(n)),s.setAttribute("stroke-linecap","round"),s.setAttribute("stroke-linejoin","round"),s.setAttribute("aria-hidden","true"),e.forEach(o=>{if(Array.isArray(o)&&o.length>=2){let a=o[0],i=o[1];if(i){let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),s.appendChild(d)}}}),s}var No={allowedTypes:Hn,maxFileSize:10*1024*1024,maxFiles:4};function od(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sd(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 xr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:No.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:No.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:No.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:No.allowedTypes),r.maxFileSize!==void 0&&(this.config.maxFileSize=r.maxFileSize),r.maxFiles!==void 0&&(this.config.maxFiles=r.maxFiles),r.onFileRejected!==void 0&&(this.config.onFileRejected=r.onFileRejected),r.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=r.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(r=>r.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(r){!r||r.length===0||await this.handleFiles(Array.from(r))}async handleFiles(r){var t,n,s,o,a,i,d;if(r.length){for(let c of r){if(this.attachments.length>=this.config.maxFiles){(n=(t=this.config).onFileRejected)==null||n.call(t,c,"count");continue}let u=gl(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let p=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,p);continue}try{let p=await ul(c),f=Ro(c)?URL.createObjectURL(c):null,m={id:od(),file:c,previewUrl:f,contentPart:p};this.attachments.push(m),this.renderPreview(m)}catch(p){console.error("[AttachmentManager] Failed to process file:",p)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(d=>d.id===r);if(t===-1)return;let n=this.attachments[t];n.previewUrl&&URL.revokeObjectURL(n.previewUrl),this.attachments.splice(t,1);let s=(o=this.previewsContainer)==null?void 0:o.querySelector(`[data-attachment-id="${r}"]`);s&&s.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var r,t;for(let n of this.attachments)n.previewUrl&&URL.revokeObjectURL(n.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(r=this.config).onAttachmentsChange)==null||t.call(r,this.getAttachments())}renderPreview(r){if(!this.previewsContainer)return;let t=Ro(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=sd(r.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=h("span");c.textContent=ml(r.file.type,r.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),n.appendChild(a)}let s=h("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");s.type="button",s.setAttribute("aria-label","Remove attachment"),s.style.position="absolute",s.style.top="-4px",s.style.right="-4px",s.style.width="18px",s.style.height="18px",s.style.borderRadius="50%",s.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",s.style.border="none",s.style.cursor="pointer",s.style.display="flex",s.style.alignItems="center",s.style.justifyContent="center",s.style.padding="0";let o=me("x",10,"var(--persona-text-inverse, #ffffff)",2);o?s.appendChild(o):(s.textContent="\xD7",s.style.color="var(--persona-text-inverse, #ffffff)",s.style.fontSize="14px",s.style.lineHeight="1"),s.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(r.id)}),n.appendChild(s),this.previewsContainer.appendChild(n)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(r,t){return new e({allowedTypes:r==null?void 0:r.allowedTypes,maxFileSize:r==null?void 0:r.maxFileSize,maxFiles:r==null?void 0:r.maxFiles,onFileRejected:r==null?void 0:r.onFileRejected,onAttachmentsChange:t})}};var fl={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},hl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.gray.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.100",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.500",hover:"palette.colors.primary.600",focus:"palette.colors.primary.700",active:"palette.colors.primary.800",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.primary.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},yl={button:{primary:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.text",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"semantic.colors.surface",placeholder:"semantic.colors.textMuted",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"semantic.colors.interactive.focus",ring:"semantic.colors.interactive.focus"}},launcher:{size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"semantic.colors.surface",border:"semantic.colors.border",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"semantic.colors.primary",iconForeground:"semantic.colors.textInverse",titleForeground:"semantic.colors.primary",subtitleForeground:"semantic.colors.textMuted",actionIconForeground:"semantic.colors.textMuted"},message:{user:{background:"semantic.colors.primary",text:"semantic.colors.textInverse",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"semantic.colors.container",text:"semantic.colors.text",borderRadius:"palette.radius.lg",border:"semantic.colors.border",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"semantic.colors.container",foreground:"semantic.colors.text"},link:{foreground:"semantic.colors.accent"},prose:{fontFamily:"inherit"}},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"palette.colors.warning.50",border:"palette.colors.warning.200",text:"palette.colors.gray.900"},approve:{background:"palette.colors.success.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"palette.colors.error.500",foreground:"palette.colors.gray.50",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function Qr(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."))?Qr(e,n):n}function us(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let d=Qr(e,a);d!==void 0&&(r[i]={path:i,value:d,type:s.includes("color")?"color":s.includes("spacing")?"spacing":s.includes("typography")?"typography":s.includes("shadow")?"shadow":s.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(e.palette,"palette"),t(e.semantic,"semantic"),t(e.components,"components"),r}function bl(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 xl(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]=xl(o,s):t[n]=s}return t}function ad(e,r){return r?xl(e,r):e}function eo(e,r={}){var s,o,a,i,d,c,u,p,f,m,x,b,S;let t={palette:fl,semantic:hl,components:yl},n={palette:{...t.palette,...e==null?void 0:e.palette,colors:{...t.palette.colors,...(s=e==null?void 0:e.palette)==null?void 0:s.colors},spacing:{...t.palette.spacing,...(o=e==null?void 0:e.palette)==null?void 0:o.spacing},typography:{...t.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...e==null?void 0:e.semantic,colors:{...t.semantic.colors,...(u=e==null?void 0:e.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(f=(p=e==null?void 0:e.semantic)==null?void 0:p.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...t.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...t.semantic.typography,...(S=e==null?void 0:e.semantic)==null?void 0:S.typography}},components:ad(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let v=bl(n);if(!v.valid)throw new Error(`Theme validation failed: ${v.errors.map(T=>T.message).join(", ")}`)}if(r.plugins)for(let v of r.plugins)n=v.transform(n);return n}function gs(e){var x,b,S,v,T,F,w,P,W,R,U,ve,le,q,ee,Ce,we,ye,ce,Q,J,V,ne,fe,wt,ut,gt,Tt,se,re,Ue,z,te,de,Qe,G,Y,tt,Ne,je,Mt,qt,ue,Ye,ke,ot,Ve,nt,Rt,Ht,kt,N,X,_,be,xe,Ae,Ee,st,Be,We,ze,pe,Ft,xn,Un,Dn,ar,Nn,Tn,Xe,tn,un;let r=us(e),t={};for(let[K,Mn]of Object.entries(r)){let on=K.replace(/\./g,"-");t[`--persona-${on}`]=Mn.value}t["--persona-primary"]=(x=t["--persona-semantic-colors-primary"])!=null?x:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(b=t["--persona-semantic-colors-secondary"])!=null?b:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(S=t["--persona-semantic-colors-accent"])!=null?S:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(v=t["--persona-semantic-colors-surface"])!=null?v:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(T=t["--persona-semantic-colors-background"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F: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"]=(P=t["--persona-semantic-colors-text-muted"])!=null?P: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"]=(R=t["--persona-semantic-colors-border"])!=null?R:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(U=t["--persona-semantic-colors-divider"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ve=t["--persona-components-voice-recording-indicator"])!=null?ve:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(le=t["--persona-components-voice-recording-background"])!=null?le:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(q=t["--persona-components-voice-processing-icon"])!=null?q:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ee=t["--persona-components-voice-speaking-icon"])!=null?ee:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ce=t["--persona-components-approval-requested-background"])!=null?Ce:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(we=t["--persona-components-approval-requested-border"])!=null?we:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ye=t["--persona-components-approval-requested-text"])!=null?ye:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(ce=t["--persona-components-approval-approve-background"])!=null?ce:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Q=t["--persona-components-approval-deny-background"])!=null?Q:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(J=t["--persona-components-attachment-image-background"])!=null?J:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(V=t["--persona-components-attachment-image-border"])!=null?V:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(ne=t["--persona-semantic-typography-fontFamily"])!=null?ne:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(fe=t["--persona-semantic-typography-fontSize"])!=null?fe:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(wt=t["--persona-semantic-typography-fontWeight"])!=null?wt:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(ut=t["--persona-semantic-typography-lineHeight"])!=null?ut: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"]=(gt=t["--persona-palette-radius-sm"])!=null?gt:"0.125rem",t["--persona-radius-md"]=(Tt=t["--persona-palette-radius-md"])!=null?Tt:"0.375rem",t["--persona-radius-lg"]=(se=t["--persona-palette-radius-lg"])!=null?se:"0.5rem",t["--persona-radius-xl"]=(re=t["--persona-palette-radius-xl"])!=null?re:"0.75rem",t["--persona-launcher-radius"]=(z=(Ue=t["--persona-components-launcher-borderRadius"])!=null?Ue:t["--persona-palette-radius-full"])!=null?z:"9999px",t["--persona-button-radius"]=(de=(te=t["--persona-components-button-primary-borderRadius"])!=null?te:t["--persona-palette-radius-full"])!=null?de:"9999px",t["--persona-panel-radius"]=(G=(Qe=t["--persona-components-panel-borderRadius"])!=null?Qe:t["--persona-radius-xl"])!=null?G:"0.75rem",t["--persona-panel-border"]=(Y=t["--persona-components-panel-border"])!=null?Y:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(Ne=(tt=t["--persona-components-panel-shadow"])!=null?tt:t["--persona-palette-shadows-xl"])!=null?Ne:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Mt=(je=t["--persona-components-input-borderRadius"])!=null?je:t["--persona-radius-lg"])!=null?Mt:"0.5rem",t["--persona-message-user-radius"]=(ue=(qt=t["--persona-components-message-user-borderRadius"])!=null?qt:t["--persona-radius-lg"])!=null?ue:"0.5rem",t["--persona-message-assistant-radius"]=(ke=(Ye=t["--persona-components-message-assistant-borderRadius"])!=null?Ye:t["--persona-radius-lg"])!=null?ke:"0.5rem",t["--persona-header-bg"]=(ot=t["--persona-components-header-background"])!=null?ot:t["--persona-surface"],t["--persona-header-border"]=(Ve=t["--persona-components-header-border"])!=null?Ve:t["--persona-divider"],t["--persona-header-icon-bg"]=(nt=t["--persona-components-header-iconBackground"])!=null?nt:t["--persona-primary"],t["--persona-header-icon-fg"]=(Rt=t["--persona-components-header-iconForeground"])!=null?Rt:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ht=t["--persona-components-header-titleForeground"])!=null?Ht:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(kt=t["--persona-components-header-subtitleForeground"])!=null?kt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(N=t["--persona-components-header-actionIconForeground"])!=null?N:t["--persona-muted"];let n=(X=e.components)==null?void 0:X.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-message-user-bg"]=(_=t["--persona-components-message-user-background"])!=null?_:t["--persona-accent"],t["--persona-message-user-text"]=(be=t["--persona-components-message-user-text"])!=null?be:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(xe=t["--persona-components-message-user-shadow"])!=null?xe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Ae=t["--persona-components-message-assistant-background"])!=null?Ae:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ee=t["--persona-components-message-assistant-text"])!=null?Ee:t["--persona-text"],t["--persona-message-assistant-border"]=(st=t["--persona-components-message-assistant-border"])!=null?st:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Be=t["--persona-components-message-assistant-shadow"])!=null?Be:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(We=t["--persona-components-toolBubble-shadow"])!=null?We:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(ze=t["--persona-components-reasoningBubble-shadow"])!=null?ze:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(pe=t["--persona-components-composer-shadow"])!=null?pe:"none",t["--persona-md-inline-code-bg"]=(Ft=t["--persona-components-markdown-inlineCode-background"])!=null?Ft:t["--persona-container"],t["--persona-md-inline-code-color"]=(xn=t["--persona-components-markdown-inlineCode-foreground"])!=null?xn:t["--persona-text"],t["--persona-md-link-color"]=(Dn=(Un=t["--persona-components-markdown-link-foreground"])!=null?Un:t["--persona-accent"])!=null?Dn:"#3b82f6";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let d=t["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(t["--persona-md-prose-font-family"]=d);let c=e.components,u=c==null?void 0:c.iconButton;u&&(u.background&&(t["--persona-icon-btn-bg"]=u.background),u.border&&(t["--persona-icon-btn-border"]=u.border),u.color&&(t["--persona-icon-btn-color"]=u.color),u.padding&&(t["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(t["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(t["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(t["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(t["--persona-icon-btn-active-border"]=u.activeBorder));let p=c==null?void 0:c.labelButton;p&&(p.background&&(t["--persona-label-btn-bg"]=p.background),p.border&&(t["--persona-label-btn-border"]=p.border),p.color&&(t["--persona-label-btn-color"]=p.color),p.padding&&(t["--persona-label-btn-padding"]=p.padding),p.borderRadius&&(t["--persona-label-btn-radius"]=p.borderRadius),p.hoverBackground&&(t["--persona-label-btn-hover-bg"]=p.hoverBackground),p.fontSize&&(t["--persona-label-btn-font-size"]=p.fontSize),p.gap&&(t["--persona-label-btn-gap"]=p.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let K=m.toolbar;K.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=K.iconHoverColor),K.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=K.iconHoverBackground),K.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=K.iconPadding),K.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=K.iconBorderRadius),K.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=K.iconBorder),K.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=K.toggleGroupGap),K.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=K.toggleBorderRadius),K.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=K.copyBackground),K.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=K.copyBorder),K.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=K.copyColor),K.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=K.copyBorderRadius),K.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=K.copyPadding),K.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=K.copyMenuBackground,t["--persona-dropdown-bg"]=(ar=t["--persona-dropdown-bg"])!=null?ar:K.copyMenuBackground),K.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=K.copyMenuBorder,t["--persona-dropdown-border"]=(Nn=t["--persona-dropdown-border"])!=null?Nn:K.copyMenuBorder),K.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=K.copyMenuShadow,t["--persona-dropdown-shadow"]=(Tn=t["--persona-dropdown-shadow"])!=null?Tn:K.copyMenuShadow),K.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=K.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Xe=t["--persona-dropdown-radius"])!=null?Xe:K.copyMenuBorderRadius),K.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=K.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(tn=t["--persona-dropdown-item-hover-bg"])!=null?tn:K.copyMenuItemHoverBackground),K.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=K.iconBackground),K.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=K.toolbarBorder)}if(m!=null&&m.tab){let K=m.tab;K.background&&(t["--persona-artifact-tab-bg"]=K.background),K.activeBackground&&(t["--persona-artifact-tab-active-bg"]=K.activeBackground),K.activeBorder&&(t["--persona-artifact-tab-active-border"]=K.activeBorder),K.borderRadius&&(t["--persona-artifact-tab-radius"]=K.borderRadius),K.textColor&&(t["--persona-artifact-tab-color"]=K.textColor),K.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=K.hoverBackground),K.listBackground&&(t["--persona-artifact-tab-list-bg"]=K.listBackground),K.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=K.listBorderColor),K.listPadding&&(t["--persona-artifact-tab-list-padding"]=K.listPadding)}if(m!=null&&m.pane){let K=m.pane;if(K.toolbarBackground){let Mn=(un=Qr(e,K.toolbarBackground))!=null?un:K.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Mn}}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 vl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function to(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];vl(o)&&vl(s)?t[n]=to(o,s):t[n]=s}return t}var ld={colors:{primary:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Cl=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Oo=()=>{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"},cd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":Oo()},wl=e=>cd(e),dd=e=>eo(e),pd=e=>{var t;let r=eo(void 0,{validate:!1});return eo({...e,palette:{...r.palette,colors:{...ld.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Fo=e=>{let r=wl(e),t=Cl(e==null?void 0:e.theme),n=Cl(e==null?void 0:e.darkTheme);return r==="dark"?pd(to(t!=null?t:{},n!=null?n:{})):dd(t)},ud=e=>gs(e),or=(e,r)=>{var o;let t=Fo(r),n=ud(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)},ms=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e(Oo())});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(Oo());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())}};import{Idiomorph as gd}from"idiomorph";var Sl=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;gd.morph(e,r.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(s,o){if(s instanceof HTMLElement&&n&&(s.classList.contains("persona-animate-typing")||s.hasAttribute("data-preserve-animation")))return!1}}})};function Al(e,r){var t,n,s,o,a,i,d,c,u,p,f,m,x,b,S,v,T,F;return[e.id,e.role,(n=(t=e.content)==null?void 0:t.length)!=null?n:0,(o=(s=e.content)==null?void 0:s.slice(-32))!=null?o:"",e.streaming?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(p=e.approval)==null?void 0:p.status)!=null?f:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(v=(S=(b=e.reasoning)==null?void 0:b.chunks)==null?void 0:S.length)!=null?v:0,(F=(T=e.contentParts)==null?void 0:T.length)!=null?F:0,r].join("\0")}function El(){return new Map}function Tl(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Ml(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function kl(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Vt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var $o={side:"right",width:"420px",animate:!0,reveal:"resize"},zt=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},hn=e=>{var t,n,s,o,a;let r=(t=e==null?void 0:e.launcher)==null?void 0:t.dock;return{side:(n=r==null?void 0:r.side)!=null?n:$o.side,width:(s=r==null?void 0:r.width)!=null?s:$o.width,animate:(o=r==null?void 0:r.animate)!=null?o:$o.animate,reveal:(a=r==null?void 0:r.reveal)!=null?a:$o.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 no=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-flex-col persona-items-start persona-text-left">
@@ -12,12 +12,12 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
12
12
  <span class="persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,t.addEventListener("click",n);let r=o=>{var q,M,N,w,F,re,Y,ae,z,ge,Ie,Xe;let a=(q=o.launcher)!=null?q:{},i=Jt(o),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(M=a.title)!=null?M:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(N=a.subtitle)!=null?N:"Get answers fast");let g=t.querySelector(".persona-flex-col");g&&(a.textHidden||i?g.style.display="none":g.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ye=(w=a.agentIconSize)!=null?w:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",a.agentIconName){let ee=parseFloat(ye)||24,te=me(a.agentIconName,ee*.6,"var(--persona-text-inverse, #ffffff)",2);te?(p.appendChild(te),p.style.display=""):(p.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(re=a.agentIconText)!=null?re:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ye=(Y=a.agentIconSize)!=null?Y:"40px";f.style.height=ye,f.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(ae=a.callToActionIconSize)!=null?ae:"32px";m.style.height=ye,m.style.width=ye,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let ee=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ee=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let te=parseFloat(ye)||24,D=Math.max(te-ee,8),U=me(a.callToActionIconName,D,"currentColor",2);U?m.appendChild(U):m.textContent=(z=a.callToActionIconText)!=null?z:"\u2197"}else m.textContent=(ge=a.callToActionIconText)!=null?ge:"\u2197"}let C=a.position&&pn[a.position]?pn[a.position]:pn["bottom-right"],v="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?E:`${v} ${C}`;let x="1px solid var(--persona-border, #e5e7eb)",k="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";if(t.style.border=(Ie=a.border)!=null?Ie:x,t.style.boxShadow=(Xe=a.shadow)!=null?Xe:k,i){let ye=Kr(o);t.style.width=`calc(${ye.collapsedWidth} - 16px)`,t.style.minWidth="40px",t.style.maxWidth=`calc(${ye.collapsedWidth} - 16px)`,t.style.justifyContent="center",t.style.padding="12px 0"}else t.style.width="",t.style.minWidth="",t.style.maxWidth="",t.style.justifyContent="",t.style.padding=""},s=()=>{t.removeEventListener("click",n),t.remove()};return e&&r(e),{element:t,update:r,destroy:s}};var Fn=e=>{var ae,z,ge,Ie,Xe,ye,ee,te,D,U,oe,he,ht,at,ut,Wt,de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je;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.borderBottomWidth="1px",r.style.borderBottomStyle="solid",r.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))";let s=(ae=n==null?void 0:n.launcher)!=null?ae:{},o=(z=s.headerIconSize)!=null?z:"48px",a=(ge=s.closeButtonSize)!=null?ge:"32px",i=(Ie=s.closeButtonPlacement)!=null?Ie:"inline",d=(Xe=s.headerIconHidden)!=null?Xe:!1,c=s.headerIconName,g=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-bg-persona-primary persona-text-white persona-text-xl");if(g.style.height=o,g.style.width=o,!d)if(c){let Me=parseFloat(o)||24,nt=me(c,Me*.6,"var(--persona-text-inverse, #ffffff)",1);nt?g.replaceChildren(nt):g.textContent=(ee=(ye=n==null?void 0:n.launcher)==null?void 0:ye.agentIconText)!=null?ee:"\u{1F4AC}"}else if((te=n==null?void 0:n.launcher)!=null&&te.iconUrl){let Me=h("img");Me.src=n.launcher.iconUrl,Me.alt="",Me.className="persona-rounded-xl persona-object-cover",Me.style.height=o,Me.style.width=o,g.replaceChildren(Me)}else g.textContent=(U=(D=n==null?void 0:n.launcher)==null?void 0:D.agentIconText)!=null?U:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col"),f=h("span","persona-text-base persona-font-semibold");f.textContent=(he=(oe=n==null?void 0:n.launcher)==null?void 0:oe.title)!=null?he:"Chat Assistant";let m=h("span","persona-text-xs persona-text-persona-muted");m.textContent=(at=(ht=n==null?void 0:n.launcher)==null?void 0:ht.subtitle)!=null?at:"Here to help you get answers fast",p.append(f,m),d?r.append(p):r.append(g,p);let C=(ut=s.clearChat)!=null?ut:{},v=(Wt=C.enabled)!=null?Wt:!0,E=(de=C.placement)!=null?de:"inline",x=null,k=null;if(v){let Me=(ie=C.size)!=null?ie:"32px",nt=(qe=C.iconName)!=null?qe:"refresh-cw",je=(j=C.iconColor)!=null?j:"",Ze=(G=C.backgroundColor)!=null?G:"",Rt=(be=C.borderWidth)!=null?be:"",Ht=(ze=C.borderColor)!=null?ze:"",Mt=(X=C.borderRadius)!=null?X:"",B=(K=C.paddingX)!=null?K:"",Z=(tt=C.paddingY)!=null?tt:"",J=(We=C.tooltipText)!=null?We:"Clear chat",_=(Ve=C.showTooltip)!=null?Ve:!0;k=h("div",E==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),E==="top-right"&&(k.style.right="48px"),x=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none"),x.style.height=Me,x.style.width=Me,x.type="button",x.setAttribute("aria-label",J);let xe=me(nt,"20px",je||"",1);if(xe&&x.appendChild(xe),je&&(x.style.color=je,x.classList.remove("persona-text-persona-muted")),Ze&&(x.style.backgroundColor=Ze,x.classList.remove("hover:persona-bg-gray-100")),Rt||Ht){let Le=Rt||"0px",He=Ht||"transparent";x.style.border=`${Le} solid ${He}`,x.classList.remove("persona-border-none")}if(Mt&&(x.style.borderRadius=Mt,x.classList.remove("persona-rounded-full")),B?(x.style.paddingLeft=B,x.style.paddingRight=B):(x.style.paddingLeft="",x.style.paddingRight=""),Z?(x.style.paddingTop=Z,x.style.paddingBottom=Z):(x.style.paddingTop="",x.style.paddingBottom=""),k.appendChild(x),_&&J&&x&&k){let Le=null,He=()=>{if(Le||!x)return;let ve=x.ownerDocument,Ce=ve.body;if(!Ce)return;Le=vn(ve,"div","persona-clear-chat-tooltip"),Le.textContent=J;let Be=vn(ve,"div");Be.className="persona-clear-chat-tooltip-arrow",Le.appendChild(Be);let ue=x.getBoundingClientRect();Le.style.position="fixed",Le.style.left=`${ue.left+ue.width/2}px`,Le.style.top=`${ue.top-8}px`,Le.style.transform="translate(-50%, -100%)",Ce.appendChild(Le)},pt=()=>{Le&&Le.parentNode&&(Le.parentNode.removeChild(Le),Le=null)};k.addEventListener("mouseenter",He),k.addEventListener("mouseleave",pt),x.addEventListener("focus",He),x.addEventListener("blur",pt),k._cleanupTooltip=()=>{pt(),k&&(k.removeEventListener("mouseenter",He),k.removeEventListener("mouseleave",pt)),x&&(x.removeEventListener("focus",He),x.removeEventListener("blur",pt))}}E==="inline"&&r.appendChild(k)}let q=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&E==="inline"?"":"persona-ml-auto"),M=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");M.style.height=a,M.style.width=a,M.type="button";let N=(Tt=s.closeButtonTooltipText)!=null?Tt:"Close chat",w=(_t=s.closeButtonShowTooltip)!=null?_t:!0;M.setAttribute("aria-label",N),M.style.display=t?"":"none";let F=(ce=s.closeButtonIconName)!=null?ce:"x",re=(Je=s.closeButtonIconText)!=null?Je:"\xD7",Y=me(F,"20px",s.closeButtonColor||"",1);if(Y?M.appendChild(Y):M.textContent=re,s.closeButtonColor?(M.style.color=s.closeButtonColor,M.classList.remove("persona-text-persona-muted")):(M.style.color="",M.classList.add("persona-text-persona-muted")),s.closeButtonBackgroundColor?(M.style.backgroundColor=s.closeButtonBackgroundColor,M.classList.remove("hover:persona-bg-gray-100")):(M.style.backgroundColor="",M.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let Me=s.closeButtonBorderWidth||"0px",nt=s.closeButtonBorderColor||"transparent";M.style.border=`${Me} solid ${nt}`,M.classList.remove("persona-border-none")}else M.style.border="",M.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(M.style.borderRadius=s.closeButtonBorderRadius,M.classList.remove("persona-rounded-full")):(M.style.borderRadius="",M.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(M.style.paddingLeft=s.closeButtonPaddingX,M.style.paddingRight=s.closeButtonPaddingX):(M.style.paddingLeft="",M.style.paddingRight=""),s.closeButtonPaddingY?(M.style.paddingTop=s.closeButtonPaddingY,M.style.paddingBottom=s.closeButtonPaddingY):(M.style.paddingTop="",M.style.paddingBottom=""),q.appendChild(M),w&&N){let Me=null,nt=()=>{if(Me)return;let Ze=M.ownerDocument,Rt=Ze.body;if(!Rt)return;Me=vn(Ze,"div","persona-clear-chat-tooltip"),Me.textContent=N;let Ht=vn(Ze,"div");Ht.className="persona-clear-chat-tooltip-arrow",Me.appendChild(Ht);let Mt=M.getBoundingClientRect();Me.style.position="fixed",Me.style.left=`${Mt.left+Mt.width/2}px`,Me.style.top=`${Mt.top-8}px`,Me.style.transform="translate(-50%, -100%)",Rt.appendChild(Me)},je=()=>{Me&&Me.parentNode&&(Me.parentNode.removeChild(Me),Me=null)};q.addEventListener("mouseenter",nt),q.addEventListener("mouseleave",je),M.addEventListener("focus",nt),M.addEventListener("blur",je),q._cleanupTooltip=()=>{je(),q.removeEventListener("mouseenter",nt),q.removeEventListener("mouseleave",je),M.removeEventListener("focus",nt),M.removeEventListener("blur",je)}}return i!=="top-right"&&r.appendChild(q),{header:r,iconHolder:g,headerTitle:f,headerSubtitle:m,closeButton:M,closeButtonWrapper:q,clearChatButton:x,clearChatButtonWrapper:k}},gr=(e,n,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=r.closeButtonPlacement)!=null?i:"inline",o=(c=(d=r.clearChat)==null?void 0:d.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))};var Sl=e=>{var r;let n=Fn({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 dd(e,n,t){var r,s;if(n!=null&&n.length)for(let o of n){let a=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(a.type="button",a.setAttribute("aria-label",(s=(r=o.ariaLabel)!=null?r:o.label)!=null?s:o.id),o.icon){let i=me(o.icon,14,"currentColor",2);i&&a.appendChild(i)}else o.label&&(a.textContent=o.label);a.addEventListener("click",()=>t==null?void 0:t(o.id)),e.appendChild(a)}}var Al=e=>{var x,k,q,M,N;let{config:n,showClose:t=!0,onClose:r,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(x=n==null?void 0:n.launcher)!=null?x:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-bg-persona-surface persona-px-6 persona-py-4 persona-border-b-persona-divider");i.setAttribute("data-persona-theme-zone","header");let d=h("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),c=h("span","persona-text-base persona-font-semibold persona-truncate");if(c.textContent=(k=a.title)!=null?k:"Chat Assistant",d.appendChild(c),dd(d,s==null?void 0:s.trailingActions,(q=s==null?void 0:s.onAction)!=null?q:o),s!=null&&s.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let w=s.onTitleClick;d.addEventListener("click",F=>{F.target.closest("button")||w()}),d.addEventListener("keydown",F=>{(F.key==="Enter"||F.key===" ")&&(F.preventDefault(),w())})}i.appendChild(d);let g=(M=a.closeButtonSize)!=null?M:"32px",p=h("div",""),f=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=g,f.style.width=g,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=t?"":"none";let m=(N=a.closeButtonIconName)!=null?N:"x",C=me(m,"20px",a.closeButtonColor||"",2);C?f.appendChild(C):f.textContent="\xD7",r&&f.addEventListener("click",r),p.appendChild(f),i.appendChild(p);let v=h("div");v.style.display="none";let E=h("span");return E.style.display="none",{header:i,iconHolder:v,headerTitle:c,headerSubtitle:E,closeButton:f,closeButtonWrapper:p,clearChatButton:null,clearChatButtonWrapper:null}},ps={default:Sl,minimal:Al},El=e=>{var n;return(n=ps[e])!=null?n:ps.default},Gr=(e,n,t)=>{var a,i,d;if(n!=null&&n.render){let c=n.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:n.trailingActions,onAction:n.onAction}),g=h("div");g.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let C=h("div");return C.style.display="none",{header:c,iconHolder:g,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:C,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=n==null?void 0:n.layout)!=null?a:"default",o=El(r)({config:e,showClose:(d=(i=n==null?void 0:n.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:n,onHeaderAction:n==null?void 0:n.onAction});return n&&(n.showIcon===!1&&(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 pd=e=>{switch(e){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}},Xr=e=>{var de,ie,qe,j,G,be,ze,X,K,tt,We,Ve,Tt,_t,ce,Je,Me,nt,je,Ze,Rt,Ht,Mt,B,Z,J,_,xe,Le,He,pt;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=(ie=(de=n==null?void 0:n.copy)==null?void 0:de.inputPlaceholder)!=null?ie:"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;let a=(j=(qe=n==null?void 0:n.theme)==null?void 0:qe.inputFontFamily)!=null?j:"sans-serif",i=(be=(G=n==null?void 0:n.theme)==null?void 0:G.inputFontWeight)!=null?be:"400";o.style.fontFamily=pd(a),o.style.fontWeight=i;let g=3*20;o.style.maxHeight=`${g}px`,o.style.overflowY="auto";let p=()=>{o.style.height="auto";let ve=Math.min(o.scrollHeight,g);o.style.height=`${ve}px`};o.addEventListener("input",p),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 f=(ze=n==null?void 0:n.sendButton)!=null?ze:{},m=(X=f.useIcon)!=null?X:!1,C=(K=f.iconText)!=null?K:"\u2191",v=f.iconName,E=(tt=f.tooltipText)!=null?tt:"Send message",x=(We=f.showTooltip)!=null?We:!1,k=(Ve=f.size)!=null?Ve:"40px",q=f.backgroundColor,M=f.textColor,N=h("div","persona-send-button-wrapper"),w=h("button",m?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(w.type="submit",w.setAttribute("data-persona-composer-submit",""),m){if(w.style.width=k,w.style.height=k,w.style.minWidth=k,w.style.minHeight=k,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",v){let ve=parseFloat(k)||24,Ce=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",Be=me(v,ve,Ce,2);Be?(w.appendChild(Be),w.style.color=Ce):(w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white"))}else w.textContent=C,M?w.style.color=M:w.classList.add("persona-text-white");q?w.style.backgroundColor=q:w.classList.add("persona-bg-persona-primary")}else w.textContent=(_t=(Tt=n==null?void 0:n.copy)==null?void 0:Tt.sendButtonLabel)!=null?_t:"Send",M?w.style.color=M:w.classList.add("persona-text-white");if(f.borderWidth&&(w.style.borderWidth=f.borderWidth,w.style.borderStyle="solid"),f.borderColor&&(w.style.borderColor=f.borderColor),f.paddingX?(w.style.paddingLeft=f.paddingX,w.style.paddingRight=f.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),f.paddingY?(w.style.paddingTop=f.paddingY,w.style.paddingBottom=f.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),x&&E){let ve=h("div","persona-send-button-tooltip");ve.textContent=E,N.appendChild(ve)}N.appendChild(w);let F=(ce=n==null?void 0:n.voiceRecognition)!=null?ce:{},re=F.enabled===!0,Y=null,ae=null,z=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ge=((Je=F.provider)==null?void 0:Je.type)==="runtype";if(re&&(z||ge)){ae=h("div","persona-send-button-wrapper"),Y=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),Y.type="button",Y.setAttribute("data-persona-composer-mic",""),Y.setAttribute("aria-label","Start voice recognition");let ve=(Me=F.iconName)!=null?Me:"mic",Ce=(nt=F.iconSize)!=null?nt:k,Be=parseFloat(Ce)||24,ue=(je=F.backgroundColor)!=null?je:q,bt=(Ze=F.iconColor)!=null?Ze:M;Y.style.width=Ce,Y.style.height=Ce,Y.style.minWidth=Ce,Y.style.minHeight=Ce,Y.style.fontSize="18px",Y.style.lineHeight="1";let Zt=bt||"currentColor",un=me(ve,Be,Zt,1.5);un?(Y.appendChild(un),Y.style.color=Zt):(Y.textContent="\u{1F3A4}",Y.style.color=Zt),ue?Y.style.backgroundColor=ue:Y.classList.add("persona-bg-persona-primary"),bt?Y.style.color=bt:!bt&&!M&&Y.classList.add("persona-text-white"),F.borderWidth&&(Y.style.borderWidth=F.borderWidth,Y.style.borderStyle="solid"),F.borderColor&&(Y.style.borderColor=F.borderColor),F.paddingX&&(Y.style.paddingLeft=F.paddingX,Y.style.paddingRight=F.paddingX),F.paddingY&&(Y.style.paddingTop=F.paddingY,Y.style.paddingBottom=F.paddingY),ae.appendChild(Y);let gn=(Rt=F.tooltipText)!=null?Rt:"Start voice recognition";if(((Ht=F.showTooltip)!=null?Ht:!1)&&gn){let Pn=h("div","persona-send-button-tooltip");Pn.textContent=gn,ae.appendChild(Pn)}}let Xe=(Mt=n==null?void 0:n.attachments)!=null?Mt:{},ye=Xe.enabled===!0,ee=null,te=null,D=null,U=null;if(ye){U=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),U.style.display="none",D=h("input"),D.type="file",D.accept=((B=Xe.allowedTypes)!=null?B:kn).join(","),D.multiple=((Z=Xe.maxFiles)!=null?Z:4)>1,D.style.display="none",D.setAttribute("aria-label","Attach files"),te=h("div","persona-send-button-wrapper"),ee=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),ee.type="button",ee.setAttribute("aria-label",(J=Xe.buttonTooltipText)!=null?J:"Attach file");let ve=(_=Xe.buttonIconName)!=null?_:"paperclip",Ce=k,Be=parseFloat(Ce)||40,ue=Math.round(Be*.6);ee.style.width=Ce,ee.style.height=Ce,ee.style.minWidth=Ce,ee.style.minHeight=Ce,ee.style.fontSize="18px",ee.style.lineHeight="1",ee.style.backgroundColor="transparent",ee.style.color="var(--persona-primary, #111827)",ee.style.border="none",ee.style.borderRadius="6px",ee.style.transition="background-color 0.15s ease",ee.addEventListener("mouseenter",()=>{ee.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),ee.addEventListener("mouseleave",()=>{ee.style.backgroundColor="transparent"});let bt=me(ve,ue,"currentColor",1.5);bt?ee.appendChild(bt):ee.textContent="\u{1F4CE}",ee.addEventListener("click",gn=>{gn.preventDefault(),D==null||D.click()}),te.appendChild(ee);let Zt=(xe=Xe.buttonTooltipText)!=null?xe:"Attach file",un=h("div","persona-send-button-tooltip");un.textContent=Zt,te.appendChild(un)}s.addEventListener("click",ve=>{ve.target!==w&&ve.target!==N&&ve.target!==Y&&ve.target!==ae&&ve.target!==ee&&ve.target!==te&&o.focus()}),U&&(U.style.gap="8px",s.append(U)),D&&s.append(D),s.append(o);let oe=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),he=h("div","persona-flex persona-items-center persona-gap-2");te&&he.append(te);let ht=h("div","persona-flex persona-items-center persona-gap-1");ae&&ht.append(ae),ht.append(N),oe.append(he,ht),s.append(oe);let at=h("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");at.setAttribute("data-persona-composer-status","");let ut=(Le=n==null?void 0:n.statusIndicator)!=null?Le:{},Wt=(He=ut.visible)!=null?He:!0;return at.style.display=Wt?"":"none",at.textContent=(pt=ut.idleText)!=null?pt:"Online",t.append(r,s,at),{footer:t,suggestions:r,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:N,micButton:Y,micButtonWrapper:ae,statusText:at,attachmentButton:ee,attachmentButtonWrapper:te,attachmentInput:D,attachmentPreviewsContainer:U,actionsRow:oe,leftActions:he,rightActions:ht}};var Tl=e=>{var c,g,p,f,m,C,v;let n=(g=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?g:!0;if(Jt(e)){let E=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),x=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return E.appendChild(x),{wrapper:E,panel:x}}if(!n){let E=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),x=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),k=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return E.style.width=k,x.style.width="100%",E.appendChild(x),{wrapper:E,panel:x}}let r=(m=e==null?void 0:e.launcher)!=null?m:{},s=r.position&&pn[r.position]?pn[r.position]:pn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(v=(C=e==null?void 0:e.launcher)==null?void 0:C.width)!=null?v:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},Ml=(e,n=!0)=>{var v,E,x,k,q,M,N,w,F;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=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,o=r?Gr(e,r,{showClose:n}):Fn({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=h("div","persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm"),d=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");d.textContent=(k=(x=e==null?void 0:e.copy)==null?void 0:x.welcomeTitle)!=null?k:"Hello \u{1F44B}";let c=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");c.textContent=(M=(q=e==null?void 0:e.copy)==null?void 0:q.welcomeSubtitle)!=null?M:"Ask anything about your account or products.",i.append(d,c);let g=h("div","persona-flex persona-flex-col persona-gap-3"),p=(N=e==null?void 0:e.layout)==null?void 0:N.contentMaxWidth;p&&(g.style.maxWidth=p,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((w=e==null?void 0:e.copy)==null?void 0:w.showWelcomeCard)!==!1?a.append(i,g):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(g));let m=Xr({config:e}),C=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;return s?gr(t,o,e):(o.header.style.display="none",gr(t,o,e)),t.append(a),C||(m.footer.style.display="none"),t.append(m.footer),{container:t,body:a,messagesWrapper:g,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:d,introSubtitle:c,closeButton:o.closeButton,closeButtonWrapper:o.closeButtonWrapper,clearChatButton:o.clearChatButton,clearChatButtonWrapper:o.clearChatButtonWrapper,iconHolder:o.iconHolder,headerTitle:o.headerTitle,headerSubtitle:o.headerSubtitle,header:o.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions}};var ud=e=>{let n=e.toLowerCase();return n.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||n.startsWith("data:image/")||!e.includes(":"))},gd=320,md=320,fd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(n=>n.type==="image"&&typeof n.image=="string"&&n.image.trim().length>0),hd=(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,d)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${gd}px`,c.style.maxHeight=`${md}px`,c.style.height="auto",c.style.objectFit="contain",c.style.borderRadius="10px",c.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",c.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let g=!1;s+=1,c.addEventListener("error",()=>{g||(g=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{g=!0}),ud(i.image)?(c.src=i.image,r.appendChild(c)):(g=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):r}catch{return t==null||t(),null}},mr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let r=document.createElement("div");r.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="500ms";let 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},Ll=(e,n,t)=>{let r={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:mr};if(n){let s=n(r);if(s!==null)return s}return mr()},yd=(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},kl=(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},bd=(e,n="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(n){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Pl=(e,n,t)=>{var m,C,v,E,x,k;let r=(m=n.showCopy)!=null?m:!0,s=(C=n.showUpvote)!=null?C:!0,o=(v=n.showDownvote)!=null?v:!0;if(!r&&!s&&!o){let q=h("div");return q.style.display="none",q.id=`actions-${e.id}`,q.setAttribute("data-actions-for",e.id),q}let a=(E=n.visibility)!=null?E:"hover",i=(x=n.align)!=null?x:"right",d=(k=n.layout)!=null?k:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],g={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${g} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(q,M,N)=>{let w=document.createElement("button");w.className="persona-message-action-btn",w.setAttribute("aria-label",M),w.setAttribute("title",M),w.setAttribute("data-action",N);let F=me(q,14,"currentColor",2);return F&&w.appendChild(F),w};return r&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},Zr=(e,n,t,r,s,o)=>{var ae,z,ge,Ie,Xe,ye,ee;let a=t!=null?t:{},i=(ae=a.layout)!=null?ae:"bubble",d=a.avatar,c=a.timestamp,g=(z=d==null?void 0:d.show)!=null?z:!1,p=(ge=c==null?void 0:c.show)!=null?ge:!1,f=(Ie=d==null?void 0:d.position)!=null?Ie:"left",m=(Xe=c==null?void 0:c.position)!=null?Xe:"below",C=bd(e.role,i),v=h("div",C.join(" "));v.id=`bubble-${e.id}`,v.setAttribute("data-message-id",e.id),v.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(v.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",v.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(v.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",v.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=fd(e),x=(ee=(ye=e.content)==null?void 0:ye.trim())!=null?ee:"",q=E.length>0&&x===Mo,M=document.createElement("div");M.classList.add("persona-message-content");let N=n({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),w=null;if(q?(w=document.createElement("div"),w.innerHTML=N,w.style.display="none",M.appendChild(w)):M.innerHTML=N,p&&m==="inline"&&e.createdAt){let te=kl(e,c);te.classList.add("persona-ml-2","persona-inline"),M.appendChild(te)}if(E.length>0){let te=hd(E,!q&&!!x,()=>{q&&w&&(w.style.display="")});te?v.appendChild(te):q&&w&&(w.style.display="")}if(v.appendChild(M),p&&m==="below"&&e.createdAt){let te=kl(e,c);te.classList.add("persona-mt-1"),v.appendChild(te)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let te=Ll("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);te&&v.appendChild(te)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let te=Pl(e,r,s);v.appendChild(te)}if(!g||e.role==="system")return v;let re=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),Y=yd(d,e.role);return f==="right"||f==="left"&&e.role==="user"?re.append(v,Y):re.append(Y,v),v.classList.remove("persona-max-w-[85%]"),v.classList.add("persona-max-w-[calc(85%-2.5rem)]"),re},xd=(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}):Zr(e,n,t,r,s,o)};var fr=new Set,Il=(e,n)=>{let t=fr.has(e),r=n.querySelector('button[data-expand-header="true"]'),s=n.querySelector(".persona-border-t");if(!r||!s)return;r.setAttribute("aria-expanded",t?"true":"false");let o=r.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},us=e=>{let n=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!n)return t;let r=fr.has(e.id),s=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");s.type="button",s.setAttribute("aria-expanded",r?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=tl(n),o.appendChild(i),n.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),g=me(r?"chevron-up":"chevron-down",16,"currentColor",2);g?d.appendChild(g):d.textContent=r?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=r?"":"none";let m=n.chunks.join(""),C=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return C.textContent=m||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(C),(()=>{s.setAttribute("aria-expanded",r?"true":"false"),d.innerHTML="";let x=me(r?"chevron-up":"chevron-down",16,"currentColor",2);x?d.appendChild(x):d.textContent=r?"Hide":"Show",f.style.display=r?"":"none"})(),t.append(s,f),t};var hr=new Set,Wl=(e,n,t)=>{var c;let r=hr.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=n.querySelector('button[data-expand-header="true"]'),a=n.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",r?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let g=s.toggleTextColor||s.headerTextColor||"currentColor",p=me(r?"chevron-up":"chevron-down",16,g,2);p?d.appendChild(p):d.textContent=r?"Hide":"Show"}a.style.display=r?"":"none"},gs=(e,n)=>{var v;let t=e.toolCall,r=(v=n==null?void 0:n.toolCall)!=null?v:{},s=h("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(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=hr.has(e.id),a=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(a.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(a.style.paddingLeft=r.headerPaddingX,a.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(a.style.paddingTop=r.headerPaddingY,a.style.paddingBottom=r.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(d.style.color=r.headerTextColor),d.textContent=nl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),g=r.toggleTextColor||r.headerTextColor||"currentColor",p=me(o?"chevron-up":"chevron-down",16,g,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",r.contentBackgroundColor&&(m.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(m.style.color=r.contentTextColor),r.contentPaddingX&&(m.style.paddingLeft=r.contentPaddingX,m.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(m.style.paddingTop=r.contentPaddingY,m.style.paddingBottom=r.contentPaddingY),t.name){let E=h("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?E.style.color=r.contentTextColor:r.headerTextColor&&(E.style.color=r.headerTextColor),E.textContent=t.name,m.appendChild(E)}if(t.args!==void 0){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Arguments";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Vr(t.args),E.append(x,k),m.appendChild(E)}if(t.chunks&&t.chunks.length){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Activity";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=t.chunks.join(`
16
- `),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&t.result!==void 0){let E=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(x.style.color=r.labelTextColor),x.textContent="Result";let k=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");k.style.fontSize="0.75rem",k.style.lineHeight="1rem",r.codeBlockBackgroundColor&&(k.style.backgroundColor=r.codeBlockBackgroundColor),r.codeBlockBorderColor&&(k.style.borderColor=r.codeBlockBorderColor),r.codeBlockTextColor&&(k.style.color=r.codeBlockTextColor),k.textContent=Vr(t.result),E.append(x,k),m.appendChild(E)}if(t.status==="complete"&&typeof t.duration=="number"){let E=h("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(E.style.color=r.contentTextColor),E.textContent=`Duration: ${t.duration}ms`,m.appendChild(E)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let E=r.toggleTextColor||r.headerTextColor||"currentColor",x=me(o?"chevron-up":"chevron-down",16,E,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var ms=(e,n)=>{var v,E,x,k,q,M,N,w,F,re,Y,ae;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-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=(v=r==null?void 0:r.backgroundColor)!=null?v:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(E=r==null?void 0:r.borderColor)!=null?E:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(x=r==null?void 0:r.titleColor)!=null?x:"currentColor",g=me(d,20,c,2);g&&i.appendChild(g);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(m.style.color=r.titleColor),m.textContent=(k=r==null?void 0:r.title)!=null?k:"Approval Required",f.appendChild(m),!s){let z=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");z.setAttribute("data-approval-status",t.status),t.status==="approved"?(z.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",z.style.color="var(--persona-palette-colors-success-700, #15803d)",z.textContent="Approved"):t.status==="denied"?(z.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",z.style.color="var(--persona-palette-colors-error-700, #b91c1c)",z.textContent="Denied"):t.status==="timeout"&&(z.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",z.style.color="var(--persona-palette-colors-warning-700, #b45309)",z.textContent="Timeout"),f.appendChild(z)}p.appendChild(f);let C=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(r!=null&&r.descriptionColor&&(C.style.color=r.descriptionColor),C.textContent=t.description,p.appendChild(C),t.parameters){let z=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&&(z.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(z.style.color=r.parameterTextColor),z.style.fontSize="0.75rem",z.style.lineHeight="1rem",z.textContent=Vr(t.parameters),p.appendChild(z)}if(s){let z=h("div","persona-flex persona-gap-2 persona-mt-2");z.setAttribute("data-approval-buttons","true");let ge=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");ge.type="button",ge.style.backgroundColor=(q=r==null?void 0:r.approveButtonColor)!=null?q:"var(--persona-approval-approve-bg, #22c55e)",ge.style.color=(M=r==null?void 0:r.approveButtonTextColor)!=null?M:"#ffffff",ge.setAttribute("data-approval-action","approve");let Ie=me("shield-check",14,(N=r==null?void 0:r.approveButtonTextColor)!=null?N:"#ffffff",2);Ie&&(Ie.style.marginRight="4px",ge.appendChild(Ie));let Xe=document.createTextNode((w=r==null?void 0:r.approveLabel)!=null?w:"Approve");ge.appendChild(Xe);let ye=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");ye.type="button",ye.style.backgroundColor=(F=r==null?void 0:r.denyButtonColor)!=null?F:"transparent",ye.style.color=(re=r==null?void 0:r.denyButtonTextColor)!=null?re:"var(--persona-feedback-error, #dc2626)",ye.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ye.setAttribute("data-approval-action","deny");let ee=me("shield-x",14,(Y=r==null?void 0:r.denyButtonTextColor)!=null?Y:"var(--persona-feedback-error, #dc2626)",2);ee&&(ee.style.marginRight="4px",ye.appendChild(ee));let te=document.createTextNode((ae=r==null?void 0:r.denyLabel)!=null?ae:"Deny");ye.appendChild(te),z.append(ge,ye),p.appendChild(z)}return a.append(i,p),o.appendChild(a),o};var Rl=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(m=>m.role==="user"))return;let g=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};r.forEach(m=>{let C=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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");C.type="button",C.textContent=m,C.disabled=p,i!=null&&i.fontFamily&&(C.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(C.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(C.style.paddingLeft=i.paddingX,C.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(C.style.paddingTop=i.paddingY,C.style.paddingBottom=i.paddingY),C.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),g.appendChild(C),n.push(C)}),e.appendChild(g)}}};var Qr=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 eo=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 yr(e,n){n&&n.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var vd={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Cd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},wd=["flowName","stepName","reasoningText","text","name","tool","toolName"],Sd=100;function Ad(e,n){let t={...vd,...n};if(t[e])return t[e];for(let r of Object.keys(t))if(r.endsWith("_")&&e.startsWith(r))return t[r];return Cd}function Ed(e,n){return`+${((e-n)/1e3).toFixed(3)}s`}function Td(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 Md(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 kd(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 Ld(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 Pd(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]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function fs(e,n,t,r,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");yr(c,(f=r.classNames)==null?void 0:f.eventRow);let g=a.find(m=>m.renderEventStreamRow);if(g!=null&&g.renderEventStreamRow&&i){let m=g.renderEventStreamRow({event:e,index:n,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var ge,Ie;let m=h("div",""),C=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");C.setAttribute("data-event-id",e.id);let v=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=me(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&v.appendChild(E);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),k=(ge=r.timestampFormat)!=null?ge:"relative";x.textContent=k==="relative"?Ed(e.timestamp,t):Td(e.timestamp);let q=null;r.showSequenceNumbers!==!1&&(q=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),q.textContent=String(n+1));let M=Ad(e.type,r.badgeColors),N=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");N.style.backgroundColor=M.bg,N.style.color=M.text,N.style.borderColor=M.text+"50",N.textContent=e.type;let w=(Ie=r.descriptionFields)!=null?Ie:wd,F=Md(e.payload,w),re=null;F&&(re=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),re.textContent=F);let Y=h("div","persona-flex-1 persona-min-w-0"),ae=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"),z=me("clipboard","12px","currentColor",1.5);return z&&ae.appendChild(z),ae.addEventListener("click",async Xe=>{Xe.stopPropagation(),await kd(Ld(e)),ae.innerHTML="";let ye=me("check","12px","currentColor",1.5);ye&&ae.appendChild(ye),setTimeout(()=>{ae.innerHTML="";let ee=me("clipboard","12px","currentColor",1.5);ee&&ae.appendChild(ee)},1500)}),C.appendChild(v),C.appendChild(x),q&&C.appendChild(q),C.appendChild(N),re&&C.appendChild(re),C.appendChild(Y),C.appendChild(ae),m.appendChild(C),d&&m.appendChild(Pd(e,a,i)),m}}function Hl(e){var c,g;let{buffer:n,getFullHistory:t,onClose:r,config:s,plugins:o=[]}=e,a=(g=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?g:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:n.getAll(),defaultRenderer:()=>d().element,onClose:r});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");yr(f,p==null?void 0:p.panel);let m=[],C="",v="",E=null,x=[],k={},q=0,M=!1,N=0,w=0,F=!1,re=null,Y=!1,ae=0,z=new Set,ge=new Map,Ie="",Xe="",ye=null,ee,te,D,U,oe;function he(){let Z=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),J=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");yr(J,p==null?void 0:p.headerBar);let _=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_.textContent="Events",ee=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"),ee.textContent="0";let xe=h("div","persona-flex-1");te=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 Le=h("option","");Le.value="",Le.textContent="All events",te.appendChild(Le),D=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"),D.type="button",D.title="Copy All";let pt=me("clipboard-copy","12px","currentColor",1.5);pt&&D.appendChild(pt);let ve=h("span","persona-text-xs");ve.textContent="Copy All",D.appendChild(ve),J.appendChild(_),J.appendChild(ee),J.appendChild(xe),J.appendChild(te),J.appendChild(D);let Ce=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");yr(Ce,p==null?void 0:p.searchBar);let Be=me("search","14px","var(--persona-muted, #9ca3af)",1.5),ue=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");Be&&ue.appendChild(Be),U=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"),yr(U,p==null?void 0:p.searchInput),U.type="text",U.placeholder="Search event payloads...",oe=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"),oe.type="button",oe.style.display="none";let bt=me("x","12px","currentColor",2);return bt&&oe.appendChild(bt),Ce.appendChild(ue),Ce.appendChild(U),Ce.appendChild(oe),Z.appendChild(J),Z.appendChild(Ce),Z}let ht,at=o.find(Z=>Z.renderEventStreamToolbar);if(at!=null&&at.renderEventStreamToolbar&&s){let Z=at.renderEventStreamToolbar({config:s,defaultRenderer:()=>he(),eventCount:n.getSize(),filteredCount:0,onFilterChange:J=>{C=J,K(),Ve()},onSearchChange:J=>{v=J,K(),Ve()}});ht=Z!=null?Z:he()}else ht=he();let ut=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");ut.style.display="none";let Wt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),de=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");de.style.height="100%";let ie=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");yr(ie,p==null?void 0:p.scrollIndicator),ie.style.display="none";let qe=me("arrow-down","12px","currentColor",2);qe&&ie.appendChild(qe);let j=h("span","");ie.appendChild(j);let G=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");G.style.display="none",Wt.appendChild(de),Wt.appendChild(G),Wt.appendChild(ie),f.setAttribute("tabindex","0"),f.appendChild(ht),f.appendChild(ut),f.appendChild(Wt);function be(){let Z=n.getAll(),J={};for(let ve of Z)J[ve.type]=(J[ve.type]||0)+1;let _=Object.keys(J).sort(),xe=_.length!==x.length||!_.every((ve,Ce)=>ve===x[Ce]),Le=!xe&&_.some(ve=>J[ve]!==k[ve]),He=Z.length!==Object.values(k).reduce((ve,Ce)=>ve+Ce,0);if(!xe&&!Le&&!He||(x=_,k=J,!te))return;let pt=te.value;if(te.options[0].textContent="All events",xe){for(;te.options.length>1;)te.remove(1);for(let ve of _){let Ce=h("option","");Ce.value=ve,Ce.textContent=`${ve} (${J[ve]||0})`,te.appendChild(Ce)}pt&&_.includes(pt)?te.value=pt:pt&&(te.value="",C="")}else for(let ve=1;ve<te.options.length;ve++){let Ce=te.options[ve];Ce.textContent=`${Ce.value} (${J[Ce.value]||0})`}}function ze(){let Z=n.getAll();if(C&&(Z=Z.filter(J=>J.type===C)),v){let J=v.toLowerCase();Z=Z.filter(_=>_.type.toLowerCase().includes(J)||_.payload.toLowerCase().includes(J))}return Z}function X(){return C!==""||v!==""}function K(){q=0,N=0,M=!1,ie.style.display="none"}function tt(Z){z.has(Z)?z.delete(Z):z.add(Z),ye=Z;let J=de.scrollTop,_=M;Y=!0,M=!0,Ve(),de.scrollTop=J,M=_,Y=!1}function We(){return de.scrollHeight-de.scrollTop-de.clientHeight<=50}function Ve(){w=Date.now(),F=!1,be();let Z=n.getEvictedCount();Z>0?(ut.textContent=`${Z.toLocaleString()} older events truncated`,ut.style.display=""):ut.style.display="none",m=ze();let J=m.length,_=n.getSize()>0;ee&&(ee.textContent=String(n.getSize())),J===0&&_&&X()?(G.textContent=v?`No events matching '${v}'`:"No events matching filter",G.style.display="",de.style.display="none"):(G.style.display="none",de.style.display=""),D&&(D.title=X()?`Copy Filtered (${J})`:"Copy All"),M&&J>q&&(N+=J-q,j.textContent=`${N} new event${N===1?"":"s"}`,ie.style.display=""),q=J;let xe=n.getAll(),Le=xe.length>0?xe[0].timestamp:0,He=new Set(m.map(Ce=>Ce.id));for(let Ce of z)He.has(Ce)||z.delete(Ce);let pt=C!==Ie||v!==Xe,ve=ge.size===0&&m.length>0;if(pt||ve||m.length===0){de.innerHTML="",ge.clear();let Ce=document.createDocumentFragment();for(let Be=0;Be<m.length;Be++){let ue=fs(m[Be],Be,Le,a,z,tt,o,s);ge.set(m[Be].id,ue),Ce.appendChild(ue)}de.appendChild(Ce),Ie=C,Xe=v,ye=null}else{if(ye!==null){let Be=ge.get(ye);if(Be&&Be.parentNode===de){let ue=m.findIndex(bt=>bt.id===ye);if(ue>=0){let bt=fs(m[ue],ue,Le,a,z,tt,o,s);de.insertBefore(bt,Be),Be.remove(),ge.set(ye,bt)}}ye=null}let Ce=new Set(m.map(Be=>Be.id));for(let[Be,ue]of ge)Ce.has(Be)||(ue.remove(),ge.delete(Be));for(let Be=0;Be<m.length;Be++){let ue=m[Be];if(!ge.has(ue.id)){let bt=fs(ue,Be,Le,a,z,tt,o,s);ge.set(ue.id,bt),de.appendChild(bt)}}}M||(de.scrollTop=de.scrollHeight)}function Tt(){if(Date.now()-w>=Sd){re!==null&&(cancelAnimationFrame(re),re=null),Ve();return}F||(F=!0,re=requestAnimationFrame(()=>{re=null,Ve()}))}let _t=(Z,J)=>{if(!D)return;D.innerHTML="";let _=me(Z,"12px","currentColor",1.5);_&&D.appendChild(_);let xe=h("span","persona-text-xs");xe.textContent="Copy All",D.appendChild(xe),setTimeout(()=>{D.innerHTML="";let Le=me("clipboard-copy","12px","currentColor",1.5);Le&&D.appendChild(Le);let He=h("span","persona-text-xs");He.textContent="Copy All",D.appendChild(He),D.disabled=!1},J)},ce=async()=>{if(D){D.disabled=!0;try{let Z;X()?Z=m:t?(Z=await t(),Z.length===0&&(Z=n.getAll())):Z=n.getAll();let J=Z.map(_=>{try{return JSON.parse(_.payload)}catch{return _.payload}});await navigator.clipboard.writeText(JSON.stringify(J,null,2)),_t("check",1500)}catch{_t("x",1500)}}},Je=()=>{te&&(C=te.value,K(),Ve())},Me=()=>{!U||!oe||(oe.style.display=U.value?"":"none",E&&clearTimeout(E),E=setTimeout(()=>{v=U.value,K(),Ve()},150))},nt=()=>{!U||!oe||(U.value="",v="",oe.style.display="none",E&&clearTimeout(E),K(),Ve())},je=()=>{if(Y)return;let Z=de.scrollTop,J=Z>ae;ae=Z,We()&&J?(M=!1,N=0,ie.style.display="none"):We()||(M=!0)},Ze=Z=>{Z.deltaY<0&&(M=!0)},Rt=()=>{de.scrollTop=de.scrollHeight,M=!1,N=0,ie.style.display="none"},Ht=Z=>{let J=Z.target;if(!J||J.closest("button"))return;let _=J.closest("[data-event-id]");if(!_)return;let xe=_.getAttribute("data-event-id");xe&&tt(xe)},Mt=Z=>{if((Z.metaKey||Z.ctrlKey)&&Z.key==="f"){Z.preventDefault(),U==null||U.focus(),U==null||U.select();return}Z.key==="Escape"&&(U&&document.activeElement===U?(nt(),U.blur(),f.focus()):r&&r())};D&&D.addEventListener("click",ce),te&&te.addEventListener("change",Je),U&&U.addEventListener("input",Me),oe&&oe.addEventListener("click",nt),de.addEventListener("scroll",je),de.addEventListener("wheel",Ze,{passive:!0}),de.addEventListener("click",Ht),ie.addEventListener("click",Rt),f.addEventListener("keydown",Mt);function B(){E&&clearTimeout(E),re!==null&&(cancelAnimationFrame(re),re=null),F=!1,ge.clear(),D&&D.removeEventListener("click",ce),te&&te.removeEventListener("change",Je),U&&U.removeEventListener("input",Me),oe&&oe.removeEventListener("click",nt),de.removeEventListener("scroll",je),de.removeEventListener("wheel",Ze),de.removeEventListener("click",Ht),ie.removeEventListener("click",Rt),f.removeEventListener("keydown",Mt)}return{element:f,update:Tt,destroy:B}}}var Bl=e=>{let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",t=typeof e.artifactId=="string"?e.artifactId:"",r=e.status==="streaming"?"streaming":"complete",o=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",a=document.createElement("div");a.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.backgroundColor="var(--persona-bg, #ffffff)",a.style.cursor="pointer",a.tabIndex=0,a.setAttribute("role","button"),a.setAttribute("aria-label",`Open ${n} in artifact panel`),t&&a.setAttribute("data-open-artifact",t);let i=document.createElement("div");i.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.color="var(--persona-muted, #9ca3af)",i.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let d=document.createElement("div");d.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let c=document.createElement("div");c.className="persona-truncate persona-text-sm persona-font-medium",c.style.color="var(--persona-text, #1f2937)",c.textContent=n;let g=document.createElement("div");if(g.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",g.style.color="var(--persona-muted, #9ca3af)",r==="streaming"){let p=document.createElement("span");p.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",p.style.backgroundColor="var(--persona-primary, #3b82f6)",p.style.animation="persona-pulse 1.5s ease-in-out infinite",g.appendChild(p);let f=document.createElement("span");f.textContent=`Generating ${o.toLowerCase()}...`,g.appendChild(f)}else g.textContent=o;if(d.append(c,g),a.append(i,d),r==="complete"){let p=document.createElement("button");p.type="button",p.textContent="Download",p.title=`Download ${n}`,p.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-text, #1f2937)",p.style.backgroundColor="transparent",p.style.cursor="pointer",p.setAttribute("data-download-artifact",t),a.append(p)}return a};var hs=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)})}},$n=new hs;$n.register("PersonaArtifactCard",Bl);function Id(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 to(e,n,t=""){let r=h("button",`persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-p-1 persona-text-persona-primary hover:persona-bg-persona-container ${t}`);r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=me(e,16,"currentColor",2);return s&&r.appendChild(s),r}function no(e,n,t){let r=h("button",`persona-artifact-doc-icon-btn ${t}`.trim());r.type="button",r.setAttribute("aria-label",n),r.title=n;let s=me(e,16,"currentColor",2);return s&&r.appendChild(s),r}function Fl(e){let n=h("button","persona-artifact-doc-copy-btn");n.type="button",n.setAttribute("aria-label","Copy"),n.title="Copy";let t=me("copy",e?14:16,"currentColor",2);if(t&&n.appendChild(t),e){let r=h("span","persona-artifact-doc-copy-label");r.textContent="Copy",n.appendChild(r)}return n}function Wd(){let e=h("button","persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn");e.type="button",e.setAttribute("aria-label","More copy options"),e.setAttribute("aria-haspopup","true"),e.setAttribute("aria-expanded","false");let n=me("chevron-down",14,"currentColor",2);return n&&e.appendChild(n),e}function $l(e,n){var Wt,de,ie,qe;let t=(de=(Wt=e.features)==null?void 0:Wt.artifacts)==null?void 0:de.layout,s=((ie=t==null?void 0:t.toolbarPreset)!=null?ie:"default")==="document",o=(qe=t==null?void 0:t.panePadding)==null?void 0:qe.trim(),a=e.markdown?lr(e.markdown):null,i=jr(e.sanitize),d=j=>{let G=a?a(j):_r(j);return i?i(G):G},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,g=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")};c&&c.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let C=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");C.type="button",C.textContent="Close",C.setAttribute("aria-label","Close artifacts panel"),C.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let v="rendered",E=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),x=s?no("eye","Rendered view","persona-artifact-view-btn"):to("eye","Rendered view",""),k=s?no("code-2","Source","persona-artifact-code-btn"):to("code-2","Source",""),q=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,N=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,w=t==null?void 0:t.documentToolbarCopyMenuItems,F=!!(N&&w&&w.length>0),re=null,Y,ae=null,z=null;if(s&&(M||N)&&!F){if(Y=Fl(M),N){let j=me("chevron-down",14,"currentColor",2);j&&Y.appendChild(j)}}else if(s&&F){re=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),Y=Fl(M),ae=Wd(),re.append(Y,ae),z=h("div","persona-artifact-doc-copy-menu persona-absolute persona-right-0 persona-top-full persona-z-20 persona-mt-1 persona-min-w-[10rem] persona-rounded-md persona-border persona-border-persona-border persona-bg-persona-surface persona-py-1 persona-shadow-md persona-hidden"),re.appendChild(z);for(let j of w){let G=h("button","persona-block persona-w-full persona-text-left persona-px-3 persona-py-2 persona-text-xs persona-text-persona-primary hover:persona-bg-persona-container");G.type="button",G.textContent=j.label,G.dataset.copyMenuId=j.id,z.appendChild(G)}}else s?Y=no("copy","Copy",""):Y=to("copy","Copy","");let ge=s?no("refresh-cw","Refresh",""):to("refresh-cw","Refresh",""),Ie=s?no("x","Close",""):to("x","Close",""),Xe=()=>{var X,K,tt;let j=(X=oe.find(We=>We.id===he))!=null?X:oe[oe.length-1],G=(K=j==null?void 0:j.id)!=null?K:null,be=(j==null?void 0:j.artifactType)==="markdown"&&(tt=j.markdown)!=null?tt:"",ze=j?JSON.stringify({component:j.component,props:j.props},null,2):"";return{markdown:be,jsonPayload:ze,id:G}},ye=async()=>{var X;let{markdown:j,jsonPayload:G}=Xe(),be=(X=oe.find(K=>K.id===he))!=null?X:oe[oe.length-1],ze=(be==null?void 0:be.artifactType)==="markdown"?j:be?G:"";try{await navigator.clipboard.writeText(ze)}catch{}};if(Y.addEventListener("click",async()=>{let j=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(j&&F){let{markdown:G,jsonPayload:be,id:ze}=Xe();try{await j({actionId:"primary",artifactId:ze,markdown:G,jsonPayload:be})}catch{}return}await ye()}),ae&&z){let j=()=>{z.classList.add("persona-hidden"),ae.setAttribute("aria-expanded","false")};ae.addEventListener("click",G=>{G.stopPropagation(),z.classList.contains("persona-hidden")?(z.classList.remove("persona-hidden"),ae.setAttribute("aria-expanded","true")):j()}),typeof document!="undefined"&&document.addEventListener("click",j),z.addEventListener("click",async G=>{let be=G.target.closest("button[data-copy-menu-id]");if(!(be!=null&&be.dataset.copyMenuId))return;G.stopPropagation();let ze=be.dataset.copyMenuId,{markdown:X,jsonPayload:K,id:tt}=Xe(),We=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{We?await We({actionId:ze,artifactId:tt,markdown:X,jsonPayload:K}):ze==="markdown"||ze==="md"?await navigator.clipboard.writeText(X):ze==="json"||ze==="source"?await navigator.clipboard.writeText(K):await navigator.clipboard.writeText(X||K)}catch{}j()})}ge.addEventListener("click",async()=>{var j;try{await((j=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:j.call(t))}catch{}at()}),Ie.addEventListener("click",()=>{var j;g(),(j=n.onDismiss)==null||j.call(n)});let ee=()=>{s&&(x.setAttribute("aria-pressed",v==="rendered"?"true":"false"),k.setAttribute("aria-pressed",v==="source"?"true":"false"))};x.addEventListener("click",()=>{v="rendered",ee(),at()}),k.addEventListener("click",()=>{v="source",ee(),at()});let te=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(),E.append(x,k),re?q.append(re,ge,Ie):q.append(Y,ge,Ie),f.append(E,te,q),ee()):(f.appendChild(m),f.appendChild(C)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let D=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"),U=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(D.style.paddingLeft=o,D.style.paddingRight=o,U.style.padding=o),p.appendChild(f),p.appendChild(D),p.appendChild(U);let oe=[],he=null,ht=!1,at=()=>{var ze,X,K,tt;let j=s&&oe.length<=1;D.classList.toggle("persona-hidden",j),D.replaceChildren();for(let We of oe){let Ve=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 hover:persona-bg-persona-container");Ve.type="button",Ve.textContent=We.title||We.id.slice(0,8),We.id===he&&Ve.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ve.addEventListener("click",()=>n.onSelect(We.id)),D.appendChild(Ve)}U.replaceChildren();let G=he&&oe.find(We=>We.id===he)||oe[oe.length-1];if(!G)return;if(s){let We=G.artifactType==="markdown"?"MD":(ze=G.component)!=null?ze:"Component",Tt=(G.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";te.textContent=`${Tt} \xB7 ${We}`}else m.textContent="Artifacts";if(G.artifactType==="markdown"){if(s&&v==="source"){let Ve=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ve.textContent=(X=G.markdown)!=null?X:"",U.appendChild(Ve);return}let We=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");We.innerHTML=d((K=G.markdown)!=null?K:""),U.appendChild(We);return}let be=G.component?$n.get(G.component):void 0;if(be){let Ve={message:{id:G.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Tt=be((tt=G.props)!=null?tt:{},Ve);if(Tt){U.appendChild(Tt);return}}catch{}}U.appendChild(Id(G))},ut=()=>{var G;let j=oe.length>0;if(p.classList.toggle("persona-hidden",!j),c){let be=typeof p.closest=="function"?p.closest("#persona-root"):null,X=((G=be==null?void 0:be.classList.contains("persona-artifact-narrow-host"))!=null?G:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;j&&X&&ht?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(j){var G,be,ze;oe=j.artifacts,he=(ze=(be=j.selectedId)!=null?be:(G=j.artifacts[j.artifacts.length-1])==null?void 0:G.id)!=null?ze:null,oe.length>0&&(ht=!0),at(),ut()},setMobileOpen(j){ht=j,!j&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):ut()}}}function an(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 Nl(e,n){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!an(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=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Rd(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 Ho(e,n){var d,c,g,p,f,m,C,v,E,x;if(!an(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"),Rd(e),Nl(e,n);return}let t=(c=(d=n.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(g=t==null?void 0:t.splitGap)!=null?g:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(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=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let s=(C=t==null?void 0:t.panePadding)==null?void 0:C.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(v=t==null?void 0:t.documentToolbarIconColor)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(x=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:x.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Nl(e,n)}var Ol=["panel","seamless"];function Bo(e,n){var i,d,c,g,p,f;for(let m of Ol)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!an(n))return;let t=(d=(i=n.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Ol.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(g=t==null?void 0:t.paneBorderRadius)==null?void 0:g.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Dl(e,n){var t,r,s;return!n||!an(e)?!1:((s=(r=(t=e.features)==null?void 0:t.artifacts)==null?void 0:r.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Hd(e,n){if(!(e!=null&&e.trim()))return n;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):n}function Bd(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 Fd(e,n,t){return t<n?n:Math.min(t,Math.max(n,e))}function $d(e,n,t,r){let s=e-r-2*n-t;return Math.max(0,s)}function _l(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 jl(e,n,t,r,s,o){let a=Hd(s,200),i=$d(n,t,r,200);i=Math.max(a,i);let d=Bd(o);return d!==null&&(i=Math.min(i,d)),Fd(e,a,i)}var Vl={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"}},ys=(e,n,t,r)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var C,v,E;if(o.dataset.enhanced==="true")return;let a=(C=o.dataset.tvForm)!=null?C:"init";o.dataset.enhanced="true";let i=(v=Vl[a])!=null?v:Vl.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,d.appendChild(x)}let g=document.createElement("form");g.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var w,F;let k=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");k.htmlFor=`${n.id}-${a}-${x.name}`;let q=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");q.textContent=x.label,k.appendChild(q);let M=(w=x.type)!=null?w:"text",N;M==="textarea"?(N=document.createElement("textarea"),N.rows=3):(N=document.createElement("input"),N.type=M),N.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",N.id=`${n.id}-${a}-${x.name}`,N.name=x.name,N.placeholder=(F=x.placeholder)!=null?F:"",x.required&&(N.required=!0),k.appendChild(N),g.appendChild(k)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(E=i.submitLabel)!=null?E:"Submit",p.appendChild(f),p.appendChild(m),g.appendChild(p),o.replaceChildren(d,g),g.addEventListener("submit",async x=>{var N,w;x.preventDefault();let k=(N=t.formEndpoint)!=null?N:"/form",q=new FormData(g),M={};q.forEach((F,re)=>{M[re]=F}),M.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let F=await fetch(k,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!F.ok)throw new Error(`Form submission failed (${F.status})`);let re=await F.json();f.textContent=(w=re.message)!=null?w:"Thanks! We'll be in touch soon.",re.success&&re.nextPrompt&&await r.sendMessage(String(re.nextPrompt))}catch(F){f.textContent=F instanceof Error?F.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var bs=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,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(n=>{var t;return(t=n.onUnregister)==null?void 0:t.call(n)}),this.plugins.clear()}},Fo=new bs;var Ul={primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#6b7280",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#111827",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},ql={primary:"#f9fafb",accent:"#3b82f6",surface:"#1f2937",muted:"#9ca3af",container:"#111827",border:"#374151",divider:"#374151",messageBorder:"#374151",inputBackground:"#111827",callToAction:"#ffffff",callToActionBackground:"#374151",sendButtonBackgroundColor:"#3b82f6",sendButtonTextColor:"#ffffff",sendButtonBorderColor:"#60a5fa",closeButtonColor:"#9ca3af",closeButtonBackgroundColor:"transparent",closeButtonBorderColor:"",clearChatIconColor:"#9ca3af",clearChatBackgroundColor:"transparent",clearChatBorderColor:"transparent",micIconColor:"#f9fafb",micBackgroundColor:"transparent",micBorderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",inputFontFamily:"sans-serif",inputFontWeight:"400",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},ft={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:Ul,darkTheme:ql,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px",collapsedWidth:"72px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",closeButtonColor:"#6b7280",closeButtonBackgroundColor:"transparent",clearChat:{iconColor:"#6b7280",backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function xs(e){var n,t,r,s,o,a,i,d,c,g,p,f,m,C,v,E,x,k,q,M,N;return e?{...ft,...e,theme:{...ft.theme,...e.theme},darkTheme:{...ft.darkTheme,...e.darkTheme},launcher:{...ft.launcher,...e.launcher,dock:{...(n=ft.launcher)==null?void 0:n.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(r=ft.launcher)==null?void 0:r.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...ft.copy,...e.copy},sendButton:{...ft.sendButton,...e.sendButton},statusIndicator:{...ft.statusIndicator,...e.statusIndicator},voiceRecognition:{...ft.voiceRecognition,...e.voiceRecognition},features:(()=>{var Y,ae;let w=(Y=ft.features)==null?void 0:Y.artifacts,F=(ae=e.features)==null?void 0:ae.artifacts,re=w===void 0&&F===void 0?void 0:{...w,...F,layout:{...w==null?void 0:w.layout,...F==null?void 0:F.layout}};return{...ft.features,...e.features,...re!==void 0?{artifacts:re}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:ft.suggestionChips,suggestionChipsConfig:{...ft.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ft.layout,...e.layout,header:{...(a=ft.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=ft.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(g=ft.layout)==null?void 0:g.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(v=(C=ft.layout)==null?void 0:C.messages)==null?void 0:v.timestamp,...(x=(E=e.layout)==null?void 0:E.messages)==null?void 0:x.timestamp}},slots:{...(k=ft.layout)==null?void 0:k.slots,...(q=e.layout)==null?void 0:q.slots}},markdown:{...ft.markdown,...e.markdown,options:{...(M=ft.markdown)==null?void 0:M.options,...(N=e.markdown)==null?void 0:N.options}},messageActions:{...ft.messageActions,...e.messageActions}}:ft}var zl=()=>{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(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Nd=e=>{let n=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return n?n[1]:e},Od=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},$o=({text:e})=>{if(!e||!e.includes("{"))return null;try{let n=Nd(e),t=Od(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}},vs=e=>typeof e=="string"?e:e==null?"":String(e),br={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:vs(e.payload.text)},messageAndClick:(e,n)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,r=vs(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:vs(t.text)}}},Jl=e=>Array.isArray(e)?e.map(n=>String(n)):[],No=e=>{let n=new Set(Jl(e.getSessionMetadata().processedActionMessageIds)),t=()=>{n=new Set(Jl(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,g)=>c||(g==null?void 0:g({text:a,message:o.message}))||null,null):null;if(!i)return null;n.add(o.message.id),r();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let g=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:g});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",g)}return{text:"",persist:!0}},syncFromMetadata:t}};var Dd=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}},_d=e=>e.map(n=>({...n,streaming:!1})),Cs=(e="persona-state")=>{let n=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=n();return t?Dd(t.getItem(e)):null},save:t=>{let r=n();if(r)try{let s={...t,messages:t.messages?_d(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)}}}};import{parse as jd,STR as Vd,OBJ as Ud}from"partial-json";function qd(e){if(!e||typeof e!="object"||!("component"in e))return!1;let n=e.component;return typeof n=="string"&&n.length>0}function zd(e,n){if(!qd(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 ws(){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=jd(t,Vd|Ud),o=zd(s,t);o&&(e=o)}catch{}return n=t.length,e},reset:()=>{e=null,n=0}}}function Jd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ss(e,n){let{config:t,message:r,onPropsUpdate:s}=n,o=$n.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 Kd(){let e=ws();return{processChunk:n=>e.processChunk(n),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function As(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 Es(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 Yd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Ts(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:d=!0,ratingLabels:c=Yd}=e,g=document.createElement("div");g.className="persona-feedback-container persona-feedback-csat",g.setAttribute("role","dialog"),g.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let C=document.createElement("h3");C.className="persona-feedback-title",C.textContent=r,m.appendChild(C);let v=document.createElement("p");v.className="persona-feedback-subtitle",v.textContent=s,m.appendChild(v),f.appendChild(m);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let w=1;w<=5;w++){let F=document.createElement("button");F.type="button",F.className="persona-feedback-rating-btn persona-feedback-star-btn",F.setAttribute("role","radio"),F.setAttribute("aria-checked","false"),F.setAttribute("aria-label",`${w} star${w>1?"s":""}: ${c[w-1]}`),F.title=c[w-1],F.dataset.rating=String(w),F.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var F,w,P,W,R,U,ve,le,q,ee,Ce,we;let a=(F=o.launcher)!=null?F:{},i=zt(o),d=t.querySelector("[data-role='launcher-title']");d&&(d.textContent=(w=a.title)!=null?w:"Chat Assistant");let c=t.querySelector("[data-role='launcher-subtitle']");c&&(c.textContent=(P=a.subtitle)!=null?P:"Get answers fast");let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let p=t.querySelector("[data-role='launcher-icon']");if(p)if(a.agentIconHidden)p.style.display="none";else{let ye=(W=a.agentIconSize)!=null?W:"40px";if(p.style.height=ye,p.style.width=ye,p.innerHTML="",a.agentIconName){let ce=parseFloat(ye)||24,Q=me(a.agentIconName,ce*.6,"var(--persona-text-inverse, #ffffff)",2);Q?(p.appendChild(Q),p.style.display=""):(p.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",p.style.display="")}else a.iconUrl?p.style.display="none":(p.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",p.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let ye=(ve=a.agentIconSize)!=null?ve:"40px";f.style.height=ye,f.style.width=ye,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(f.src=a.iconUrl,f.style.display="block"):f.style.display="none"}let m=t.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let ye=(le=a.callToActionIconSize)!=null?le:"32px";m.style.height=ye,m.style.width=ye,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary"));let ce=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,ce=(parseFloat(a.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),a.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",a.callToActionIconName){let Q=parseFloat(ye)||24,J=Math.max(Q-ce,8),V=me(a.callToActionIconName,J,"currentColor",2);V?m.appendChild(V):m.textContent=(q=a.callToActionIconText)!=null?q:"\u2197"}else m.textContent=(ee=a.callToActionIconText)!=null?ee:"\u2197"}let x=a.position&&yn[a.position]?yn[a.position]:yn["bottom-right"],b="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer persona-z-50",S="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?S:`${b} ${x}`;let v="1px solid var(--persona-border, #e5e7eb)",T="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=(Ce=a.border)!=null?Ce:v,t.style.boxShadow=(we=a.shadow)!=null?we:T,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="",t.style.justifyContent="",t.style.padding="",t.style.overflow="")},s=()=>{t.removeEventListener("click",r),t.remove()};return e&&n(e),{element:t,update:n,destroy:s}};var bn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #2563eb))",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))"},jn=e=>{var le,q,ee,Ce,we,ye,ce,Q,J,V,ne,fe,wt,ut,gt,Tt,se,re,Ue,z,te,de,Qe,G,Y,tt,Ne,je,Mt,qt,ue,Ye;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=(le=r==null?void 0:r.launcher)!=null?le:{},o=(q=s.headerIconSize)!=null?q:"48px",a=(ee=s.closeButtonSize)!=null?ee:"32px",i=(Ce=s.closeButtonPlacement)!=null?Ce:"inline",d=(we=s.headerIconHidden)!=null?we:!1,c=s.headerIconName,u=h("div","persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl");if(u.style.height=o,u.style.width=o,u.style.backgroundColor="var(--persona-header-icon-bg, var(--persona-primary, #2563eb))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!d)if(c){let ke=parseFloat(o)||24,ot=me(c,ke*.6,"currentColor",1);ot?u.replaceChildren(ot):u.textContent=(ce=(ye=r==null?void 0:r.launcher)==null?void 0:ye.agentIconText)!=null?ce:"\u{1F4AC}"}else if((Q=r==null?void 0:r.launcher)!=null&&Q.iconUrl){let ke=h("img");ke.src=r.launcher.iconUrl,ke.alt="",ke.className="persona-rounded-xl persona-object-cover",ke.style.height=o,ke.style.width=o,u.replaceChildren(ke)}else u.textContent=(V=(J=r==null?void 0:r.launcher)==null?void 0:J.agentIconText)!=null?V:"\u{1F4AC}";let p=h("div","persona-flex persona-flex-col"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(fe=(ne=r==null?void 0:r.launcher)==null?void 0:ne.title)!=null?fe:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(ut=(wt=r==null?void 0:r.launcher)==null?void 0:wt.subtitle)!=null?ut:"Here to help you get answers fast",p.append(f,m),d?n.append(p):n.append(u,p);let x=(gt=s.clearChat)!=null?gt:{},b=(Tt=x.enabled)!=null?Tt:!0,S=(se=x.placement)!=null?se:"inline",v=null,T=null;if(b){let ke=(re=x.size)!=null?re:"32px",ot=(Ue=x.iconName)!=null?Ue:"refresh-cw",Ve=(z=x.iconColor)!=null?z:"",nt=(te=x.backgroundColor)!=null?te:"",Rt=(de=x.borderWidth)!=null?de:"",Ht=(Qe=x.borderColor)!=null?Qe:"",kt=(G=x.borderRadius)!=null?G:"",N=(Y=x.paddingX)!=null?Y:"",X=(tt=x.paddingY)!=null?tt:"",_=(Ne=x.tooltipText)!=null?Ne:"Clear chat",be=(je=x.showTooltip)!=null?je:!0;T=h("div",S==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),S==="top-right"&&(T.style.right="48px"),v=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"),v.style.height=ke,v.style.width=ke,v.type="button",v.setAttribute("aria-label",_),v.style.color=Ve||bn.actionIconColor;let xe=me(ot,"20px","currentColor",1);if(xe&&v.appendChild(xe),nt&&(v.style.backgroundColor=nt,v.classList.remove("hover:persona-bg-gray-100")),Rt||Ht){let Ae=Rt||"0px",Ee=Ht||"transparent";v.style.border=`${Ae} solid ${Ee}`,v.classList.remove("persona-border-none")}if(kt&&(v.style.borderRadius=kt,v.classList.remove("persona-rounded-full")),N?(v.style.paddingLeft=N,v.style.paddingRight=N):(v.style.paddingLeft="",v.style.paddingRight=""),X?(v.style.paddingTop=X,v.style.paddingBottom=X):(v.style.paddingTop="",v.style.paddingBottom=""),T.appendChild(v),be&&_&&v&&T){let Ae=null,Ee=()=>{if(Ae||!v)return;let Be=v.ownerDocument,We=Be.body;if(!We)return;Ae=An(Be,"div","persona-clear-chat-tooltip"),Ae.textContent=_;let ze=An(Be,"div");ze.className="persona-clear-chat-tooltip-arrow",Ae.appendChild(ze);let pe=v.getBoundingClientRect();Ae.style.position="fixed",Ae.style.left=`${pe.left+pe.width/2}px`,Ae.style.top=`${pe.top-8}px`,Ae.style.transform="translate(-50%, -100%)",We.appendChild(Ae)},st=()=>{Ae&&Ae.parentNode&&(Ae.parentNode.removeChild(Ae),Ae=null)};T.addEventListener("mouseenter",Ee),T.addEventListener("mouseleave",st),v.addEventListener("focus",Ee),v.addEventListener("blur",st),T._cleanupTooltip=()=>{st(),T&&(T.removeEventListener("mouseenter",Ee),T.removeEventListener("mouseleave",st)),v&&(v.removeEventListener("focus",Ee),v.removeEventListener("blur",st))}}S==="inline"&&n.appendChild(T)}let F=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&S==="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 P=(Mt=s.closeButtonTooltipText)!=null?Mt:"Close chat",W=(qt=s.closeButtonShowTooltip)!=null?qt:!0;w.setAttribute("aria-label",P),w.style.display=t?"":"none";let R=(ue=s.closeButtonIconName)!=null?ue:"x",U=(Ye=s.closeButtonIconText)!=null?Ye:"\xD7";w.style.color=s.closeButtonColor||bn.actionIconColor;let ve=me(R,"20px","currentColor",1);if(ve?w.appendChild(ve):w.textContent=U,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 ke=s.closeButtonBorderWidth||"0px",ot=s.closeButtonBorderColor||"transparent";w.style.border=`${ke} solid ${ot}`,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=""),F.appendChild(w),W&&P){let ke=null,ot=()=>{if(ke)return;let nt=w.ownerDocument,Rt=nt.body;if(!Rt)return;ke=An(nt,"div","persona-clear-chat-tooltip"),ke.textContent=P;let Ht=An(nt,"div");Ht.className="persona-clear-chat-tooltip-arrow",ke.appendChild(Ht);let kt=w.getBoundingClientRect();ke.style.position="fixed",ke.style.left=`${kt.left+kt.width/2}px`,ke.style.top=`${kt.top-8}px`,ke.style.transform="translate(-50%, -100%)",Rt.appendChild(ke)},Ve=()=>{ke&&ke.parentNode&&(ke.parentNode.removeChild(ke),ke=null)};F.addEventListener("mouseenter",ot),F.addEventListener("mouseleave",Ve),w.addEventListener("focus",ot),w.addEventListener("blur",Ve),F._cleanupTooltip=()=>{Ve(),F.removeEventListener("mouseenter",ot),F.removeEventListener("mouseleave",Ve),w.removeEventListener("focus",ot),w.removeEventListener("blur",Ve)}}return i!=="top-right"&&n.appendChild(F),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:w,closeButtonWrapper:F,clearChatButton:v,clearChatButtonWrapper:T}},vr=(e,r,t)=>{var a,i,d,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(d=n.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(r.header),s==="top-right"&&(e.style.position="relative",e.appendChild(r.closeButtonWrapper)),r.clearChatButtonWrapper&&o==="top-right"&&(e.style.position="relative",e.appendChild(r.clearChatButtonWrapper))};function sr(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="10000"):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",s==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of r){if(m.dividerBefore){let S=document.createElement("hr");a.appendChild(S)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let S=me(m.icon,16,"currentColor",1.5);S&&x.appendChild(S)}let b=document.createElement("span");b.textContent=m.label,x.appendChild(b),x.addEventListener("click",S=>{S.stopPropagation(),u(),t(m.id)}),a.appendChild(x)}let i=null;function d(){if(!o)return;let m=n.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,s==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!a.contains(x.target)&&!n.contains(x.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function p(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:p,destroy:f}}function _t(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,d=h("button","persona-icon-btn"+(o?" "+o:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,p]of Object.entries(i))d.setAttribute(u,p);return d}function _o(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:d}=e,c="persona-label-btn";n!=="default"&&(c+=" persona-label-btn--"+n),c+=" persona-label-btn--"+s,a&&(c+=" "+a);let u=h("button",c);if(u.type="button",u.setAttribute("aria-label",t),r){let f=me(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let p=h("span");if(p.textContent=t,u.appendChild(p),i&&u.addEventListener("click",i),d)for(let[f,m]of Object.entries(d))u.setAttribute(f,m);return u}function md(e){let{items:r,selectedId:t,onSelect:n,className:s}=e,o=h("div","persona-toggle-group"+(s?" "+s:""));o.setAttribute("role","group");let a=t,i=[];function d(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let p;u.icon?p=_t({icon:u.icon,label:u.label,onClick:()=>{a=u.id,d(),n(u.id)}}):(p=h("button","persona-icon-btn"),p.type="button",p.setAttribute("aria-label",u.label),p.title=u.label,p.textContent=u.label,p.addEventListener("click",()=>{a=u.id,d(),n(u.id)})),p.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:p}),o.appendChild(p)}function c(u){a=u,d()}return{element:o,setSelected:c}}function fs(e){var m,x;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:d}=e,c=h("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",r);let u=h("span","persona-combo-btn-label");u.textContent=r,c.appendChild(u);let p=me(t,14,"currentColor",2);p&&(p.style.marginLeft="4px",p.style.opacity="0.6",c.appendChild(p)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(x=d.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 b,S;c.style.backgroundColor=(b=d.background)!=null?b:"",c.style.borderColor=(S=d.border)!=null?S:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=sr({items:n,onSelect:b=>{c.setAttribute("aria-expanded","false"),s(b)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",b=>{b.stopPropagation();let S=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",S?"false":"true"),f.toggle()}),c.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),c.click())}),{element:c,setLabel:b=>{u.textContent=b,c.setAttribute("aria-label",b)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ll=e=>{var n;let r=jn({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 fd(e,r,t){var n,s,o;if(r!=null&&r.length)for(let a of r){let i=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(s=(n=a.ariaLabel)!=null?n:a.label)!=null?s:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let d=h("div","persona-relative");d.appendChild(i);let c=sr({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Pl=e=>{var T,F,w,P,W,R,U,ve,le;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(T=r==null?void 0:r.launcher)!=null?T:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=s==null?void 0:s.titleMenu,c,u;if(d)c=fs({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=bn.titleColor,u=(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"),u=h("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=bn.titleColor,u.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(u),fd(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 ee=s.onTitleClick;c.addEventListener("click",Ce=>{Ce.target.closest("button")||ee()}),c.addEventListener("keydown",Ce=>{(Ce.key==="Enter"||Ce.key===" ")&&(Ce.preventDefault(),ee())})}let q=s==null?void 0:s.titleRowHover;q&&(c.style.borderRadius=(R=q.borderRadius)!=null?R:"10px",c.style.padding=(U=q.padding)!=null?U:"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 ee,Ce;c.style.backgroundColor=(ee=q.background)!=null?ee:"",c.style.borderColor=(Ce=q.border)!=null?Ce:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let p=(ve=a.closeButtonSize)!=null?ve:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=p,m.style.width=p,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let x=(le=a.closeButtonIconName)!=null?le:"x",b=me(x,"20px","currentColor",2);b?m.appendChild(b):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let S=h("div");S.style.display="none";let v=h("span");return v.style.display="none",{header:i,iconHolder:S,headerTitle:u,headerSubtitle:v,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},hs={default:Ll,minimal:Pl},Il=e=>{var r;return(r=hs[e])!=null?r:hs.default},ro=(e,r,t)=>{var a,i,d;if(r!=null&&r.render){let c=r.render({config:e,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:r.trailingActions,onAction:r.onAction}),u=h("div");u.style.display="none";let p=h("span"),f=h("span"),m=h("button");m.style.display="none";let x=h("div");return x.style.display="none",{header:c,iconHolder:u,headerTitle:p,headerSubtitle:f,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Il(n)({config:e,showClose:(d=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var oo=e=>{var gt,Tt,se,re,Ue,z,te,de,Qe,G,Y,tt,Ne,je,Mt,qt,ue,Ye,ke,ot,Ve,nt,Rt,Ht,kt,N,X;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=(Tt=(gt=r==null?void 0:r.copy)==null?void 0:gt.inputPlaceholder)!=null?Tt:"Type your message\u2026",o.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",o.rows=1,o.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',o.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let d=3*20;o.style.maxHeight=`${d}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let _=Math.min(o.scrollHeight,d);o.style.height=`${_}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 u=(se=r==null?void 0:r.sendButton)!=null?se:{},p=(re=u.useIcon)!=null?re:!1,f=(Ue=u.iconText)!=null?Ue:"\u2191",m=u.iconName,x=(z=u.tooltipText)!=null?z:"Send message",b=(te=u.showTooltip)!=null?te:!1,S=(de=u.size)!=null?de:"40px",v=u.backgroundColor,T=u.textColor,F=h("div","persona-send-button-wrapper"),w=h("button",p?"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",""),p){if(w.style.width=S,w.style.height=S,w.style.minWidth=S,w.style.minHeight=S,w.style.fontSize="18px",w.style.lineHeight="1",w.innerHTML="",m){let _=parseFloat(S)||24,be=T&&typeof T=="string"&&T.trim()?T.trim():"currentColor",xe=me(m,_,be,2);xe?(w.appendChild(xe),w.style.color=be):(w.textContent=f,T?w.style.color=T:w.classList.add("persona-text-white"))}else w.textContent=f,T?w.style.color=T:w.classList.add("persona-text-white");v?w.style.backgroundColor=v:w.classList.add("persona-bg-persona-primary")}else w.textContent=(G=(Qe=r==null?void 0:r.copy)==null?void 0:Qe.sendButtonLabel)!=null?G:"Send",T?w.style.color=T:w.classList.add("persona-text-white");if(u.borderWidth&&(w.style.borderWidth=u.borderWidth,w.style.borderStyle="solid"),u.borderColor&&(w.style.borderColor=u.borderColor),u.paddingX?(w.style.paddingLeft=u.paddingX,w.style.paddingRight=u.paddingX):(w.style.paddingLeft="",w.style.paddingRight=""),u.paddingY?(w.style.paddingTop=u.paddingY,w.style.paddingBottom=u.paddingY):(w.style.paddingTop="",w.style.paddingBottom=""),b&&x){let _=h("div","persona-send-button-tooltip");_.textContent=x,F.appendChild(_)}F.appendChild(w);let P=(Y=r==null?void 0:r.voiceRecognition)!=null?Y:{},W=P.enabled===!0,R=null,U=null,ve=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),le=((tt=P.provider)==null?void 0:tt.type)==="runtype";if(W&&(ve||le)){U=h("div","persona-send-button-wrapper"),R=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),R.type="button",R.setAttribute("data-persona-composer-mic",""),R.setAttribute("aria-label","Start voice recognition");let _=(Ne=P.iconName)!=null?Ne:"mic",be=(je=P.iconSize)!=null?je:S,xe=parseFloat(be)||24,Ae=(Mt=P.backgroundColor)!=null?Mt:v,Ee=(qt=P.iconColor)!=null?qt:T;R.style.width=be,R.style.height=be,R.style.minWidth=be,R.style.minHeight=be,R.style.fontSize="18px",R.style.lineHeight="1";let st=Ee||"currentColor",Be=me(_,xe,st,1.5);Be?(R.appendChild(Be),R.style.color=st):(R.textContent="\u{1F3A4}",R.style.color=st),Ae?R.style.backgroundColor=Ae:R.classList.add("persona-bg-persona-primary"),Ee?R.style.color=Ee:!Ee&&!T&&R.classList.add("persona-text-white"),P.borderWidth&&(R.style.borderWidth=P.borderWidth,R.style.borderStyle="solid"),P.borderColor&&(R.style.borderColor=P.borderColor),P.paddingX&&(R.style.paddingLeft=P.paddingX,R.style.paddingRight=P.paddingX),P.paddingY&&(R.style.paddingTop=P.paddingY,R.style.paddingBottom=P.paddingY),U.appendChild(R);let We=(ue=P.tooltipText)!=null?ue:"Start voice recognition";if(((Ye=P.showTooltip)!=null?Ye:!1)&&We){let pe=h("div","persona-send-button-tooltip");pe.textContent=We,U.appendChild(pe)}}let ee=(ke=r==null?void 0:r.attachments)!=null?ke:{},Ce=ee.enabled===!0,we=null,ye=null,ce=null,Q=null;if(Ce){Q=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Q.style.display="none",ce=h("input"),ce.type="file",ce.accept=((ot=ee.allowedTypes)!=null?ot:Hn).join(","),ce.multiple=((Ve=ee.maxFiles)!=null?Ve:4)>1,ce.style.display="none",ce.setAttribute("aria-label","Attach files"),ye=h("div","persona-send-button-wrapper"),we=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),we.type="button",we.setAttribute("aria-label",(nt=ee.buttonTooltipText)!=null?nt:"Attach file");let _=(Rt=ee.buttonIconName)!=null?Rt:"paperclip",be=S,xe=parseFloat(be)||40,Ae=Math.round(xe*.6);we.style.width=be,we.style.height=be,we.style.minWidth=be,we.style.minHeight=be,we.style.fontSize="18px",we.style.lineHeight="1",we.style.backgroundColor="transparent",we.style.color="var(--persona-primary, #111827)",we.style.border="none",we.style.borderRadius="6px",we.style.transition="background-color 0.15s ease",we.addEventListener("mouseenter",()=>{we.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),we.addEventListener("mouseleave",()=>{we.style.backgroundColor="transparent"});let Ee=me(_,Ae,"currentColor",1.5);Ee?we.appendChild(Ee):we.textContent="\u{1F4CE}",we.addEventListener("click",We=>{We.preventDefault(),ce==null||ce.click()}),ye.appendChild(we);let st=(Ht=ee.buttonTooltipText)!=null?Ht:"Attach file",Be=h("div","persona-send-button-tooltip");Be.textContent=st,ye.appendChild(Be)}s.addEventListener("click",_=>{_.target!==w&&_.target!==F&&_.target!==R&&_.target!==U&&_.target!==we&&_.target!==ye&&o.focus()}),Q&&(Q.style.gap="8px",s.append(Q)),ce&&s.append(ce),s.append(o);let J=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),V=h("div","persona-flex persona-items-center persona-gap-2");ye&&V.append(ye);let ne=h("div","persona-flex persona-items-center persona-gap-1");U&&ne.append(U),ne.append(F),J.append(V,ne),s.append(J);let fe=h("div","persona-mt-2 persona-text-right persona-text-xs persona-text-persona-muted");fe.setAttribute("data-persona-composer-status","");let wt=(kt=r==null?void 0:r.statusIndicator)!=null?kt:{},ut=(N=wt.visible)!=null?N:!0;return fe.style.display=ut?"":"none",fe.textContent=(X=wt.idleText)!=null?X:"Online",t.append(n,s,fe),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:w,sendButtonWrapper:F,micButton:R,micButtonWrapper:U,statusText:fe,attachmentButton:we,attachmentButtonWrapper:ye,attachmentInput:ce,attachmentPreviewsContainer:Q,actionsRow:J,leftActions:V,rightActions:ne}};var Wl=e=>{var c,u,p,f,m,x,b;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(zt(e)){let S=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),v=h("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return S.appendChild(v),{wrapper:S,panel:v}}if(!r){let S=h("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),v=h("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),T=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.width)!=null?f:"100%";return S.style.width=T,v.style.width="100%",S.appendChild(v),{wrapper:S,panel:v}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&yn[n.position]?yn[n.position]:yn["bottom-right"],o=h("div",`persona-widget-wrapper persona-fixed ${s} persona-z-50 persona-transition`),a=h("div","persona-widget-panel persona-relative persona-min-h-[320px]"),i=(b=(x=e==null?void 0:e.launcher)==null?void 0:x.width)!=null?b:e==null?void 0:e.launcherWidth,d=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=d,a.style.maxWidth=d,o.appendChild(a),{wrapper:o,panel:a}},Rl=(e,r=!0)=>{var S,v,T,F,w,P,W,R,U;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=(S=e==null?void 0:e.layout)==null?void 0:S.header,s=((v=e==null?void 0:e.layout)==null?void 0:v.showHeader)!==!1,o=n?ro(e,n,{showClose:r}):jn({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=zt(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",d=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(F=(T=e==null?void 0:e.copy)==null?void 0:T.welcomeTitle)!=null?F:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(P=(w=e==null?void 0:e.copy)==null?void 0:w.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",d.append(c,u);let p=h("div","persona-flex persona-flex-col persona-gap-3"),f=(W=e==null?void 0:e.layout)==null?void 0:W.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1?a.append(d,p):(a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3"),a.append(p));let x=oo({config:e}),b=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;return s?vr(t,o,e):(o.header.style.display="none",vr(t,o,e)),t.append(a),b||(x.footer.style.display="none"),t.append(x.footer),{container:t,body:a,messagesWrapper:p,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:u,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 hd=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},yd=320,bd=320,xd=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),vd=(e,r,t)=>{if(e.length===0)return null;try{let n=h("div","persona-flex persona-flex-col persona-gap-2");n.setAttribute("data-message-attachments","images"),r&&(n.style.marginBottom="8px");let s=0,o=!1,a=()=>{o||(o=!0,n.remove(),t==null||t())};return e.forEach((i,d)=>{var p;let c=h("img");c.alt=((p=i.alt)==null?void 0:p.trim())||`Attached image ${d+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${yd}px`,c.style.maxHeight=`${bd}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 u=!1;s+=1,c.addEventListener("error",()=>{u||(u=!0,s=Math.max(0,s-1),c.remove(),s===0&&a())}),c.addEventListener("load",()=>{u=!0}),hd(i.image)?(c.src=i.image,n.appendChild(c)):(u=!0,s=Math.max(0,s-1),c.remove())}),s===0?(a(),null):n}catch{return t==null||t(),null}},Cr=()=>{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-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-bg-persona-primary persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.animationDelay="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},Bl=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Cr};if(r){let s=r(n);if(s!==null)return s}return Cr()},Cd=(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},Hl=(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},wd=(e,r="bubble")=>{let t=["vanilla-message-bubble","persona-max-w-[85%]"];switch(r){case"flat":e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):t.push("vanilla-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":t.push("persona-text-sm","persona-leading-relaxed"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:t.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?t.push("vanilla-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):t.push("vanilla-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return t},Dl=(e,r,t)=>{var m,x,b,S,v,T;let n=(m=r.showCopy)!=null?m:!0,s=(x=r.showUpvote)!=null?x:!0,o=(b=r.showDownvote)!=null?b:!0;if(!n&&!s&&!o){let F=h("div");return F.style.display="none",F.id=`actions-${e.id}`,F.setAttribute("data-actions-for",e.id),F}let a=(S=r.visibility)!=null?S:"hover",i=(v=r.align)!=null?v:"right",d=(T=r.layout)!=null?T:"pill-inside",c={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[i],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[d],p=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);p.id=`actions-${e.id}`,p.setAttribute("data-actions-for",e.id);let f=(F,w,P)=>{let W=_t({icon:F,label:w,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",P),W};return n&&p.appendChild(f("copy","Copy message","copy")),s&&p.appendChild(f("thumbs-up","Upvote","upvote")),o&&p.appendChild(f("thumbs-down","Downvote","downvote")),p},so=(e,r,t,n,s,o)=>{var le,q,ee,Ce,we,ye,ce;let a=t!=null?t:{},i=(le=a.layout)!=null?le:"bubble",d=a.avatar,c=a.timestamp,u=(q=d==null?void 0:d.show)!=null?q:!1,p=(ee=c==null?void 0:c.show)!=null?ee:!1,f=(Ce=d==null?void 0:d.position)!=null?Ce:"left",m=(we=c==null?void 0:c.position)!=null?we:"below",x=wd(e.role,i),b=h("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let S=xd(e),v=(ce=(ye=e.content)==null?void 0:ye.trim())!=null?ce:"",F=S.length>0&&v===Wo,w=document.createElement("div");w.classList.add("persona-message-content");let P=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),W=null;if(F?(W=document.createElement("div"),W.innerHTML=P,W.style.display="none",w.appendChild(W)):w.innerHTML=P,p&&m==="inline"&&e.createdAt){let Q=Hl(e,c);Q.classList.add("persona-ml-2","persona-inline"),w.appendChild(Q)}if(S.length>0){let Q=vd(S,!F&&!!v,()=>{F&&W&&(W.style.display="")});Q?b.appendChild(Q):F&&W&&(W.style.display="")}if(b.appendChild(w),p&&m==="below"&&e.createdAt){let Q=Hl(e,c);Q.classList.add("persona-mt-1"),b.appendChild(Q)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Q=Bl("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Q&&b.appendChild(Q)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Q=Dl(e,n,s);b.appendChild(Q)}if(!u||e.role==="system")return b;let U=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=Cd(d,e.role);return f==="right"||f==="left"&&e.role==="user"?U.append(b,ve):U.append(ve,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),U},Sd=(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}):so(e,r,t,n,s,o)};var wr=new Set,Nl=(e,r)=>{let t=wr.has(e),n=r.querySelector('button[data-expand-header="true"]'),s=r.querySelector(".persona-border-t");if(!n||!s)return;n.setAttribute("aria-expanded",t?"true":"false");let o=n.querySelector(".persona-ml-auto"),a=o==null?void 0:o.querySelector(":scope > .persona-flex.persona-items-center");if(a){a.innerHTML="";let d=me(t?"chevron-up":"chevron-down",16,"currentColor",2);d?a.appendChild(d):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},ys=e=>{let r=e.reasoning,t=h("div",["vanilla-message-bubble","vanilla-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(t.id=`bubble-${e.id}`,t.setAttribute("data-message-id",e.id),!r)return t;let n=wr.has(e.id),s=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");s.type="button",s.setAttribute("aria-expanded",n?"true":"false"),s.setAttribute("data-expand-header","true"),s.setAttribute("data-bubble-type","reasoning");let o=h("div","persona-flex persona-flex-col persona-text-left"),a=h("span","persona-text-xs persona-text-persona-primary");a.textContent="Thinking...",o.appendChild(a);let i=h("span","persona-text-xs persona-text-persona-primary");i.textContent=cl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let d=h("div","persona-flex persona-items-center"),u=me(n?"chevron-up":"chevron-down",16,"currentColor",2);u?d.appendChild(u):d.textContent=n?"Hide":"Show";let p=h("div","persona-flex persona-items-center persona-ml-auto");p.append(d),s.append(o,p);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),x=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return x.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(x),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),d.innerHTML="";let v=me(n?"chevron-up":"chevron-down",16,"currentColor",2);v?d.appendChild(v):d.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Sr=new Set,Ol=(e,r,t)=>{var c;let n=Sr.has(e),s=(c=t==null?void 0:t.toolCall)!=null?c:{},o=r.querySelector('button[data-expand-header="true"]'),a=r.querySelector(".persona-border-t");if(!o||!a)return;o.setAttribute("aria-expanded",n?"true":"false");let i=o.querySelector(".persona-ml-auto"),d=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(d){d.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",p=me(n?"chevron-up":"chevron-down",16,u,2);p?d.appendChild(p):d.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},bs=(e,r)=>{var b;let t=e.toolCall,n=(b=r==null?void 0:r.toolCall)!=null?b:{},s=h("div",["vanilla-message-bubble","vanilla-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(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=Sr.has(e.id),a=h("button","persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none");a.type="button",a.setAttribute("aria-expanded",o?"true":"false"),a.setAttribute("data-expand-header","true"),a.setAttribute("data-bubble-type","tool"),n.headerBackgroundColor&&(a.style.backgroundColor=n.headerBackgroundColor),n.headerPaddingX&&(a.style.paddingLeft=n.headerPaddingX,a.style.paddingRight=n.headerPaddingX),n.headerPaddingY&&(a.style.paddingTop=n.headerPaddingY,a.style.paddingBottom=n.headerPaddingY);let i=h("div","persona-flex persona-flex-col persona-text-left"),d=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(d.style.color=n.headerTextColor),d.textContent=dl(t),i.appendChild(d);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",p=me(o?"chevron-up":"chevron-down",16,u,2);p?c.appendChild(p):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let S=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?S.style.color=n.contentTextColor:n.headerTextColor&&(S.style.color=n.headerTextColor),S.textContent=t.name,m.appendChild(S)}if(t.args!==void 0){let S=h("div","persona-space-y-1"),v=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(v.style.color=n.labelTextColor),v.textContent="Arguments";let T=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");T.style.fontSize="0.75rem",T.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(T.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(T.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(T.style.color=n.codeBlockTextColor),T.textContent=Yr(t.args),S.append(v,T),m.appendChild(S)}if(t.chunks&&t.chunks.length){let S=h("div","persona-space-y-1"),v=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(v.style.color=n.labelTextColor),v.textContent="Activity";let T=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");T.style.fontSize="0.75rem",T.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(T.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(T.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(T.style.color=n.codeBlockTextColor),T.textContent=t.chunks.join(`
16
+ `),S.append(v,T),m.appendChild(S)}if(t.status==="complete"&&t.result!==void 0){let S=h("div","persona-space-y-1"),v=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(v.style.color=n.labelTextColor),v.textContent="Result";let T=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");T.style.fontSize="0.75rem",T.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(T.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(T.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(T.style.color=n.codeBlockTextColor),T.textContent=Yr(t.result),S.append(v,T),m.appendChild(S)}if(t.status==="complete"&&typeof t.duration=="number"){let S=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(S.style.color=n.contentTextColor),S.textContent=`Duration: ${t.duration}ms`,m.appendChild(S)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let S=n.toggleTextColor||n.headerTextColor||"currentColor",v=me(o?"chevron-up":"chevron-down",16,S,2);v?c.appendChild(v):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var xs=(e,r)=>{var b,S,v,T,F,w,P,W,R,U,ve,le;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-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=(b=n==null?void 0:n.backgroundColor)!=null?b:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(S=n==null?void 0:n.borderColor)!=null?S:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=t.status==="denied"?"shield-x":t.status==="timeout"?"shield-alert":"shield-check",c=t.status==="approved"?"var(--persona-feedback-success, #16a34a)":t.status==="denied"?"var(--persona-feedback-error, #dc2626)":t.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(v=n==null?void 0:n.titleColor)!=null?v:"currentColor",u=me(d,20,c,2);u&&i.appendChild(u);let p=h("div","persona-flex-1 persona-min-w-0"),f=h("div","persona-flex persona-items-center persona-gap-2"),m=h("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(n!=null&&n.titleColor&&(m.style.color=n.titleColor),m.textContent=(T=n==null?void 0:n.title)!=null?T:"Approval Required",f.appendChild(m),!s){let q=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");q.setAttribute("data-approval-status",t.status),t.status==="approved"?(q.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",q.style.color="var(--persona-palette-colors-success-700, #15803d)",q.textContent="Approved"):t.status==="denied"?(q.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",q.style.color="var(--persona-palette-colors-error-700, #b91c1c)",q.textContent="Denied"):t.status==="timeout"&&(q.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",q.style.color="var(--persona-palette-colors-warning-700, #b45309)",q.textContent="Timeout"),f.appendChild(q)}p.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,p.appendChild(x),t.parameters){let q=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&&(q.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(q.style.color=n.parameterTextColor),q.style.fontSize="0.75rem",q.style.lineHeight="1rem",q.textContent=Yr(t.parameters),p.appendChild(q)}if(s){let q=h("div","persona-flex persona-gap-2 persona-mt-2");q.setAttribute("data-approval-buttons","true");let ee=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");ee.type="button",ee.style.backgroundColor=(F=n==null?void 0:n.approveButtonColor)!=null?F:"var(--persona-approval-approve-bg, #22c55e)",ee.style.color=(w=n==null?void 0:n.approveButtonTextColor)!=null?w:"#ffffff",ee.setAttribute("data-approval-action","approve");let Ce=me("shield-check",14,(P=n==null?void 0:n.approveButtonTextColor)!=null?P:"#ffffff",2);Ce&&(Ce.style.marginRight="4px",ee.appendChild(Ce));let we=document.createTextNode((W=n==null?void 0:n.approveLabel)!=null?W:"Approve");ee.appendChild(we);let ye=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");ye.type="button",ye.style.backgroundColor=(R=n==null?void 0:n.denyButtonColor)!=null?R:"transparent",ye.style.color=(U=n==null?void 0:n.denyButtonTextColor)!=null?U:"var(--persona-feedback-error, #dc2626)",ye.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ye.setAttribute("data-approval-action","deny");let ce=me("shield-x",14,(ve=n==null?void 0:n.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);ce&&(ce.style.marginRight="4px",ye.appendChild(ce));let Q=document.createTextNode((le=n==null?void 0:n.denyLabel)!=null?le:"Deny");ye.appendChild(Q),q.append(ee,ye),p.appendChild(q)}return a.append(i,p),o.appendChild(a),o};var Fl=e=>{let r=[];return{buttons:r,render:(n,s,o,a,i)=>{if(e.innerHTML="",r.length=0,!n||!n.length||(a!=null?a:s?s.getMessages():[]).some(m=>m.role==="user"))return;let u=document.createDocumentFragment(),p=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let 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-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");x.type="button",x.textContent=m,x.disabled=p,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(m))}),u.appendChild(x),r.push(x)}),e.appendChild(u)}}};var ao=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 io=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 Ar(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Ad={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #dbeafe)",text:"var(--persona-palette-colors-primary-700, #1e40af)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Ed={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Td=["flowName","stepName","reasoningText","text","name","tool","toolName"],Md=100;function kd(e,r){let t={...Ad,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Ed}function Ld(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function Pd(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 Id(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 Wd(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 Rd(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 Hd(e,r,t){let n,s;try{s=JSON.parse(e.payload),n=JSON.stringify(s,null,2)}catch{s=e.payload,n=e.payload}let o=r.find(i=>i.renderEventStreamPayload);if(o!=null&&o.renderEventStreamPayload&&t){let i=o.renderEventStreamPayload({event:e,config:t,defaultRenderer:()=>a(),parsedPayload:s});if(i)return i}return a();function a(){let i=h("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=n,i.appendChild(d),i}}function vs(e,r,t,n,s,o,a,i){var f;let d=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ar(c,(f=n.classNames)==null?void 0:f.eventRow);let u=a.find(m=>m.renderEventStreamRow);if(u!=null&&u.renderEventStreamRow&&i){let m=u.renderEventStreamRow({event:e,index:r,config:i,defaultRenderer:()=>p(),isExpanded:d,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(p()),c;function p(){var ee,Ce;let m=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 b=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),S=me(d?"chevron-down":"chevron-right","14px","currentColor",2);S&&b.appendChild(S);let v=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),T=(ee=n.timestampFormat)!=null?ee:"relative";v.textContent=T==="relative"?Ld(e.timestamp,t):Pd(e.timestamp);let F=null;n.showSequenceNumbers!==!1&&(F=h("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),F.textContent=String(r+1));let w=kd(e.type,n.badgeColors),P=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");P.style.backgroundColor=w.bg,P.style.color=w.text,P.style.borderColor=w.text+"50",P.textContent=e.type;let W=(Ce=n.descriptionFields)!=null?Ce:Td,R=Id(e.payload,W),U=null;R&&(U=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=R);let ve=h("div","persona-flex-1 persona-min-w-0"),le=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"),q=me("clipboard","12px","currentColor",1.5);return q&&le.appendChild(q),le.addEventListener("click",async we=>{we.stopPropagation(),await Wd(Rd(e)),le.innerHTML="";let ye=me("check","12px","currentColor",1.5);ye&&le.appendChild(ye),setTimeout(()=>{le.innerHTML="";let ce=me("clipboard","12px","currentColor",1.5);ce&&le.appendChild(ce)},1500)}),x.appendChild(b),x.appendChild(v),F&&x.appendChild(F),x.appendChild(P),U&&x.appendChild(U),x.appendChild(ve),x.appendChild(le),m.appendChild(x),d&&m.appendChild(Hd(e,a,i)),m}}function $l(e){var c,u;let{buffer:r,getFullHistory:t,onClose:n,config:s,plugins:o=[]}=e,a=(u=(c=s==null?void 0:s.features)==null?void 0:c.eventStream)!=null?u:{},i=o.find(p=>p.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let p=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>d().element,onClose:n});if(p)return{element:p,update:()=>{},destroy:()=>{}}}return d();function d(){let p=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ar(f,p==null?void 0:p.panel);let m=[],x="",b="",S=null,v=[],T={},F=0,w=!1,P=0,W=0,R=!1,U=null,ve=!1,le=0,q=new Set,ee=new Map,Ce="",we="",ye=null,ce,Q,J,V,ne;function fe(){let X=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),_=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");Ar(_,p==null?void 0:p.headerBar);let be=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");be.textContent="Events",ce=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"),ce.textContent="0";let xe=h("div","persona-flex-1");Q=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 Ae=h("option","");Ae.value="",Ae.textContent="All events",Q.appendChild(Ae),J=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"),J.type="button",J.title="Copy All";let st=me("clipboard-copy","12px","currentColor",1.5);st&&J.appendChild(st);let Be=h("span","persona-text-xs");Be.textContent="Copy All",J.appendChild(Be),_.appendChild(be),_.appendChild(ce),_.appendChild(xe),_.appendChild(Q),_.appendChild(J);let We=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ar(We,p==null?void 0:p.searchBar);let ze=me("search","14px","var(--persona-muted, #9ca3af)",1.5),pe=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");ze&&pe.appendChild(ze),V=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"),Ar(V,p==null?void 0:p.searchInput),V.type="text",V.placeholder="Search event payloads...",ne=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"),ne.type="button",ne.style.display="none";let Ft=me("x","12px","currentColor",2);return Ft&&ne.appendChild(Ft),We.appendChild(pe),We.appendChild(V),We.appendChild(ne),X.appendChild(_),X.appendChild(We),X}let wt,ut=o.find(X=>X.renderEventStreamToolbar);if(ut!=null&&ut.renderEventStreamToolbar&&s){let X=ut.renderEventStreamToolbar({config:s,defaultRenderer:()=>fe(),eventCount:r.getSize(),filteredCount:0,onFilterChange:_=>{x=_,Y(),je()},onSearchChange:_=>{b=_,Y(),je()}});wt=X!=null?X:fe()}else wt=fe();let gt=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");gt.style.display="none";let Tt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),se=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");se.style.height="100%";let re=h("div","persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-bg-persona-accent persona-text-white persona-text-xs persona-px-3 persona-py-1.5 persona-rounded-full persona-cursor-pointer persona-shadow-md persona-z-10 persona-flex persona-items-center persona-gap-1");Ar(re,p==null?void 0:p.scrollIndicator),re.style.display="none";let Ue=me("arrow-down","12px","currentColor",2);Ue&&re.appendChild(Ue);let z=h("span","");re.appendChild(z);let te=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");te.style.display="none",Tt.appendChild(se),Tt.appendChild(te),Tt.appendChild(re),f.setAttribute("tabindex","0"),f.appendChild(wt),f.appendChild(gt),f.appendChild(Tt);function de(){let X=r.getAll(),_={};for(let Be of X)_[Be.type]=(_[Be.type]||0)+1;let be=Object.keys(_).sort(),xe=be.length!==v.length||!be.every((Be,We)=>Be===v[We]),Ae=!xe&&be.some(Be=>_[Be]!==T[Be]),Ee=X.length!==Object.values(T).reduce((Be,We)=>Be+We,0);if(!xe&&!Ae&&!Ee||(v=be,T=_,!Q))return;let st=Q.value;if(Q.options[0].textContent="All events",xe){for(;Q.options.length>1;)Q.remove(1);for(let Be of be){let We=h("option","");We.value=Be,We.textContent=`${Be} (${_[Be]||0})`,Q.appendChild(We)}st&&be.includes(st)?Q.value=st:st&&(Q.value="",x="")}else for(let Be=1;Be<Q.options.length;Be++){let We=Q.options[Be];We.textContent=`${We.value} (${_[We.value]||0})`}}function Qe(){let X=r.getAll();if(x&&(X=X.filter(_=>_.type===x)),b){let _=b.toLowerCase();X=X.filter(be=>be.type.toLowerCase().includes(_)||be.payload.toLowerCase().includes(_))}return X}function G(){return x!==""||b!==""}function Y(){F=0,P=0,w=!1,re.style.display="none"}function tt(X){q.has(X)?q.delete(X):q.add(X),ye=X;let _=se.scrollTop,be=w;ve=!0,w=!0,je(),se.scrollTop=_,w=be,ve=!1}function Ne(){return se.scrollHeight-se.scrollTop-se.clientHeight<=50}function je(){W=Date.now(),R=!1,de();let X=r.getEvictedCount();X>0?(gt.textContent=`${X.toLocaleString()} older events truncated`,gt.style.display=""):gt.style.display="none",m=Qe();let _=m.length,be=r.getSize()>0;ce&&(ce.textContent=String(r.getSize())),_===0&&be&&G()?(te.textContent=b?`No events matching '${b}'`:"No events matching filter",te.style.display="",se.style.display="none"):(te.style.display="none",se.style.display=""),J&&(J.title=G()?`Copy Filtered (${_})`:"Copy All"),w&&_>F&&(P+=_-F,z.textContent=`${P} new event${P===1?"":"s"}`,re.style.display=""),F=_;let xe=r.getAll(),Ae=xe.length>0?xe[0].timestamp:0,Ee=new Set(m.map(We=>We.id));for(let We of q)Ee.has(We)||q.delete(We);let st=x!==Ce||b!==we,Be=ee.size===0&&m.length>0;if(st||Be||m.length===0){se.innerHTML="",ee.clear();let We=document.createDocumentFragment();for(let ze=0;ze<m.length;ze++){let pe=vs(m[ze],ze,Ae,a,q,tt,o,s);ee.set(m[ze].id,pe),We.appendChild(pe)}se.appendChild(We),Ce=x,we=b,ye=null}else{if(ye!==null){let ze=ee.get(ye);if(ze&&ze.parentNode===se){let pe=m.findIndex(Ft=>Ft.id===ye);if(pe>=0){let Ft=vs(m[pe],pe,Ae,a,q,tt,o,s);se.insertBefore(Ft,ze),ze.remove(),ee.set(ye,Ft)}}ye=null}let We=new Set(m.map(ze=>ze.id));for(let[ze,pe]of ee)We.has(ze)||(pe.remove(),ee.delete(ze));for(let ze=0;ze<m.length;ze++){let pe=m[ze];if(!ee.has(pe.id)){let Ft=vs(pe,ze,Ae,a,q,tt,o,s);ee.set(pe.id,Ft),se.appendChild(Ft)}}}w||(se.scrollTop=se.scrollHeight)}function Mt(){if(Date.now()-W>=Md){U!==null&&(cancelAnimationFrame(U),U=null),je();return}R||(R=!0,U=requestAnimationFrame(()=>{U=null,je()}))}let qt=(X,_)=>{if(!J)return;J.innerHTML="";let be=me(X,"12px","currentColor",1.5);be&&J.appendChild(be);let xe=h("span","persona-text-xs");xe.textContent="Copy All",J.appendChild(xe),setTimeout(()=>{J.innerHTML="";let Ae=me("clipboard-copy","12px","currentColor",1.5);Ae&&J.appendChild(Ae);let Ee=h("span","persona-text-xs");Ee.textContent="Copy All",J.appendChild(Ee),J.disabled=!1},_)},ue=async()=>{if(J){J.disabled=!0;try{let X;G()?X=m:t?(X=await t(),X.length===0&&(X=r.getAll())):X=r.getAll();let _=X.map(be=>{try{return JSON.parse(be.payload)}catch{return be.payload}});await navigator.clipboard.writeText(JSON.stringify(_,null,2)),qt("check",1500)}catch{qt("x",1500)}}},Ye=()=>{Q&&(x=Q.value,Y(),je())},ke=()=>{!V||!ne||(ne.style.display=V.value?"":"none",S&&clearTimeout(S),S=setTimeout(()=>{b=V.value,Y(),je()},150))},ot=()=>{!V||!ne||(V.value="",b="",ne.style.display="none",S&&clearTimeout(S),Y(),je())},Ve=()=>{if(ve)return;let X=se.scrollTop,_=X>le;le=X,Ne()&&_?(w=!1,P=0,re.style.display="none"):Ne()||(w=!0)},nt=X=>{X.deltaY<0&&(w=!0)},Rt=()=>{se.scrollTop=se.scrollHeight,w=!1,P=0,re.style.display="none"},Ht=X=>{let _=X.target;if(!_||_.closest("button"))return;let be=_.closest("[data-event-id]");if(!be)return;let xe=be.getAttribute("data-event-id");xe&&tt(xe)},kt=X=>{if((X.metaKey||X.ctrlKey)&&X.key==="f"){X.preventDefault(),V==null||V.focus(),V==null||V.select();return}X.key==="Escape"&&(V&&document.activeElement===V?(ot(),V.blur(),f.focus()):n&&n())};J&&J.addEventListener("click",ue),Q&&Q.addEventListener("change",Ye),V&&V.addEventListener("input",ke),ne&&ne.addEventListener("click",ot),se.addEventListener("scroll",Ve),se.addEventListener("wheel",nt,{passive:!0}),se.addEventListener("click",Ht),re.addEventListener("click",Rt),f.addEventListener("keydown",kt);function N(){S&&clearTimeout(S),U!==null&&(cancelAnimationFrame(U),U=null),R=!1,ee.clear(),J&&J.removeEventListener("click",ue),Q&&Q.removeEventListener("change",Ye),V&&V.removeEventListener("input",ke),ne&&ne.removeEventListener("click",ot),se.removeEventListener("scroll",Ve),se.removeEventListener("wheel",nt),se.removeEventListener("click",Ht),re.removeEventListener("click",Rt),f.removeEventListener("keydown",kt)}return{element:f,update:Mt,destroy:N}}}function _l(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-bg, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${t} in artifact panel`),n&&i.setAttribute("data-open-artifact",n);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let c=document.createElement("div");c.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let u=document.createElement("div");u.className="persona-truncate persona-text-sm persona-font-medium",u.style.color="var(--persona-text, #1f2937)",u.textContent=t;let p=document.createElement("div");if(p.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",p.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, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",p.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,p.appendChild(m)}else p.textContent=a;if(c.append(u,p),i.append(d,c),s==="complete"){let f=document.createElement("button");f.type="button",f.textContent="Download",f.title=`Download ${t}`,f.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",f.style.border="1px solid var(--persona-border, #e5e7eb)",f.style.color="var(--persona-text, #1f2937)",f.style.backgroundColor="transparent",f.style.cursor="pointer",f.setAttribute("data-download-artifact",n),i.append(f)}return i}var jl=(e,r)=>{var n,s,o;let t=(o=(s=(n=r==null?void 0:r.config)==null?void 0:n.features)==null?void 0:s.artifacts)==null?void 0:o.renderCard;if(t){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:d},config:r.config,defaultRenderer:()=>_l(e,r)});if(u)return u}return _l(e,r)};var Cs=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)})}},zn=new Cs;zn.register("PersonaArtifactCard",jl);function Bd(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 zl(e,r){var Tt,se,re,Ue;let t=(se=(Tt=e.features)==null?void 0:Tt.artifacts)==null?void 0:se.layout,s=((re=t==null?void 0:t.toolbarPreset)!=null?re:"default")==="document",o=(Ue=t==null?void 0:t.panePadding)==null?void 0:Ue.trim(),a=e.markdown?fr(e.markdown):null,i=Kr(e.sanitize),d=z=>{let te=a?a(z):Jr(z);return i?i(te):te},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,u=()=>{c==null||c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"),q==null||q.hide()};c&&c.addEventListener("click",()=>{var z;u(),(z=r.onDismiss)==null||z.call(r)});let p=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");p.setAttribute("data-persona-theme-zone","artifact-pane"),s&&p.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let 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;u(),(z=r.onDismiss)==null||z.call(r)});let b="rendered",S=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),v=s?_t({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):_t({icon:"eye",label:"Rendered view"}),T=s?_t({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):_t({icon:"code-2",label:"Source"}),F=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),w=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,P=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,W=t==null?void 0:t.documentToolbarCopyMenuItems,R=!!(P&&W&&W.length>0),U=null,ve,le=null,q=null;if(s&&(w||P)&&!R){if(ve=w?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let z=me("chevron-down",14,"currentColor",2);z&&ve.appendChild(z)}}else s&&R?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ve=w?_o({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),le=_t({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"}}),U.append(ve,le)):s?ve=_t({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ve=_t({icon:"copy",label:"Copy"});let ee=s?_t({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):_t({icon:"refresh-cw",label:"Refresh"}),Ce=s?_t({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):_t({icon:"x",label:"Close"}),we=()=>{var G,Y,tt;let z=(G=ne.find(Ne=>Ne.id===fe))!=null?G:ne[ne.length-1],te=(Y=z==null?void 0:z.id)!=null?Y:null,de=(z==null?void 0:z.artifactType)==="markdown"&&(tt=z.markdown)!=null?tt:"",Qe=z?JSON.stringify({component:z.component,props:z.props},null,2):"";return{markdown:de,jsonPayload:Qe,id:te}},ye=async()=>{var G;let{markdown:z,jsonPayload:te}=we(),de=(G=ne.find(Y=>Y.id===fe))!=null?G:ne[ne.length-1],Qe=(de==null?void 0:de.artifactType)==="markdown"?z:de?te:"";try{await navigator.clipboard.writeText(Qe)}catch{}};if(ve.addEventListener("click",async()=>{let z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(z&&R){let{markdown:te,jsonPayload:de,id:Qe}=we();try{await z({actionId:"primary",artifactId:Qe,markdown:te,jsonPayload:de})}catch{}return}await ye()}),le&&(W!=null&&W.length)){let z=()=>{var de;return(de=p.closest("[data-persona-root]"))!=null?de:document.body},te=()=>{q=sr({items:W.map(de=>({id:de.id,label:de.label})),onSelect:async de=>{let{markdown:Qe,jsonPayload:G,id:Y}=we(),tt=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{tt?await tt({actionId:de,artifactId:Y,markdown:Qe,jsonPayload:G}):de==="markdown"||de==="md"?await navigator.clipboard.writeText(Qe):de==="json"||de==="source"?await navigator.clipboard.writeText(G):await navigator.clipboard.writeText(Qe||G)}catch{}},anchor:U!=null?U:le,position:"bottom-right",portal:z()})};p.isConnected?te():requestAnimationFrame(te),le.addEventListener("click",de=>{de.stopPropagation(),q==null||q.toggle()})}ee.addEventListener("click",async()=>{var z;try{await((z=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:z.call(t))}catch{}ut()}),Ce.addEventListener("click",()=>{var z;u(),(z=r.onDismiss)==null||z.call(r)});let ce=()=>{s&&(v.setAttribute("aria-pressed",b==="rendered"?"true":"false"),T.setAttribute("aria-pressed",b==="source"?"true":"false"))};v.addEventListener("click",()=>{b="rendered",ce(),ut()}),T.addEventListener("click",()=>{b="source",ce(),ut()});let Q=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(),S.append(v,T),U?F.append(U,ee,Ce):F.append(ve,ee,Ce),f.append(S,Q,F),ce()):(f.appendChild(m),f.appendChild(x)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let J=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"),V=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(J.style.paddingLeft=o,J.style.paddingRight=o,V.style.padding=o),p.appendChild(f),p.appendChild(J),p.appendChild(V);let ne=[],fe=null,wt=!1,ut=()=>{var Qe,G,Y,tt;let z=s&&ne.length<=1;J.classList.toggle("persona-hidden",z),J.replaceChildren();for(let Ne of ne){let je=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");je.type="button",je.textContent=Ne.title||Ne.id.slice(0,8),Ne.id===fe&&je.classList.add("persona-bg-persona-container","persona-border-persona-border"),je.addEventListener("click",()=>r.onSelect(Ne.id)),J.appendChild(je)}V.replaceChildren();let te=fe&&ne.find(Ne=>Ne.id===fe)||ne[ne.length-1];if(!te)return;if(s){let Ne=te.artifactType==="markdown"?"MD":(Qe=te.component)!=null?Qe:"Component",Mt=(te.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Q.textContent=`${Mt} \xB7 ${Ne}`}else m.textContent="Artifacts";if(te.artifactType==="markdown"){if(s&&b==="source"){let je=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");je.textContent=(G=te.markdown)!=null?G:"",V.appendChild(je);return}let Ne=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ne.innerHTML=d((Y=te.markdown)!=null?Y:""),V.appendChild(Ne);return}let de=te.component?zn.get(te.component):void 0;if(de){let je={message:{id:te.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Mt=de((tt=te.props)!=null?tt:{},je);if(Mt){V.appendChild(Mt);return}}catch{}}V.appendChild(Bd(te))},gt=()=>{var te;let z=ne.length>0;if(p.classList.toggle("persona-hidden",!z),c){let de=typeof p.closest=="function"?p.closest("[data-persona-root]"):null,G=((te=de==null?void 0:de.classList.contains("persona-artifact-narrow-host"))!=null?te:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;z&&G&&wt?(c.classList.remove("persona-hidden"),p.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open"))}};return{element:p,backdrop:c,update(z){var te,de,Qe;ne=z.artifacts,fe=(Qe=(de=z.selectedId)!=null?de:(te=z.artifacts[z.artifacts.length-1])==null?void 0:te.id)!=null?Qe:null,ne.length>0&&(wt=!0),ut(),gt()},setMobileOpen(z){wt=z,!z&&c?(c.classList.add("persona-hidden"),p.classList.remove("persona-artifact-drawer-open")):gt()}}}function pn(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 ql(e,r){var o,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!pn(r))return;let t=(a=(o=r.features)==null?void 0:o.artifacts)==null?void 0:a.layout,n=(i=t==null?void 0:t.paneBorder)==null?void 0:i.trim(),s=(d=t==null?void 0:t.paneBorderLeft)==null?void 0:d.trim();n?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",n)):s&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",s))}function Dd(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 jo(e,r){var d,c,u,p,f,m,x,b,S,v;if(!pn(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"),Dd(e),ql(e,r);return}let t=(c=(d=r.features)==null?void 0:d.artifacts)==null?void 0:c.layout;e.style.setProperty("--persona-artifact-split-gap",(u=t==null?void 0:t.splitGap)!=null?u:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(p=t==null?void 0:t.paneWidth)!=null?p:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(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=(b=t==null?void 0:t.documentToolbarIconColor)==null?void 0:b.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(S=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:S.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(v=t==null?void 0:t.documentToolbarToggleActiveBorderColor)==null?void 0:v.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),ql(e,r)}var Ul=["panel","seamless"];function zo(e,r){var i,d,c,u,p,f;for(let m of Ul)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!pn(r))return;let t=(d=(i=r.features)==null?void 0:i.artifacts)==null?void 0:d.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Ul.includes(n)?n:"panel";e.classList.add(`persona-artifact-appearance-${s}`);let o=(u=t==null?void 0:t.paneBorderRadius)==null?void 0:u.trim();o&&e.style.setProperty("--persona-artifact-pane-radius",o);let a=(p=t==null?void 0:t.paneShadow)==null?void 0:p.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Vl(e,r){var t,n,s;return!r||!pn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Nd(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 Od(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 Fd(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function $d(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Jl(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 Kl(e,r,t,n,s,o){let a=Nd(s,200),i=$d(r,t,n,200);i=Math.max(a,i);let d=Od(o);return d!==null&&(i=Math.min(i,d)),Fd(e,a,i)}var Yl={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"}},ws=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var x,b,S;if(o.dataset.enhanced==="true")return;let a=(x=o.dataset.tvForm)!=null?x:"init";o.dataset.enhanced="true";let i=(b=Yl[a])!=null?b:Yl.init;o.classList.add("persona-form-card","persona-space-y-4");let d=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,d.appendChild(c),i.description){let v=h("p","persona-text-sm persona-text-persona-muted");v.textContent=i.description,d.appendChild(v)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(v=>{var W,R;let T=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");T.htmlFor=`${r.id}-${a}-${v.name}`;let F=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=v.label,T.appendChild(F);let w=(W=v.type)!=null?W:"text",P;w==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=w),P.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",P.id=`${r.id}-${a}-${v.name}`,P.name=v.name,P.placeholder=(R=v.placeholder)!=null?R:"",v.required&&(P.required=!0),T.appendChild(P),u.appendChild(T)});let p=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(S=i.submitLabel)!=null?S:"Submit",p.appendChild(f),p.appendChild(m),u.appendChild(p),o.replaceChildren(d,u),u.addEventListener("submit",async v=>{var P,W;v.preventDefault();let T=(P=t.formEndpoint)!=null?P:"/form",F=new FormData(u),w={};F.forEach((R,U)=>{w[U]=R}),w.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let R=await fetch(T,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(w)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let U=await R.json();f.textContent=(W=U.message)!=null?W:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await n.sendMessage(String(U.nextPrompt))}catch(R){f.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ss=class{constructor(){this.plugins=new Map}register(r){var t;this.plugins.has(r.id)&&console.warn(`Plugin "${r.id}" is already registered. Overwriting.`),this.plugins.set(r.id,r),(t=r.onRegister)==null||t.call(r)}unregister(r){var n;let t=this.plugins.get(r);t&&((n=t.onUnregister)==null||n.call(t),this.plugins.delete(r))}getAll(){return Array.from(this.plugins.values()).sort((r,t)=>{var n,s;return((n=t.priority)!=null?n:0)-((s=r.priority)!=null?s:0)})}getForInstance(r){let t=this.getAll();if(!r||r.length===0)return t;let n=new Set(r.map(o=>o.id));return[...t.filter(o=>!n.has(o.id)),...r].sort((o,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=o.priority)!=null?d:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},qo=new Ss;var ht={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",position:"bottom-right",width:"min(400px, calc(100vw - 24px))",heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:"#000000",callToActionIconBackgroundColor:"#ffffff",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:"1px solid #e5e7eb",shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",backgroundColor:"#111827",textColor:"#ffffff",borderColor:"#60a5fa",useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:"#111827",backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:"#ffffff",recordingBackgroundColor:"#ef4444",recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function Gl(e,r){if(!(!e&&!r))return e?r?to(e,r):e:r}function As(e){var r,t,n,s,o,a,i,d,c,u,p,f,m,x,b,S,v,T,F,w,P;return e?{...ht,...e,theme:Gl(ht.theme,e.theme),darkTheme:Gl(ht.darkTheme,e.darkTheme),launcher:{...ht.launcher,...e.launcher,dock:{...(r=ht.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=ht.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...ht.copy,...e.copy},sendButton:{...ht.sendButton,...e.sendButton},statusIndicator:{...ht.statusIndicator,...e.statusIndicator},voiceRecognition:{...ht.voiceRecognition,...e.voiceRecognition},features:(()=>{var ve,le;let W=(ve=ht.features)==null?void 0:ve.artifacts,R=(le=e.features)==null?void 0:le.artifacts,U=W===void 0&&R===void 0?void 0:{...W,...R,layout:{...W==null?void 0:W.layout,...R==null?void 0:R.layout}};return{...ht.features,...e.features,...U!==void 0?{artifacts:U}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:ht.suggestionChips,suggestionChipsConfig:{...ht.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...ht.layout,...e.layout,header:{...(a=ht.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=ht.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(p=(u=ht.layout)==null?void 0:u.messages)==null?void 0:p.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(b=(x=ht.layout)==null?void 0:x.messages)==null?void 0:b.timestamp,...(v=(S=e.layout)==null?void 0:S.messages)==null?void 0:v.timestamp}},slots:{...(T=ht.layout)==null?void 0:T.slots,...(F=e.layout)==null?void 0:F.slots}},markdown:{...ht.markdown,...e.markdown,options:{...(w=ht.markdown)==null?void 0:w.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...ht.messageActions,...e.messageActions}}:ht}var Xl=()=>{let e=new Map,r=(s,o)=>(e.has(s)||e.set(s,new Set),e.get(s).add(o),()=>t(s,o)),t=(s,o)=>{var a;(a=e.get(s))==null||a.delete(o)};return{on:r,off:t,emit:(s,o)=>{var a;(a=e.get(s))==null||a.forEach(i=>{try{i(o)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var _d=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},jd=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},Uo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=_d(e),t=jd(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}},Es=e=>typeof e=="string"?e:e==null?"":String(e),Er={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Es(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=Es(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:Es(t.text)}}},Zl=e=>Array.isArray(e)?e.map(r=>String(r)):[],Vo=e=>{let r=new Set(Zl(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(Zl(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,u)=>c||(u==null?void 0:u({text:a,message:o.message}))||null,null):null;if(!i)return null;r.add(o.message.id),n();let d={action:i,message:o.message};e.emit("action:detected",d);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",d)},p=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!p)continue;if(p.handled){let f=p.persistMessage!==!1;return{text:p.displayText!==void 0?p.displayText:"",persist:f,resubmit:p.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var zd=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}},qd=e=>e.map(r=>({...r,streaming:!1})),Ts=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?zd(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?qd(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)}}}};import{parse as Ud,STR as Vd,OBJ as Jd}from"partial-json";function Kd(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function Yd(e,r){if(!Kd(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 Ms(){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=Ud(t,Vd|Jd),o=Yd(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function Gd(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function ks(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=zn.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 Xd(){let e=Ms();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ls(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 Ps(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 Zd=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Is(e){let{onSubmit:r,onDismiss:t,title:n="How satisfied are you?",subtitle:s="Please rate your experience",commentPlaceholder:o="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:c=Zd}=e,u=document.createElement("div");u.className="persona-feedback-container persona-feedback-csat",u.setAttribute("role","dialog"),u.setAttribute("aria-label","Customer satisfaction feedback");let p=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=n,m.appendChild(x);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,m.appendChild(b),f.appendChild(m);let S=document.createElement("div");S.className="persona-feedback-rating persona-feedback-rating-csat",S.setAttribute("role","radiogroup"),S.setAttribute("aria-label","Satisfaction rating from 1 to 5");let v=[];for(let W=1;W<=5;W++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${W} star${W>1?"s":""}: ${c[W-1]}`),R.title=c[W-1],R.dataset.rating=String(W),R.innerHTML=`
17
17
  <svg class="persona-feedback-star" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
18
18
  <polygon points="12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2"></polygon>
19
19
  </svg>
20
- `,F.addEventListener("click",()=>{p=w,x.forEach((re,Y)=>{let ae=Y<w;re.classList.toggle("selected",ae),re.setAttribute("aria-checked",Y===w-1?"true":"false")})}),x.push(F),E.appendChild(F)}f.appendChild(E);let k=null;if(d){let w=document.createElement("div");w.className="persona-feedback-comment-container",k=document.createElement("textarea"),k.className="persona-feedback-comment",k.placeholder=o,k.rows=3,k.setAttribute("aria-label","Additional comments"),w.appendChild(k),f.appendChild(w)}let q=document.createElement("div");q.className="persona-feedback-actions";let M=document.createElement("button");M.type="button",M.className="persona-feedback-btn persona-feedback-btn-skip",M.textContent=i,M.addEventListener("click",()=>{t==null||t(),g.remove()});let N=document.createElement("button");return N.type="button",N.className="persona-feedback-btn persona-feedback-btn-submit",N.textContent=a,N.addEventListener("click",async()=>{if(p===null){E.classList.add("persona-feedback-shake"),setTimeout(()=>E.classList.remove("persona-feedback-shake"),500);return}N.disabled=!0,N.textContent="Submitting...";try{let w=(k==null?void 0:k.value.trim())||void 0;await n(p,w),g.remove()}catch(w){N.disabled=!1,N.textContent=a,console.error("[CSAT Feedback] Failed to submit:",w)}}),q.appendChild(M),q.appendChild(N),f.appendChild(q),g.appendChild(f),g}function Ms(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:d=!0,lowLabel:c="Not likely",highLabel:g="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let C=document.createElement("div");C.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,C.appendChild(v);let E=document.createElement("p");E.className="persona-feedback-subtitle",E.textContent=s,C.appendChild(E),m.appendChild(C);let x=document.createElement("div");x.className="persona-feedback-rating persona-feedback-rating-nps",x.setAttribute("role","radiogroup"),x.setAttribute("aria-label","Likelihood rating from 0 to 10");let k=document.createElement("div");k.className="persona-feedback-labels";let q=document.createElement("span");q.className="persona-feedback-label-low",q.textContent=c;let M=document.createElement("span");M.className="persona-feedback-label-high",M.textContent=g,k.appendChild(q),k.appendChild(M);let N=document.createElement("div");N.className="persona-feedback-numbers";let w=[];for(let z=0;z<=10;z++){let ge=document.createElement("button");ge.type="button",ge.className="persona-feedback-rating-btn persona-feedback-number-btn",ge.setAttribute("role","radio"),ge.setAttribute("aria-checked","false"),ge.setAttribute("aria-label",`Rating ${z} out of 10`),ge.textContent=String(z),ge.dataset.rating=String(z),z<=6?ge.classList.add("persona-feedback-detractor"):z<=8?ge.classList.add("persona-feedback-passive"):ge.classList.add("persona-feedback-promoter"),ge.addEventListener("click",()=>{f=z,w.forEach((Ie,Xe)=>{Ie.classList.toggle("selected",Xe===z),Ie.setAttribute("aria-checked",Xe===z?"true":"false")})}),w.push(ge),N.appendChild(ge)}x.appendChild(k),x.appendChild(N),m.appendChild(x);let F=null;if(d){let z=document.createElement("div");z.className="persona-feedback-comment-container",F=document.createElement("textarea"),F.className="persona-feedback-comment",F.placeholder=o,F.rows=3,F.setAttribute("aria-label","Additional comments"),z.appendChild(F),m.appendChild(z)}let re=document.createElement("div");re.className="persona-feedback-actions";let Y=document.createElement("button");Y.type="button",Y.className="persona-feedback-btn persona-feedback-btn-skip",Y.textContent=i,Y.addEventListener("click",()=>{t==null||t(),p.remove()});let ae=document.createElement("button");return ae.type="button",ae.className="persona-feedback-btn persona-feedback-btn-submit",ae.textContent=a,ae.addEventListener("click",async()=>{if(f===null){N.classList.add("persona-feedback-shake"),setTimeout(()=>N.classList.remove("persona-feedback-shake"),500);return}ae.disabled=!0,ae.textContent="Submitting...";try{let z=(F==null?void 0:F.value.trim())||void 0;await n(f,z),p.remove()}catch(z){ae.disabled=!1,ae.textContent=a,console.error("[NPS Feedback] Failed to submit:",z)}}),re.appendChild(Y),re.appendChild(ae),m.appendChild(re),p.appendChild(m),p}var xr="persona-chat-history",Gd=30*1e3,Xd={"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 Zd(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 d=(s=Xd[i.type])!=null?s:"png";n.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{type:i.type,lastModified:Date.now()}))}if(n.length>0)return n;for(let a of Array.from((o=e.files)!=null?o:[]))a.type.startsWith("image/")&&n.push(a);return n}function Qd(e){var n,t,r,s,o,a,i,d,c;return e?e===!0?{storage:"session",keyPrefix:"persona-",persist:{openState:!0,voiceState:!0,focusInput:!0},clearOnChatClear:!0}:{storage:(n=e.storage)!=null?n:"session",keyPrefix:(t=e.keyPrefix)!=null?t:"persona-",persist:{openState:(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:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function ep(e){try{let n=e==="local"?localStorage:sessionStorage,t="__persist_test__";return n.setItem(t,"1"),n.removeItem(t),n}catch{return null}}var ks=e=>!e||typeof e!="object"?{}:{...e},Kl=e=>e.map(n=>({...n,streaming:!1})),Yl=(e,n,t)=>{let r=e!=null&&e.markdown?lr(e.markdown):null,s=jr(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,g,p;let a=(c=o.text)!=null?c:"",i=(g=o.message.rawContent)!=null?g: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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):r?d=r(a):d=_r(a),s?s(d):d}},Ls=(e,n,t)=>{var le,Se,ot,kt,wt,Bt,Lt,st,lt,At,ct,Ft,Yt,on,Fs,$s,Ns,Os,Ds,_s,js,Vs,Us,qs,zs,Js,Ks,Ys,Gs,Xs,Zs,Qs,ea,ta,na,ra,oa,sa;e.id&&e.id!=="persona-root"&&!e.getAttribute("data-persona-instance")&&e.setAttribute("data-persona-instance",e.id),e.id="persona-root";let r=xs(n),s=Fo.getForInstance(r.plugins);r.components&&$n.registerAll(r.components);let o=zl(),a=(le=r.storageAdapter)!=null?le:Cs(),i={},d=null,c=l=>{if(r.onStateLoaded)try{return r.onStateLoaded(l)}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",u)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(u=>{let y=u!=null?u:{messages:[],metadata:{}};return c(y)});else{let u=l!=null?l:{messages:[],metadata:{}},y=c(u);y.metadata&&(i=ks(y.metadata)),(Se=y.messages)!=null&&Se.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=c({messages:[],metadata:{}});(ot=l.messages)!=null&&ot.length&&(r={...r,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let g=()=>i,p=l=>{var y;i=(y=l({...i}))!=null?y:{},Lr()},f=r.actionParsers&&r.actionParsers.length?r.actionParsers:[$o],m=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[br.message,br.messageAndClick],C=No({parsers:f,handlers:m,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null});C.syncFromMetadata();let v=(wt=(kt=r.launcher)==null?void 0:kt.enabled)!=null?wt:!0,E=(Lt=(Bt=r.launcher)==null?void 0:Bt.autoExpand)!=null?Lt:!1,x=(st=r.autoFocusInput)!=null?st:!1,k=E,q=v,M=(At=(lt=r.layout)==null?void 0:lt.header)==null?void 0:At.layout,N=!1,w=v?E:!0,F=!1,re=null,Y=()=>{F=!0,re&&clearTimeout(re),re=setTimeout(()=>{F&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),F=!1)},1e4)},ae=Yl(r,C,Y),z=(Ft=(ct=r.features)==null?void 0:ct.showReasoning)!=null?Ft:!0,ge=(on=(Yt=r.features)==null?void 0:Yt.showToolCalls)!=null?on:!0,Ie=($s=(Fs=r.features)==null?void 0:Fs.showEventStreamToggle)!=null?$s:!1,ye=`${(Os=typeof r.persistState=="object"?(Ns=r.persistState)==null?void 0:Ns.keyPrefix:void 0)!=null?Os:"persona-"}event-stream`,ee=Ie?new eo(ye):null,te=(js=(_s=(Ds=r.features)==null?void 0:Ds.eventStream)==null?void 0:_s.maxEvents)!=null?js:2e3,D=Ie?new Qr(te,ee):null,U=null,oe=!1,he=null,ht=0;ee==null||ee.open().then(()=>D==null?void 0:D.restore()).catch(l=>{r.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let at={onCopy:l=>{var u,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",S)}),(y=(u=r.messageActions)==null?void 0:u.onCopy)==null||y.call(u,l)},onFeedback:l=>{var u,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(S=>{r.debug&&console.error("[AgentWidget] Failed to submit feedback:",S)}),(y=(u=r.messageActions)==null?void 0:u.onFeedback)==null||y.call(u,l)}},ut=(Vs=r.statusIndicator)!=null?Vs:{},Wt=l=>{var u,y,S,R;return l==="idle"?(u=ut.idleText)!=null?u:Vt.idle:l==="connecting"?(y=ut.connectingText)!=null?y:Vt.connecting:l==="connected"?(S=ut.connectedText)!=null?S:Vt.connected:l==="error"?(R=ut.errorText)!=null?R:Vt.error:Vt[l]},{wrapper:de,panel:ie}=Tl(r),qe=Ml(r,v),{container:j,body:G,messagesWrapper:be,suggestions:ze,textarea:X,sendButton:K,sendButtonWrapper:tt,composerForm:We,statusText:Ve,introTitle:Tt,introSubtitle:_t,closeButton:ce,iconHolder:Je,headerTitle:Me,headerSubtitle:nt,header:je,footer:Ze,actionsRow:Rt,leftActions:Ht,rightActions:Mt}=qe,B=qe.micButton,Z=qe.micButtonWrapper,J=qe.attachmentButton,_=qe.attachmentButtonWrapper,xe=qe.attachmentInput,Le=qe.attachmentPreviewsContainer,He=null,pt=null,ve=s.find(l=>l.renderHeader);if(ve!=null&&ve.renderHeader){let l=ve.renderHeader({config:r,defaultRenderer:()=>{let u=Fn({config:r,showClose:v});return gr(j,u,r),u.header},onClose:()=>gt(!1,"user")});if(l){let u=j.querySelector(".persona-border-b-persona-divider");u&&(u.replaceWith(l),je=l)}}let Ce=()=>{var u,y,S,R;if(!D)return;if(oe=!0,!U&&D&&(U=Hl({buffer:D,getFullHistory:()=>D.getAllFromStore(),onClose:()=>Be(),config:r,plugins:s})),U&&(G.style.display="none",(u=Ze.parentNode)==null||u.insertBefore(U.element,Ze),U.update()),ue){ue.classList.remove("persona-text-persona-muted"),ue.classList.add("persona-text-persona-accent"),ue.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let L=(R=(S=(y=r.features)==null?void 0:y.eventStream)==null?void 0:S.classNames)==null?void 0:R.toggleButtonActive;L&&L.split(/\s+/).forEach(P=>P&&ue.classList.add(P))}let l=()=>{if(!oe)return;let L=Date.now();L-ht>=200&&(U==null||U.update(),ht=L),he=requestAnimationFrame(l)};ht=0,he=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},Be=()=>{var l,u,y;if(oe){if(oe=!1,U&&U.element.remove(),G.style.display="",ue){ue.classList.remove("persona-text-persona-accent"),ue.classList.add("persona-text-persona-muted"),ue.style.boxShadow="";let S=(y=(u=(l=r.features)==null?void 0:l.eventStream)==null?void 0:u.classNames)==null?void 0:y.toggleButtonActive;S&&S.split(/\s+/).forEach(R=>R&&ue.classList.remove(R))}he!==null&&(cancelAnimationFrame(he),he=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},ue=null;if(Ie){let l=(qs=(Us=r.features)==null?void 0:Us.eventStream)==null?void 0:qs.classNames,u="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");ue=h("button",u),ue.style.width="28px",ue.style.height="28px",ue.type="button",ue.setAttribute("aria-label","Event Stream"),ue.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&ue.appendChild(y);let S=qe.clearChatButtonWrapper,R=qe.closeButtonWrapper,L=S||R;L&&L.parentNode===je?je.insertBefore(ue,L):je.appendChild(ue),ue.addEventListener("click",()=>{oe?Be():Ce()})}let bt=l=>{var S,R,L;let u=r.attachments;if(!(u!=null&&u.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 P=l.querySelector("[data-persona-composer-form]");P!=null&&P.parentNode?P.parentNode.insertBefore(y,P):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let P=h("input");P.type="file",P.accept=((S=u.allowedTypes)!=null?S:kn).join(","),P.multiple=((R=u.maxFiles)!=null?R:4)>1,P.style.display="none",P.setAttribute("aria-label",(L=u.buttonTooltipText)!=null?L:"Attach files"),l.appendChild(P)}},Zt=s.find(l=>l.renderComposer);if(Zt!=null&&Zt.renderComposer){let l=r.composer,u=Zt.renderComposer({config:r,defaultRenderer:()=>Xr({config:r}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{xe==null||xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{r.composer={...r.composer,selectedModelId:y}},onVoiceToggle:((zs=r.voiceRecognition)==null?void 0:zs.enabled)===!0?()=>{pt==null||pt()}:void 0});u&&(Ze.replaceWith(u),Ze=u)}let un=l=>{let u=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),S=l.querySelector("[data-persona-composer-submit]"),R=l.querySelector("[data-persona-composer-mic]"),L=l.querySelector("[data-persona-composer-status]");u&&(We=u),y&&(X=y),S&&(K=S),R&&(B=R,Z=R.parentElement),L&&(Ve=L);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(ze=P);let V=l.querySelector(".persona-attachment-button");V&&(J=V,_=V.parentElement),xe=l.querySelector('input[type="file"]'),Le=l.querySelector(".persona-attachment-previews");let $=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");$&&(Rt=$)};bt(Ze),un(Ze);let gn=(Js=r.layout)==null?void 0:Js.contentMaxWidth;gn&&We&&(We.style.maxWidth=gn,We.style.marginLeft="auto",We.style.marginRight="auto"),(Ks=r.attachments)!=null&&Ks.enabled&&xe&&Le&&(He=ur.fromConfig(r.attachments),He.setPreviewsContainer(Le),xe.addEventListener("change",l=>{let u=l.target;He==null||He.handleFileSelect(u.files),u.value=""})),(()=>{var S,R;let l=(R=(S=r.layout)==null?void 0:S.slots)!=null?R:{},u=L=>{switch(L){case"body-top":return j.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return be;case"footer-top":return ze;case"composer":return We;case"footer-bottom":return Ve;default:return null}},y=(L,P)=>{var V;switch(L){case"header-left":case"header-center":case"header-right":if(L==="header-left")je.insertBefore(P,je.firstChild);else if(L==="header-right")je.appendChild(P);else{let $=je.querySelector(".persona-flex-col");$?(V=$.parentNode)==null||V.insertBefore(P,$.nextSibling):je.appendChild(P)}break;case"body-top":{let $=G.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");$?$.replaceWith(P):G.insertBefore(P,G.firstChild);break}case"body-bottom":G.appendChild(P);break;case"footer-top":ze.replaceWith(P);break;case"footer-bottom":Ve.replaceWith(P);break;default:break}};for(let[L,P]of Object.entries(l))if(P)try{let V=P({config:r,defaultContent:()=>u(L)});V&&y(L,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${L}":`,V)}})();let Pn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let S=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=y.getAttribute("data-bubble-type");L==="reasoning"?(fr.has(R)?fr.delete(R):fr.add(R),Il(R,S)):L==="tool"&&(hr.has(R)?hr.delete(R):hr.add(R),Wl(R,S,r))};be.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Pn(l))}),be.addEventListener("keydown",l=>{let u=l.target;(l.key==="Enter"||l.key===" ")&&u.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Pn(l))});let Zn=new Map;be.addEventListener("click",l=>{var P;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 R=S.getAttribute("data-actions-for");if(!R)return;let L=y.getAttribute("data-action");if(L==="copy"){let $=H.getMessages().find(se=>se.id===R);if($&&at.onCopy){let se=$.content||"";navigator.clipboard.writeText(se).then(()=>{y.classList.add("persona-message-action-success");let fe=me("check",14,"currentColor",2);fe&&(y.innerHTML="",y.appendChild(fe)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let ke=me("copy",14,"currentColor",2);ke&&(y.innerHTML="",y.appendChild(ke))},2e3)}).catch(fe=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",fe)}),at.onCopy($)}}else if(L==="upvote"||L==="downvote")if(((P=Zn.get(R))!=null?P:null)===L)Zn.delete(R),y.classList.remove("persona-message-action-active");else{let se=L==="upvote"?"downvote":"upvote",fe=S.querySelector(`[data-action="${se}"]`);fe&&fe.classList.remove("persona-message-action-active"),Zn.set(R,L),y.classList.add("persona-message-action-active");let Ne=H.getMessages().find(Ae=>Ae.id===R);Ne&&at.onFeedback&&at.onFeedback({type:L,messageId:Ne.id,message:Ne})}}),be.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.closest(".vanilla-approval-bubble");if(!S)return;let R=S.getAttribute("data-message-id");if(!R)return;let L=y.getAttribute("data-approval-action");if(!L)return;let P=L==="approve"?"approved":"denied",$=H.getMessages().find(fe=>fe.id===R);if(!($!=null&&$.approval))return;let se=S.querySelector("[data-approval-buttons]");se&&se.querySelectorAll("button").forEach(ke=>{ke.disabled=!0,ke.style.opacity="0.5",ke.style.cursor="not-allowed"}),H.resolveApproval($.approval,P)});let Qe=null,mn=null,In={artifacts:[],selectedId:null},ln=!1,Cr={current:null};be.addEventListener("click",l=>{var ke,Ne,Ae,I,Te;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let S=y.getAttribute("data-download-artifact");if(!S||((Ae=(Ne=(ke=r.features)==null?void 0:ke.artifacts)==null?void 0:Ne.onArtifactAction)==null?void 0:Ae.call(Ne,{type:"download",artifactId:S}))===!0)return;let L=H.getArtifactById(S),P=L==null?void 0:L.markdown,V=(L==null?void 0:L.title)||"artifact";if(!P){let Ee=y.closest("[data-open-artifact]"),ne=Ee==null?void 0:Ee.closest("[data-message-id]"),Pe=ne==null?void 0:ne.getAttribute("data-message-id");if(Pe){let Ke=H.getMessages().find(pe=>pe.id===Pe);if(Ke!=null&&Ke.rawContent)try{let pe=JSON.parse(Ke.rawContent);P=(I=pe==null?void 0:pe.props)==null?void 0:I.markdown,V=((Te=pe==null?void 0:pe.props)==null?void 0:Te.title)||V}catch{}}}if(!P)return;let $=new Blob([P],{type:"text/markdown"}),se=URL.createObjectURL($),fe=document.createElement("a");fe.href=se,fe.download=`${V}.md`,fe.click(),URL.revokeObjectURL(se)}),be.addEventListener("click",l=>{var L,P,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let S=y.getAttribute("data-open-artifact");!S||((V=(P=(L=r.features)==null?void 0:L.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:V.call(P,{type:"open",artifactId:S}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(S),hn())}),be.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let u=l.target;u.hasAttribute("data-open-artifact")&&(l.preventDefault(),u.click())});let fn=null,dt=null,nn=null,wn=null,wr=()=>{};function Qn(){wn==null||wn(),wn=null}let Sr=()=>{var P;if(!fn||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((P=e.ownerDocument.defaultView)!=null?P:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){dt.style.removeProperty("position"),dt.style.removeProperty("left"),dt.style.removeProperty("top"),dt.style.removeProperty("bottom"),dt.style.removeProperty("width"),dt.style.removeProperty("z-index");return}let S=fn.firstElementChild;if(!S||S===dt)return;let R=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${R}px`,dt.style.zIndex="5";let L=S.offsetWidth-R/2;dt.style.left=`${Math.max(0,L)}px`},Nn=()=>{},hn=()=>{var y,S,R,L,P;if(!Qe||!an(r))return;Ho(e,r),Bo(e,r),Nn();let l=(L=(R=(S=(y=r.features)==null?void 0:y.artifacts)==null?void 0:S.layout)==null?void 0:R.narrowHostMaxWidth)!=null?L:520,u=ie.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",u>0&&u<=l),Qe.update(In),ln?(Qe.setMobileOpen(!1),Qe.element.classList.add("persona-hidden"),(P=Qe.backdrop)==null||P.classList.add("persona-hidden")):In.artifacts.length>0&&(Qe.element.classList.remove("persona-hidden"),Qe.setMobileOpen(!0)),wr()};if(an(r)){ie.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),u=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(j),Qe=$l(r,{onSelect:y=>{var S;return(S=Cr.current)==null?void 0:S.selectArtifact(y)},onDismiss:()=>{ln=!0,hn()}}),Qe.element.classList.add("persona-hidden"),fn=u,u.appendChild(l),u.appendChild(Qe.element),Qe.backdrop&&ie.appendChild(Qe.backdrop),ie.appendChild(u),wr=()=>{var S,R,L,P;if(!fn||!Qe)return;if(!(((L=(R=(S=r.features)==null?void 0:S.artifacts)==null?void 0:R.layout)==null?void 0:L.resizable)===!0)){nn==null||nn(),nn=null,Qn(),dt&&(dt.remove(),dt=null),Qe.element.style.removeProperty("width"),Qe.element.style.removeProperty("maxWidth");return}if(!dt){let V=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");V.setAttribute("role","separator"),V.setAttribute("aria-orientation","vertical"),V.setAttribute("aria-label","Resize artifacts panel"),V.tabIndex=0;let $=e.ownerDocument,se=(P=$.defaultView)!=null?P:window,fe=ke=>{var ne,Pe;if(!Qe||ke.button!==0||e.classList.contains("persona-artifact-narrow-host")||se.innerWidth<=640)return;ke.preventDefault(),Qn();let Ne=ke.clientX,Ae=Qe.element.getBoundingClientRect().width,I=(Pe=(ne=r.features)==null?void 0:ne.artifacts)==null?void 0:Pe.layout,Te=rt=>{let Ke=fn.getBoundingClientRect().width,pe=e.classList.contains("persona-artifact-appearance-seamless"),Pt=pe?0:_l(fn,se),it=pe?0:V.getBoundingClientRect().width||6,Gt=Ae-(rt.clientX-Ne),jt=jl(Gt,Ke,Pt,it,I==null?void 0:I.resizableMinWidth,I==null?void 0:I.resizableMaxWidth);Qe.element.style.width=`${jt}px`,Qe.element.style.maxWidth="none",Sr()},Ee=()=>{$.removeEventListener("pointermove",Te),$.removeEventListener("pointerup",Ee),$.removeEventListener("pointercancel",Ee),wn=null;try{V.releasePointerCapture(ke.pointerId)}catch{}};wn=Ee,$.addEventListener("pointermove",Te),$.addEventListener("pointerup",Ee),$.addEventListener("pointercancel",Ee);try{V.setPointerCapture(ke.pointerId)}catch{}};V.addEventListener("pointerdown",fe),dt=V,fn.insertBefore(V,Qe.element),nn=()=>{V.removeEventListener("pointerdown",fe)}}if(dt){let V=In.artifacts.length>0&&!ln;dt.classList.toggle("persona-hidden",!V),Sr()}},Nn=()=>{var se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke,pe,Pt;if(!v||!Qe||((fe=(se=r.launcher)==null?void 0:se.sidebarMode)!=null?fe:!1))return;let S=(ke=e.ownerDocument.defaultView)!=null?ke:window,R=(Ae=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?Ae:!0,L=(Te=(I=r.launcher)==null?void 0:I.mobileBreakpoint)!=null?Te:640;if(R&&S.innerWidth<=L||!Dl(r,v))return;let P=(Pe=(ne=(Ee=r.launcher)==null?void 0:Ee.width)!=null?ne:r.launcherWidth)!=null?Pe:"min(400px, calc(100vw - 24px))",V=(Pt=(pe=(Ke=(rt=r.features)==null?void 0:rt.artifacts)==null?void 0:Ke.layout)==null?void 0:pe.expandedPanelWidth)!=null?Pt:"min(720px, calc(100vw - 24px))";In.artifacts.length>0&&!ln?(ie.style.width=V,ie.style.maxWidth=V):(ie.style.width=P,ie.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(mn=new ResizeObserver(()=>{hn()}),mn.observe(ie))}else ie.appendChild(j);e.appendChild(de);let On=()=>{var Ke,pe,Pt,it,Gt,jt,qt,$t,sn,_e,yt,yo,bo,xo,vo,Co,Ko,Yo,Et,wo,Br;let l=Jt(r),u=(pe=(Ke=r.launcher)==null?void 0:Ke.sidebarMode)!=null?pe:!1,y=l||u||((it=(Pt=r.launcher)==null?void 0:Pt.fullHeight)!=null?it:!1),S=((Gt=r.launcher)==null?void 0:Gt.enabled)===!1,R=(jt=r.theme)!=null?jt:{},L=(qt=e.ownerDocument.defaultView)!=null?qt:window,P=(sn=($t=r.launcher)==null?void 0:$t.mobileFullscreen)!=null?sn:!0,V=(yt=(_e=r.launcher)==null?void 0:_e.mobileBreakpoint)!=null?yt:640,$=L.innerWidth<=V,se=P&&$&&v,fe=(bo=(yo=r.launcher)==null?void 0:yo.position)!=null?bo:"bottom-left",ke=fe==="bottom-left"||fe==="top-left",Ne=u||se?"none":"1px solid var(--persona-persona-border)",Ae=se?"none":u?ke?"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))",I=u||se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",Te=(xo=R.panelBorder)!=null?xo:Ne,Ee=(vo=R.panelShadow)!=null?vo:Ae,ne=(Co=R.panelBorderRadius)!=null?Co:I;if(e.style.cssText="",de.style.cssText="",ie.style.cssText="",j.style.cssText="",G.style.cssText="",Ze.style.cssText="",se){de.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"),de.style.cssText=`
20
+ `,R.addEventListener("click",()=>{p=W,v.forEach((U,ve)=>{let le=ve<W;U.classList.toggle("selected",le),U.setAttribute("aria-checked",ve===W-1?"true":"false")})}),v.push(R),S.appendChild(R)}f.appendChild(S);let T=null;if(d){let W=document.createElement("div");W.className="persona-feedback-comment-container",T=document.createElement("textarea"),T.className="persona-feedback-comment",T.placeholder=o,T.rows=3,T.setAttribute("aria-label","Additional comments"),W.appendChild(T),f.appendChild(W)}let F=document.createElement("div");F.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(),u.remove()});let P=document.createElement("button");return P.type="button",P.className="persona-feedback-btn persona-feedback-btn-submit",P.textContent=a,P.addEventListener("click",async()=>{if(p===null){S.classList.add("persona-feedback-shake"),setTimeout(()=>S.classList.remove("persona-feedback-shake"),500);return}P.disabled=!0,P.textContent="Submitting...";try{let W=(T==null?void 0:T.value.trim())||void 0;await r(p,W),u.remove()}catch(W){P.disabled=!1,P.textContent=a,console.error("[CSAT Feedback] Failed to submit:",W)}}),F.appendChild(w),F.appendChild(P),f.appendChild(F),u.appendChild(f),u}function Ws(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:d=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-nps",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let x=document.createElement("div");x.className="persona-feedback-header";let b=document.createElement("h3");b.className="persona-feedback-title",b.textContent=n,x.appendChild(b);let S=document.createElement("p");S.className="persona-feedback-subtitle",S.textContent=s,x.appendChild(S),m.appendChild(x);let v=document.createElement("div");v.className="persona-feedback-rating persona-feedback-rating-nps",v.setAttribute("role","radiogroup"),v.setAttribute("aria-label","Likelihood rating from 0 to 10");let T=document.createElement("div");T.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let w=document.createElement("span");w.className="persona-feedback-label-high",w.textContent=u,T.appendChild(F),T.appendChild(w);let P=document.createElement("div");P.className="persona-feedback-numbers";let W=[];for(let q=0;q<=10;q++){let ee=document.createElement("button");ee.type="button",ee.className="persona-feedback-rating-btn persona-feedback-number-btn",ee.setAttribute("role","radio"),ee.setAttribute("aria-checked","false"),ee.setAttribute("aria-label",`Rating ${q} out of 10`),ee.textContent=String(q),ee.dataset.rating=String(q),q<=6?ee.classList.add("persona-feedback-detractor"):q<=8?ee.classList.add("persona-feedback-passive"):ee.classList.add("persona-feedback-promoter"),ee.addEventListener("click",()=>{f=q,W.forEach((Ce,we)=>{Ce.classList.toggle("selected",we===q),Ce.setAttribute("aria-checked",we===q?"true":"false")})}),W.push(ee),P.appendChild(ee)}v.appendChild(T),v.appendChild(P),m.appendChild(v);let R=null;if(d){let q=document.createElement("div");q.className="persona-feedback-comment-container",R=document.createElement("textarea"),R.className="persona-feedback-comment",R.placeholder=o,R.rows=3,R.setAttribute("aria-label","Additional comments"),q.appendChild(R),m.appendChild(q)}let U=document.createElement("div");U.className="persona-feedback-actions";let ve=document.createElement("button");ve.type="button",ve.className="persona-feedback-btn persona-feedback-btn-skip",ve.textContent=i,ve.addEventListener("click",()=>{t==null||t(),p.remove()});let le=document.createElement("button");return le.type="button",le.className="persona-feedback-btn persona-feedback-btn-submit",le.textContent=a,le.addEventListener("click",async()=>{if(f===null){P.classList.add("persona-feedback-shake"),setTimeout(()=>P.classList.remove("persona-feedback-shake"),500);return}le.disabled=!0,le.textContent="Submitting...";try{let q=(R==null?void 0:R.value.trim())||void 0;await r(f,q),p.remove()}catch(q){le.disabled=!1,le.textContent=a,console.error("[NPS Feedback] Failed to submit:",q)}}),U.appendChild(ve),U.appendChild(le),m.appendChild(U),p.appendChild(m),p}var Tr="persona-chat-history",Qd=30*1e3,ep={"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 tp(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 d=(s=ep[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${d}`,{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 np(e){var r,t,n,s,o,a,i,d,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:(d=(i=e.persist)==null?void 0:i.focusInput)!=null?d:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function rp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Rs=e=>!e||typeof e!="object"?{}:{...e},Ql=e=>e.map(r=>({...r,streaming:!1})),ec=(e,r,t)=>{let n=e!=null&&e.markdown?fr(e.markdown):null,s=Kr(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,u,p;let a=(c=o.text)!=null?c:"",i=(u=o.message.rawContent)!=null?u: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 d;return e!=null&&e.postprocessMessage?d=e.postprocessMessage({...o,text:a,raw:(p=i!=null?i:o.text)!=null?p:""}):n?d=n(a):d=Jr(a),s?s(d):d}},Hs=(e,r,t)=>{var ie,Me,at,Lt,Ct,Bt,Pt,it,ct,At,dt,Dt,Xt,ln,qs,Us,Vs,Js,Ks,Ys,Gs,Xs,Zs,Qs,ea,ta,na,ra,oa,sa,aa,ia,la,ca,da,pa,ua,ga;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=As(r),s=qo.getForInstance(n.plugins);n.components&&zn.registerAll(n.components);let o=Xl(),a=(ie=n.storageAdapter)!=null?ie:Ts(),i={},d=null,c=l=>{if(n.onStateLoaded)try{return n.onStateLoaded(l)}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",g)}return l};if(a!=null&&a.load)try{let l=a.load();if(l&&typeof l.then=="function")d=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return c(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=c(g);y.metadata&&(i=Rs(y.metadata)),(Me=y.messages)!=null&&Me.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=c({messages:[],metadata:{}});(at=l.messages)!=null&&at.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let u=()=>i,p=l=>{var y;i=(y=l({...i}))!=null?y:{},Br()},f=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],m=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Er.message,Er.messageAndClick],x=Vo({parsers:f,handlers:m,getSessionMetadata:u,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null});x.syncFromMetadata();let b=(Ct=(Lt=n.launcher)==null?void 0:Lt.enabled)!=null?Ct:!0,S=(Pt=(Bt=n.launcher)==null?void 0:Bt.autoExpand)!=null?Pt:!1,v=(it=n.autoFocusInput)!=null?it:!1,T=S,F=b,w=(At=(ct=n.layout)==null?void 0:ct.header)==null?void 0:At.layout,P=!1,W=b?S:!0,R=!1,U=null,ve=()=>{R=!0,U&&clearTimeout(U),U=setTimeout(()=>{R&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),R=!1)},1e4)},le=ec(n,x,ve),q=(Dt=(dt=n.features)==null?void 0:dt.showReasoning)!=null?Dt:!0,ee=(ln=(Xt=n.features)==null?void 0:Xt.showToolCalls)!=null?ln:!0,Ce=(Us=(qs=n.features)==null?void 0:qs.showEventStreamToggle)!=null?Us:!1,ye=`${(Js=typeof n.persistState=="object"?(Vs=n.persistState)==null?void 0:Vs.keyPrefix:void 0)!=null?Js:"persona-"}event-stream`,ce=Ce?new io(ye):null,Q=(Gs=(Ys=(Ks=n.features)==null?void 0:Ks.eventStream)==null?void 0:Ys.maxEvents)!=null?Gs:2e3,J=Ce?new ao(Q,ce):null,V=null,ne=!1,fe=null,wt=0;ce==null||ce.open().then(()=>J==null?void 0:J.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let ut={onCopy:l=>{var g,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=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,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=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},gt=(Xs=n.statusIndicator)!=null?Xs:{},Tt=l=>{var g,y,A,k;return l==="idle"?(g=gt.idleText)!=null?g:Vt.idle:l==="connecting"?(y=gt.connectingText)!=null?y:Vt.connecting:l==="connected"?(A=gt.connectedText)!=null?A:Vt.connected:l==="error"?(k=gt.errorText)!=null?k:Vt.error:Vt[l]},{wrapper:se,panel:re}=Wl(n),Ue=Rl(n,b),{container:z,body:te,messagesWrapper:de,suggestions:Qe,textarea:G,sendButton:Y,sendButtonWrapper:tt,composerForm:Ne,statusText:je,introTitle:Mt,introSubtitle:qt,closeButton:ue,iconHolder:Ye,headerTitle:ke,headerSubtitle:ot,header:Ve,footer:nt,actionsRow:Rt,leftActions:Ht,rightActions:kt}=Ue,N=Ue.micButton,X=Ue.micButtonWrapper,_=Ue.attachmentButton,be=Ue.attachmentButtonWrapper,xe=Ue.attachmentInput,Ae=Ue.attachmentPreviewsContainer,Ee=null,st=null,Be=s.find(l=>l.renderHeader);if(Be!=null&&Be.renderHeader){let l=Be.renderHeader({config:n,defaultRenderer:()=>{let g=jn({config:n,showClose:b});return vr(z,g,n),g.header},onClose:()=>mt(!1,"user")});if(l){let g=z.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ve=l)}}let We=()=>{var g,y,A,k;if(!J)return;if(ne=!0,!V&&J&&(V=$l({buffer:J,getFullHistory:()=>J.getAllFromStore(),onClose:()=>ze(),config:n,plugins:s})),V&&(te.style.display="none",(g=nt.parentNode)==null||g.insertBefore(V.element,nt),V.update()),pe){pe.classList.remove("persona-text-persona-muted"),pe.classList.add("persona-text-persona-accent"),pe.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let I=(k=(A=(y=n.features)==null?void 0:y.eventStream)==null?void 0:A.classNames)==null?void 0:k.toggleButtonActive;I&&I.split(/\s+/).forEach(L=>L&&pe.classList.add(L))}let l=()=>{if(!ne)return;let I=Date.now();I-wt>=200&&(V==null||V.update(),wt=I),fe=requestAnimationFrame(l)};wt=0,fe=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},ze=()=>{var l,g,y;if(ne){if(ne=!1,V&&V.element.remove(),te.style.display="",pe){pe.classList.remove("persona-text-persona-accent"),pe.classList.add("persona-text-persona-muted"),pe.style.boxShadow="";let A=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;A&&A.split(/\s+/).forEach(k=>k&&pe.classList.remove(k))}fe!==null&&(cancelAnimationFrame(fe),fe=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},pe=null;if(Ce){let l=(Qs=(Zs=n.features)==null?void 0:Zs.eventStream)==null?void 0:Qs.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");pe=h("button",g),pe.style.width="28px",pe.style.height="28px",pe.type="button",pe.setAttribute("aria-label","Event Stream"),pe.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&pe.appendChild(y);let A=Ue.clearChatButtonWrapper,k=Ue.closeButtonWrapper,I=A||k;I&&I.parentNode===Ve?Ve.insertBefore(pe,I):Ve.appendChild(pe),pe.addEventListener("click",()=>{ne?ze():We()})}let Ft=l=>{var A,k,I;let g=n.attachments;if(!(g!=null&&g.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 L=l.querySelector("[data-persona-composer-form]");L!=null&&L.parentNode?L.parentNode.insertBefore(y,L):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let L=h("input");L.type="file",L.accept=((A=g.allowedTypes)!=null?A:Hn).join(","),L.multiple=((k=g.maxFiles)!=null?k:4)>1,L.style.display="none",L.setAttribute("aria-label",(I=g.buttonTooltipText)!=null?I:"Attach files"),l.appendChild(L)}},xn=s.find(l=>l.renderComposer);if(xn!=null&&xn.renderComposer){let l=n.composer,g=xn.renderComposer({config:n,defaultRenderer:()=>oo({config:n}).footer,onSubmit:y=>{D&&!D.isStreaming()&&D.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{xe==null||xe.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((ea=n.voiceRecognition)==null?void 0:ea.enabled)===!0?()=>{st==null||st()}:void 0});g&&(nt.replaceWith(g),nt=g)}let Un=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),A=l.querySelector("[data-persona-composer-submit]"),k=l.querySelector("[data-persona-composer-mic]"),I=l.querySelector("[data-persona-composer-status]");g&&(Ne=g),y&&(G=y),A&&(Y=A),k&&(N=k,X=k.parentElement),I&&(je=I);let L=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");L&&(Qe=L);let j=l.querySelector(".persona-attachment-button");j&&(_=j,be=j.parentElement),xe=l.querySelector('input[type="file"]'),Ae=l.querySelector(".persona-attachment-previews");let O=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");O&&(Rt=O)};Ft(nt),Un(nt);let Dn=(ta=n.layout)==null?void 0:ta.contentMaxWidth;Dn&&Ne&&(Ne.style.maxWidth=Dn,Ne.style.marginLeft="auto",Ne.style.marginRight="auto"),(na=n.attachments)!=null&&na.enabled&&xe&&Ae&&(Ee=xr.fromConfig(n.attachments),Ee.setPreviewsContainer(Ae),xe.addEventListener("change",l=>{let g=l.target;Ee==null||Ee.handleFileSelect(g.files),g.value=""})),(()=>{var A,k;let l=(k=(A=n.layout)==null?void 0:A.slots)!=null?k:{},g=I=>{switch(I){case"body-top":return z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return de;case"footer-top":return Qe;case"composer":return Ne;case"footer-bottom":return je;default:return null}},y=(I,L)=>{var j;switch(I){case"header-left":case"header-center":case"header-right":if(I==="header-left")Ve.insertBefore(L,Ve.firstChild);else if(I==="header-right")Ve.appendChild(L);else{let O=Ve.querySelector(".persona-flex-col");O?(j=O.parentNode)==null||j.insertBefore(L,O.nextSibling):Ve.appendChild(L)}break;case"body-top":{let O=te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");O?O.replaceWith(L):te.insertBefore(L,te.firstChild);break}case"body-bottom":te.appendChild(L);break;case"footer-top":Qe.replaceWith(L);break;case"footer-bottom":je.replaceWith(L);break;default:break}};for(let[I,L]of Object.entries(l))if(L)try{let j=L({config:n,defaultContent:()=>g(I)});j&&y(I,j)}catch(j){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${I}":`,j)}})();let Nn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let A=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!A)return;let k=A.getAttribute("data-message-id");if(!k)return;let I=y.getAttribute("data-bubble-type");I==="reasoning"?(wr.has(k)?wr.delete(k):wr.add(k),Nl(k,A)):I==="tool"&&(Sr.has(k)?Sr.delete(k):Sr.add(k),Ol(k,A,n))};de.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nn(l))}),de.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nn(l))});let Tn=new Map;de.addEventListener("click",l=>{var L;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 k=A.getAttribute("data-actions-for");if(!k)return;let I=y.getAttribute("data-action");if(I==="copy"){let O=D.getMessages().find(oe=>oe.id===k);if(O&&ut.onCopy){let oe=O.content||"";navigator.clipboard.writeText(oe).then(()=>{y.classList.add("persona-message-action-success");let he=me("check",14,"currentColor",2);he&&(y.innerHTML="",y.appendChild(he)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let Se=me("copy",14,"currentColor",2);Se&&(y.innerHTML="",y.appendChild(Se))},2e3)}).catch(he=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",he)}),ut.onCopy(O)}}else if(I==="upvote"||I==="downvote")if(((L=Tn.get(k))!=null?L:null)===I)Tn.delete(k),y.classList.remove("persona-message-action-active");else{let oe=I==="upvote"?"downvote":"upvote",he=A.querySelector(`[data-action="${oe}"]`);he&&he.classList.remove("persona-message-action-active"),Tn.set(k,I),y.classList.add("persona-message-action-active");let Re=D.getMessages().find(Le=>Le.id===k);Re&&ut.onFeedback&&ut.onFeedback({type:I,messageId:Re.id,message:Re})}}),de.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.closest(".vanilla-approval-bubble");if(!A)return;let k=A.getAttribute("data-message-id");if(!k)return;let I=y.getAttribute("data-approval-action");if(!I)return;let L=I==="approve"?"approved":"denied",O=D.getMessages().find(he=>he.id===k);if(!(O!=null&&O.approval))return;let oe=A.querySelector("[data-approval-buttons]");oe&&oe.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),D.resolveApproval(O.approval,L)});let Xe=null,tn=null,un={artifacts:[],selectedId:null},K=!1,Mn={current:null};de.addEventListener("click",l=>{var Se,Re,Le,B,Pe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let A=y.getAttribute("data-download-artifact");if(!A||((Le=(Re=(Se=n.features)==null?void 0:Se.artifacts)==null?void 0:Re.onArtifactAction)==null?void 0:Le.call(Re,{type:"download",artifactId:A}))===!0)return;let I=D.getArtifactById(A),L=I==null?void 0:I.markdown,j=(I==null?void 0:I.title)||"artifact";if(!L){let Ie=y.closest("[data-open-artifact]"),ae=Ie==null?void 0:Ie.closest("[data-message-id]"),He=ae==null?void 0:ae.getAttribute("data-message-id");if(He){let Je=D.getMessages().find(ge=>ge.id===He);if(Je!=null&&Je.rawContent)try{let ge=JSON.parse(Je.rawContent);L=(B=ge==null?void 0:ge.props)==null?void 0:B.markdown,j=((Pe=ge==null?void 0:ge.props)==null?void 0:Pe.title)||j}catch{}}}if(!L)return;let O=new Blob([L],{type:"text/markdown"}),oe=URL.createObjectURL(O),he=document.createElement("a");he.href=oe,he.download=`${j}.md`,he.click(),URL.revokeObjectURL(oe)}),de.addEventListener("click",l=>{var I,L,j;let y=l.target.closest("[data-open-artifact]");if(!y)return;let A=y.getAttribute("data-open-artifact");!A||((j=(L=(I=n.features)==null?void 0:I.artifacts)==null?void 0:L.onArtifactAction)==null?void 0:j.call(L,{type:"open",artifactId:A}))===!0||(l.preventDefault(),l.stopPropagation(),D.selectArtifact(A),vn())}),de.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let on=null,pt=null,sn=null,kn=null,kr=()=>{};function ir(){kn==null||kn(),kn=null}let Lr=()=>{var L;if(!on||!pt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((L=e.ownerDocument.defaultView)!=null?L:window).innerWidth<=640;if(!l||e.classList.contains("persona-artifact-narrow-host")||y){pt.style.removeProperty("position"),pt.style.removeProperty("left"),pt.style.removeProperty("top"),pt.style.removeProperty("bottom"),pt.style.removeProperty("width"),pt.style.removeProperty("z-index");return}let A=on.firstElementChild;if(!A||A===pt)return;let k=10;pt.style.position="absolute",pt.style.top="0",pt.style.bottom="0",pt.style.width=`${k}px`,pt.style.zIndex="5";let I=A.offsetWidth-k/2;pt.style.left=`${Math.max(0,I)}px`},Vn=()=>{},vn=()=>{var y,A,k,I,L;if(!Xe||!pn(n))return;jo(e,n),zo(e,n),Vn();let l=(I=(k=(A=(y=n.features)==null?void 0:y.artifacts)==null?void 0:A.layout)==null?void 0:k.narrowHostMaxWidth)!=null?I:520,g=re.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),Xe.update(un),K?(Xe.setMobileOpen(!1),Xe.element.classList.add("persona-hidden"),(L=Xe.backdrop)==null||L.classList.add("persona-hidden")):un.artifacts.length>0&&(Xe.element.classList.remove("persona-hidden"),Xe.setMobileOpen(!0)),kr()};if(pn(n)){re.style.position="relative";let l=h("div","persona-flex persona-flex-1 persona-flex-col persona-min-w-0 persona-min-h-0"),g=h("div","persona-flex persona-h-full persona-w-full persona-min-h-0 persona-artifact-split-root");l.appendChild(z),Xe=zl(n,{onSelect:y=>{var A;return(A=Mn.current)==null?void 0:A.selectArtifact(y)},onDismiss:()=>{K=!0,vn()}}),Xe.element.classList.add("persona-hidden"),on=g,g.appendChild(l),g.appendChild(Xe.element),Xe.backdrop&&re.appendChild(Xe.backdrop),re.appendChild(g),kr=()=>{var A,k,I,L;if(!on||!Xe)return;if(!(((I=(k=(A=n.features)==null?void 0:A.artifacts)==null?void 0:k.layout)==null?void 0:I.resizable)===!0)){sn==null||sn(),sn=null,ir(),pt&&(pt.remove(),pt=null),Xe.element.style.removeProperty("width"),Xe.element.style.removeProperty("maxWidth");return}if(!pt){let j=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");j.setAttribute("role","separator"),j.setAttribute("aria-orientation","vertical"),j.setAttribute("aria-label","Resize artifacts panel"),j.tabIndex=0;let O=e.ownerDocument,oe=(L=O.defaultView)!=null?L:window,he=Se=>{var ae,He;if(!Xe||Se.button!==0||e.classList.contains("persona-artifact-narrow-host")||oe.innerWidth<=640)return;Se.preventDefault(),ir();let Re=Se.clientX,Le=Xe.element.getBoundingClientRect().width,B=(He=(ae=n.features)==null?void 0:ae.artifacts)==null?void 0:He.layout,Pe=et=>{let Je=on.getBoundingClientRect().width,ge=e.classList.contains("persona-artifact-appearance-seamless"),It=ge?0:Jl(on,oe),lt=ge?0:j.getBoundingClientRect().width||6,Zt=Le-(et.clientX-Re),Ut=Kl(Zt,Je,It,lt,B==null?void 0:B.resizableMinWidth,B==null?void 0:B.resizableMaxWidth);Xe.element.style.width=`${Ut}px`,Xe.element.style.maxWidth="none",Lr()},Ie=()=>{O.removeEventListener("pointermove",Pe),O.removeEventListener("pointerup",Ie),O.removeEventListener("pointercancel",Ie),kn=null;try{j.releasePointerCapture(Se.pointerId)}catch{}};kn=Ie,O.addEventListener("pointermove",Pe),O.addEventListener("pointerup",Ie),O.addEventListener("pointercancel",Ie);try{j.setPointerCapture(Se.pointerId)}catch{}};j.addEventListener("pointerdown",he),pt=j,on.insertBefore(j,Xe.element),sn=()=>{j.removeEventListener("pointerdown",he)}}if(pt){let j=un.artifacts.length>0&&!K;pt.classList.toggle("persona-hidden",!j),Lr()}},Vn=()=>{var oe,he,Se,Re,Le,B,Pe,Ie,ae,He,et,Je,ge,It;if(!b||!Xe||((he=(oe=n.launcher)==null?void 0:oe.sidebarMode)!=null?he:!1)||zt(n)&&hn(n).reveal==="emerge")return;let A=(Se=e.ownerDocument.defaultView)!=null?Se:window,k=(Le=(Re=n.launcher)==null?void 0:Re.mobileFullscreen)!=null?Le:!0,I=(Pe=(B=n.launcher)==null?void 0:B.mobileBreakpoint)!=null?Pe:640;if(k&&A.innerWidth<=I||!Vl(n,b))return;let L=(He=(ae=(Ie=n.launcher)==null?void 0:Ie.width)!=null?ae:n.launcherWidth)!=null?He:"min(400px, calc(100vw - 24px))",j=(It=(ge=(Je=(et=n.features)==null?void 0:et.artifacts)==null?void 0:Je.layout)==null?void 0:ge.expandedPanelWidth)!=null?It:"min(720px, calc(100vw - 24px))";un.artifacts.length>0&&!K?(re.style.width=j,re.style.maxWidth=j):(re.style.width=L,re.style.maxWidth=L)},typeof ResizeObserver!="undefined"&&(tn=new ResizeObserver(()=>{vn()}),tn.observe(re))}else re.appendChild(z);e.appendChild(se);let Jn=()=>{var It,lt,Zt,Ut,Kt,Nt,cn,Ke,yt,Co,wo,So,Ao,Eo,ns,rs,Et,To,_r;let l=zt(n),g=(lt=(It=n.launcher)==null?void 0:It.sidebarMode)!=null?lt:!1,y=l||g||((Ut=(Zt=n.launcher)==null?void 0:Zt.fullHeight)!=null?Ut:!1),A=((Kt=n.launcher)==null?void 0:Kt.enabled)===!1,k=(cn=(Nt=n.theme)==null?void 0:Nt.components)==null?void 0:cn.panel,I=Fo(n),L=(Qt,dn)=>{var Mo;return Qt==null||Qt===""?dn:(Mo=Qr(I,Qt))!=null?Mo:Qt},j=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,O=(Co=(yt=n.launcher)==null?void 0:yt.mobileFullscreen)!=null?Co:!0,oe=(So=(wo=n.launcher)==null?void 0:wo.mobileBreakpoint)!=null?So:640,he=j.innerWidth<=oe,Se=O&&he&&b,Re=(Eo=(Ao=n.launcher)==null?void 0:Ao.position)!=null?Eo:"bottom-left",Le=Re==="bottom-left"||Re==="top-left",B=g||Se?"none":"1px solid var(--persona-border)",Pe=Se?"none":g?Le?"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&&!Se&&(Pe="none",B="none");let Ie=g||Se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",ae=L(k==null?void 0:k.border,B),He=L(k==null?void 0:k.shadow,Pe),et=L(k==null?void 0:k.borderRadius,Ie);if(e.style.cssText="",se.style.cssText="",re.style.cssText="",z.style.cssText="",te.style.cssText="",nt.style.cssText="",Se){se.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"),se.style.cssText=`
21
21
  position: fixed !important;
22
22
  inset: 0 !important;
23
23
  width: 100% !important;
@@ -28,7 +28,7 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
28
28
  display: flex !important;
29
29
  flex-direction: column !important;
30
30
  z-index: inherit !important;
31
- `,ie.style.cssText=`
31
+ `,re.style.cssText=`
32
32
  position: relative !important;
33
33
  display: flex !important;
34
34
  flex-direction: column !important;
@@ -41,7 +41,7 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
41
41
  padding: 0 !important;
42
42
  box-shadow: none !important;
43
43
  border-radius: 0 !important;
44
- `,j.style.cssText=`
44
+ `,z.style.cssText=`
45
45
  display: flex !important;
46
46
  flex-direction: column !important;
47
47
  flex: 1 1 0% !important;
@@ -52,19 +52,19 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
52
52
  overflow: hidden !important;
53
53
  border-radius: 0 !important;
54
54
  border: none !important;
55
- `,G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ze.style.flexShrink="0",N=!0;return}let Pe=(Yo=(Ko=r==null?void 0:r.launcher)==null?void 0:Ko.width)!=null?Yo:r==null?void 0:r.launcherWidth,rt=Pe!=null?Pe:"min(400px, calc(100vw - 24px))";if(!u&&!l?S&&y?(ie.style.width="100%",ie.style.maxWidth="100%"):(ie.style.width=rt,ie.style.maxWidth=rt):l&&(ie.style.width="100%",ie.style.maxWidth="100%"),Nn(),ie.style.boxShadow=Ee,ie.style.borderRadius=ne,j.style.border=Te,j.style.borderRadius=ne,y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",S&&(e.style.width="100%"),de.style.display="flex",de.style.flexDirection="column",de.style.flex="1 1 0%",de.style.minHeight="0",de.style.maxHeight="100%",de.style.height="100%",S&&(de.style.overflow="hidden"),ie.style.display="flex",ie.style.flexDirection="column",ie.style.flex="1 1 0%",ie.style.minHeight="0",ie.style.maxHeight="100%",ie.style.height="100%",ie.style.overflow="hidden",j.style.display="flex",j.style.flexDirection="column",j.style.flex="1 1 0%",j.style.minHeight="0",j.style.maxHeight="100%",j.style.overflow="hidden",G.style.flex="1 1 0%",G.style.minHeight="0",G.style.overflowY="auto",Ze.style.flexShrink="0"),de.classList.remove("persona-bottom-6","persona-right-6","persona-left-6","persona-top-6","persona-bottom-4","persona-right-4","persona-left-4","persona-top-4"),!u&&!S&&!l&&((Et=pn[fe])!=null?Et:pn["bottom-right"]).split(" ").forEach(Jn=>de.classList.add(Jn)),u){let zn=(Br=(wo=r.launcher)==null?void 0:wo.sidebarWidth)!=null?Br:"420px";de.style.cssText=`
55
+ `,te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",nt.style.flexShrink="0",P=!0;return}let Je=(rs=(ns=n==null?void 0:n.launcher)==null?void 0:ns.width)!=null?rs:n==null?void 0:n.launcherWidth,ge=Je!=null?Je:"min(400px, calc(100vw - 24px))";if(!g&&!l)A&&y?(re.style.width="100%",re.style.maxWidth="100%"):(re.style.width=ge,re.style.maxWidth=ge);else if(l)if(hn(n).reveal==="emerge"){let dn=hn(n).width;re.style.width=dn,re.style.maxWidth=dn}else re.style.width="100%",re.style.maxWidth="100%";if(Vn(),re.style.boxShadow=He,re.style.borderRadius=et,z.style.border=ae,z.style.borderRadius=et,l&&!Se&&(k==null?void 0:k.border)===void 0&&(z.style.border="none",hn(n).side==="right"?z.style.borderLeft="1px solid var(--persona-border)":z.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",A&&(e.style.width="100%"),se.style.display="flex",se.style.flexDirection="column",se.style.flex="1 1 0%",se.style.minHeight="0",se.style.maxHeight="100%",se.style.height="100%",A&&(se.style.overflow="hidden"),re.style.display="flex",re.style.flexDirection="column",re.style.flex="1 1 0%",re.style.minHeight="0",re.style.maxHeight="100%",re.style.height="100%",re.style.overflow="hidden",z.style.display="flex",z.style.flexDirection="column",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.maxHeight="100%",z.style.overflow="hidden",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.overflowY="auto",nt.style.flexShrink="0"),se.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"),!g&&!A&&!l&&((Et=yn[Re])!=null?Et:yn["bottom-right"]).split(" ").forEach(dn=>se.classList.add(dn)),g){let Qt=(_r=(To=n.launcher)==null?void 0:To.sidebarWidth)!=null?_r:"420px";se.style.cssText=`
56
56
  position: fixed !important;
57
57
  top: 0 !important;
58
58
  bottom: 0 !important;
59
- width: ${zn} !important;
59
+ width: ${Qt} !important;
60
60
  height: 100vh !important;
61
61
  max-height: 100vh !important;
62
62
  margin: 0 !important;
63
63
  padding: 0 !important;
64
64
  display: flex !important;
65
65
  flex-direction: column !important;
66
- ${ke?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
67
- `,ie.style.cssText=`
66
+ ${Le?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
67
+ `,re.style.cssText=`
68
68
  position: relative !important;
69
69
  display: flex !important;
70
70
  flex-direction: column !important;
@@ -75,9 +75,9 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
75
75
  min-height: 0 !important;
76
76
  margin: 0 !important;
77
77
  padding: 0 !important;
78
- box-shadow: ${Ee} !important;
79
- border-radius: ${ne} !important;
80
- `,ie.style.setProperty("width","100%","important"),ie.style.setProperty("max-width","100%","important"),j.style.cssText=`
78
+ box-shadow: ${He} !important;
79
+ border-radius: ${et} !important;
80
+ `,re.style.setProperty("width","100%","important"),re.style.setProperty("max-width","100%","important"),z.style.cssText=`
81
81
  display: flex !important;
82
82
  flex-direction: column !important;
83
83
  flex: 1 1 0% !important;
@@ -86,29 +86,29 @@ import{Marked as Ac}from"marked";var Ec=e=>{if(e)return e},Ao=e=>{var s,o;let n=
86
86
  min-height: 0 !important;
87
87
  max-height: 100% !important;
88
88
  overflow: hidden !important;
89
- border-radius: ${ne} !important;
90
- border: ${Te} !important;
91
- `,Ze.style.cssText=`
89
+ border-radius: ${et} !important;
90
+ border: ${ae} !important;
91
+ `,nt.style.cssText=`
92
92
  flex-shrink: 0 !important;
93
93
  border-top: none !important;
94
94
  padding: 8px 16px 12px 16px !important;
95
- `}if(!S&&!l){let zn="max-height: -moz-available !important; max-height: stretch !important;",Jn=u?"":"padding-top: 1.25em !important;";de.style.cssText+=zn+Jn}};On(),Xn(e,r),Ho(e,r),Bo(e,r);let xt=[];mn&&xt.push(()=>{mn==null||mn.disconnect(),mn=null}),xt.push(()=>{nn==null||nn(),nn=null,Qn(),dt&&(dt.remove(),dt=null),Qe==null||Qe.element.style.removeProperty("width"),Qe==null||Qe.element.style.removeProperty("maxWidth")}),Ie&&xt.push(()=>{he!==null&&(cancelAnimationFrame(he),he=null),U==null||U.destroy(),U=null,D==null||D.destroy(),D=null,ee=null});let yn=null,Ar=()=>{yn&&(yn(),yn=null),r.colorScheme==="auto"&&(yn=ds(()=>{Xn(e,r)}))};Ar(),xt.push(()=>{yn&&(yn(),yn=null)});let Wn=Rl(ze),bn=null,H,Rn=!1,Hn=xl(),Er=0,Sn=!0,Dn=0,Tr=0,An=null,En=!1,er=0,tr=!1,oo=125,so=2e3,ao=5,Mr=50,nr=new Map,Ue={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},kr=(Gs=(Ys=r.voiceRecognition)==null?void 0:Ys.autoResume)!=null?Gs:!1,rn=l=>{o.emit("voice:state",{active:Ue.active,source:l,timestamp:Date.now()})},Kt=()=>{p(l=>({...l,voiceState:{active:Ue.active,timestamp:Date.now(),manuallyDeactivated:Ue.manuallyDeactivated}}))},io=()=>{var S,R;if(((S=r.voiceRecognition)==null?void 0:S.enabled)===!1)return;let l=ks(i.voiceState),u=!!l.active,y=Number((R=l.timestamp)!=null?R:0);Ue.manuallyDeactivated=!!l.manuallyDeactivated,u&&Date.now()-y<Gd&&setTimeout(()=>{var L,P;Ue.active||(Ue.manuallyDeactivated=!1,((P=(L=r.voiceRecognition)==null?void 0:L.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("restore"),H.isVoiceActive()&&Bn()}):Vn("restore"))},1e3)},lo=()=>H?Kl(H.getMessages()).filter(l=>!l.__skipPersist):[];function Lr(l){if(!(a!=null&&a.save))return;let y={messages:l?Kl(l):H?lo():[],metadata:i};try{let S=a.save(y);S instanceof Promise&&S.catch(R=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",R)})}catch(S){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",S)}}let _n=(l=!1)=>{if(!Sn)return;let u=Date.now();En&&u<er&&!l||(En&&u>=er&&(En=!1),!(!l&&!Rn)&&(u-Tr<oo||(Tr=u,An&&cancelAnimationFrame(An),An=requestAnimationFrame(()=>{En||!Sn||(tr=!0,G.scrollTop=G.scrollHeight,Dn=G.scrollTop,requestAnimationFrame(()=>{tr=!1}),An=null)}))))},Tn=null,co=()=>de.querySelector("#persona-scroll-container")||G,po=(l,u=500)=>{let y=l.scrollTop,S=l.clientHeight,R=l.scrollHeight,L=R-y;if(y+S>=R-2||Math.abs(L)<5)return;Tn!==null&&(cancelAnimationFrame(Tn),Tn=null);let V=performance.now(),$=fe=>1-Math.pow(1-fe,3),se=fe=>{let ke=l.scrollHeight;ke!==R&&(R=ke,L=R-y);let Ne=fe-V,Ae=Math.min(Ne/u,1),I=$(Ae),Te=y+L*I;l.scrollTop=Te,Ae<1?Tn=requestAnimationFrame(se):(l.scrollTop=l.scrollHeight,Tn=null)};Tn=requestAnimationFrame(se)},uo=l=>{let u=new Map;l.forEach(y=>{let S=nr.get(y.id);u.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}))}),nr.clear(),u.forEach((y,S)=>{nr.set(S,y)})},jn=(l,u,y)=>{var fe,ke,Ne,Ae;let S=document.createElement("div"),L=(()=>{var Te;let I=s.find(Ee=>Ee.renderLoadingIndicator);if(I!=null&&I.renderLoadingIndicator)return I.renderLoadingIndicator;if((Te=r.loadingIndicator)!=null&&Te.render)return r.loadingIndicator.render})(),P=new Set;u.forEach(I=>{var pe,Pt;P.add(I.id);let Te=bl(I,Er),Ee=vl(Hn,I.id,Te);if(Ee){S.appendChild(Ee.cloneNode(!0));return}let ne=null,Pe=s.find(it=>!!(I.variant==="reasoning"&&it.renderReasoning||I.variant==="tool"&&it.renderToolCall||I.variant==="approval"&&it.renderApproval||!I.variant&&it.renderMessage)),rt=(pe=r.layout)==null?void 0:pe.messages;if(Pe)if(I.variant==="reasoning"&&I.reasoning&&Pe.renderReasoning){if(!z)return;ne=Pe.renderReasoning({message:I,defaultRenderer:()=>us(I),config:r})}else if(I.variant==="tool"&&I.toolCall&&Pe.renderToolCall){if(!ge)return;ne=Pe.renderToolCall({message:I,defaultRenderer:()=>gs(I,r),config:r})}else if(I.variant==="approval"&&I.approval&&Pe.renderApproval){if(r.approval===!1)return;ne=Pe.renderApproval({message:I,defaultRenderer:()=>ms(I,r),config:r})}else Pe.renderMessage&&(ne=Pe.renderMessage({message:I,defaultRenderer:()=>{let it=Zr(I,y,rt,r.messageActions,at,{loadingIndicatorRenderer:L,widgetConfig:r});return I.role!=="user"&&ys(it,I,r,H),it},config:r}));if(!ne&&I.role==="assistant"&&!I.variant&&r.enableComponentStreaming!==!1&&As(I)){let Gt=Es(I);if(Gt){let jt=Ss(Gt,{config:r,message:I,transform:y});if(jt)if(r.wrapComponentDirectiveInBubble!==!1){let $t=document.createElement("div");if($t.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",sn.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(sn)}$t.appendChild(jt),ne=$t}else{let $t=document.createElement("div");if($t.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",$t.id=`bubble-${I.id}`,$t.setAttribute("data-message-id",I.id),$t.setAttribute("data-persona-component-directive","true"),I.content&&I.content.trim()){let sn=document.createElement("div");sn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",sn.innerHTML=y({text:I.content,message:I,streaming:!!I.streaming,raw:I.rawContent}),$t.appendChild(sn)}$t.appendChild(jt),ne=$t}}}if(!ne)if(I.variant==="reasoning"&&I.reasoning){if(!z)return;ne=us(I)}else if(I.variant==="tool"&&I.toolCall){if(!ge)return;ne=gs(I,r)}else if(I.variant==="approval"&&I.approval){if(r.approval===!1)return;ne=ms(I,r)}else{let it=(Pt=r.layout)==null?void 0:Pt.messages;it!=null&&it.renderUserMessage&&I.role==="user"?ne=it.renderUserMessage({message:I,config:r,streaming:!!I.streaming}):it!=null&&it.renderAssistantMessage&&I.role==="assistant"?ne=it.renderAssistantMessage({message:I,config:r,streaming:!!I.streaming}):ne=Zr(I,y,it,r.messageActions,at,{loadingIndicatorRenderer:L,widgetConfig:r}),I.role!=="user"&&ne&&ys(ne,I,r,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${I.id}`,Ke.setAttribute("data-wrapper-id",I.id),I.role==="user"&&Ke.classList.add("persona-justify-end"),(ne==null?void 0:ne.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(ne),Cl(Hn,I.id,Te,Ke),S.appendChild(Ke)}),wl(Hn,P);let V=u.some(I=>I.role==="assistant"&&I.streaming),$=u[u.length-1],se=($==null?void 0:$.role)==="assistant"&&!$.streaming&&$.variant!=="approval";if(Rn&&u.some(I=>I.role==="user")&&!V&&!se){let I={config:r,streaming:!0,location:"standalone",defaultRenderer:mr},Te=s.find(ne=>ne.renderLoadingIndicator),Ee=null;if(Te!=null&&Te.renderLoadingIndicator&&(Ee=Te.renderLoadingIndicator(I)),Ee===null&&((fe=r.loadingIndicator)!=null&&fe.render)&&(Ee=r.loadingIndicator.render(I)),Ee===null&&(Ee=mr()),Ee){let ne=document.createElement("div"),Pe=((ke=r.loadingIndicator)==null?void 0:ke.showBubble)!==!1;ne.className=Pe?["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(" "),ne.setAttribute("data-typing-indicator","true"),ne.appendChild(Ee);let rt=document.createElement("div");rt.className="persona-flex",rt.id="wrapper-typing-indicator",rt.setAttribute("data-wrapper-id","typing-indicator"),rt.appendChild(ne),S.appendChild(rt)}}if(!Rn&&u.length>0){let I=u[u.length-1],Te={config:r,lastMessage:I,messageCount:u.length},Ee=s.find(Pe=>Pe.renderIdleIndicator),ne=null;if(Ee!=null&&Ee.renderIdleIndicator&&(ne=Ee.renderIdleIndicator(Te)),ne===null&&((Ne=r.loadingIndicator)!=null&&Ne.renderIdle)&&(ne=r.loadingIndicator.renderIdle(Te)),ne){let Pe=document.createElement("div"),rt=((Ae=r.loadingIndicator)==null?void 0:Ae.showBubble)!==!1;Pe.className=rt?["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(" "),Pe.setAttribute("data-idle-indicator","true"),Pe.appendChild(ne);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(Pe),S.appendChild(Ke)}}yl(l,S),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let I=co();po(I)})})},rr=()=>{if(!v)return;let l=Jt(r);w?(de.style.display=l?"flex":"",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-95","persona-opacity-0"),ie.classList.add("persona-scale-100","persona-opacity-100"),we?we.element.style.display="none":$e&&($e.style.display="none")):(l?(de.style.display="none",de.classList.remove("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(de.style.display="",de.classList.add("persona-pointer-events-none","persona-opacity-0"),ie.classList.remove("persona-scale-100","persona-opacity-100"),ie.classList.add("persona-scale-95","persona-opacity-0")),we?we.element.style.display="":$e&&($e.style.display=""))},gt=(l,u="user")=>{if(!v||w===l)return;let y=w;w=l,rr(),w&&(vt(),_n(!0));let S={open:w,source:u,timestamp:Date.now()};w&&!y?o.emit("widget:opened",S):!w&&y&&o.emit("widget:closed",S),o.emit("widget:state",{open:w,launcherEnabled:v,voiceActive:Ue.active,streaming:H.isStreaming()})},or=l=>{K.disabled=l,B&&(B.disabled=l),Wn.buttons.forEach(u=>{u.disabled=l}),Ze.dataset.personaComposerStreaming=l?"true":"false",Ze.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(u=>{(u instanceof HTMLButtonElement||u instanceof HTMLInputElement||u instanceof HTMLTextAreaElement||u instanceof HTMLSelectElement)&&(u.disabled=l)})},sr=()=>{Ue.active||X&&X.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>sr(),200)});let Pr=()=>{var R,L,P,V,$,se,fe,ke,Ne,Ae,I,Te,Ee,ne;Tt.textContent=(L=(R=r.copy)==null?void 0:R.welcomeTitle)!=null?L:"Hello \u{1F44B}",_t.textContent=(V=(P=r.copy)==null?void 0:P.welcomeSubtitle)!=null?V:"Ask anything about your account or products.",X.placeholder=(se=($=r.copy)==null?void 0:$.inputPlaceholder)!=null?se:"How can I help...",(ke=(fe=r.sendButton)==null?void 0:fe.useIcon)!=null&&ke||(K.textContent=(Ae=(Ne=r.copy)==null?void 0:Ne.sendButtonLabel)!=null?Ae:"Send");let u=(Te=(I=r.theme)==null?void 0:I.inputFontFamily)!=null?Te:"sans-serif",y=(ne=(Ee=r.theme)==null?void 0:Ee.inputFontWeight)!=null?ne:"400",S=Pe=>{switch(Pe){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'}};X.style.fontFamily=S(u),X.style.fontWeight=y};if(r.clientToken&&(r={...r,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(u=>({...u,sessionId:l}))}}),H=new zr(r,{onMessagesChanged(l){jn(be,l,ae),H&&(l.some(R=>R.role==="user")?Wn.render([],H,X,l):Wn.render(r.suggestionChips,H,X,l,r.suggestionChipsConfig)),_n(!Rn),uo(l);let u=[...l].reverse().find(S=>S.role==="user"),y=Ue.lastUserMessageId;u&&u.id!==y&&(Ue.lastUserMessageId=u.id,o.emit("user:message",u)),Ue.lastUserMessageWasVoice=!!(u!=null&&u.viaVoice),Lr(l)},onStatusChanged(l){var S;let u=(S=r.statusIndicator)!=null?S:{},y=R=>{var L,P,V,$;return R==="idle"?(L=u.idleText)!=null?L:Vt.idle:R==="connecting"?(P=u.connectingText)!=null?P:Vt.connecting:R==="connected"?(V=u.connectedText)!=null?V:Vt.connected:R==="error"?($=u.errorText)!=null?$:Vt.error:Vt[R]};Ve.textContent=y(l)},onStreamingChanged(l){Rn=l,or(l),H&&jn(be,H.getMessages(),ae),l||_n(!0)},onVoiceStatusChanged(l){var u,y;if(((y=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":dn(),mo();break;case"speaking":dn(),fo();break;default:l==="idle"&&H.isBargeInActive()?(dn(),Bn(),B==null||B.setAttribute("aria-label","End voice session")):(Ue.active=!1,dn(),rn("system"),Kt());break}},onArtifactsState(l){In=l,hn()}}),Cr.current=H,((Zs=(Xs=r.voiceRecognition)==null?void 0:Xs.provider)==null?void 0:Zs.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}r.clientToken&&H.initClientSession().catch(l=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),D&&H.setSSEEventCallback((l,u)=>{D==null||D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(u)})}),d&&d.then(l=>{var u;l&&(l.metadata&&(i=ks(l.metadata),C.syncFromMetadata()),(u=l.messages)!=null&&u.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Ir=l=>{var R;l.preventDefault();let u=X.value.trim(),y=(R=He==null?void 0:He.hasAttachments())!=null?R:!1;if(!u&&!y)return;let S;y&&(S=[],S.push(...He.getContentParts()),u&&S.push(ns(u))),X.value="",X.style.height="auto",H.sendMessage(u,{contentParts:S}),y&&He.clearAttachments()},Wr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),K.click())},Rr=async l=>{var y;if(((y=r.attachments)==null?void 0:y.enabled)!==!0||!He)return;let u=Zd(l.clipboardData);u.length!==0&&(l.preventDefault(),await He.handleFiles(u))},Ut=null,Qt=!1,Mn=null,Re=null,Hr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Vn=(l="user")=>{var L,P,V,$,se,fe,ke,Ne;if(Qt||H.isStreaming())return;let u=Hr();if(!u)return;Ut=new u;let S=(P=((L=r.voiceRecognition)!=null?L:{}).pauseDuration)!=null?P:2e3;Ut.continuous=!0,Ut.interimResults=!0,Ut.lang="en-US";let R=X.value;Ut.onresult=Ae=>{let I="",Te="";for(let ne=0;ne<Ae.results.length;ne++){let Pe=Ae.results[ne],rt=Pe[0].transcript;Pe.isFinal?I+=rt+" ":Te=rt}let Ee=R+I+Te;X.value=Ee,Mn&&clearTimeout(Mn),(I||Te)&&(Mn=window.setTimeout(()=>{let ne=X.value.trim();ne&&Ut&&Qt&&(cn(),X.value="",X.style.height="auto",H.sendMessage(ne,{viaVoice:!0}))},S))},Ut.onerror=Ae=>{Ae.error!=="no-speech"&&cn()},Ut.onend=()=>{if(Qt){let Ae=X.value.trim();Ae&&Ae!==R.trim()&&(X.value="",X.style.height="auto",H.sendMessage(Ae,{viaVoice:!0})),cn()}};try{if(Ut.start(),Qt=!0,Ue.active=!0,l!=="system"&&(Ue.manuallyDeactivated=!1),rn(l),Kt(),B){let Ae=(V=r.voiceRecognition)!=null?V:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:($=Ae.iconName)!=null?$:"mic",iconSize:parseFloat((ke=(fe=Ae.iconSize)!=null?fe:(se=r.sendButton)==null?void 0:se.size)!=null?ke:"40")||24};let I=(Ne=Ae.recordingBackgroundColor)!=null?Ne:"#ef4444",Te=Ae.recordingIconColor,Ee=Ae.recordingBorderColor;if(B.classList.add("persona-voice-recording"),B.style.backgroundColor=I,Te){B.style.color=Te;let ne=B.querySelector("svg");ne&&ne.setAttribute("stroke",Te)}Ee&&(B.style.borderColor=Ee),B.setAttribute("aria-label","Stop voice recognition")}}catch{cn("system")}},cn=(l="user")=>{if(Qt){if(Qt=!1,Mn&&(clearTimeout(Mn),Mn=null),Ut){try{Ut.stop()}catch{}Ut=null}if(Ue.active=!1,rn(l),Kt(),B){if(B.classList.remove("persona-voice-recording"),Re){B.style.backgroundColor=Re.backgroundColor,B.style.color=Re.color,B.style.borderColor=Re.borderColor;let u=B.querySelector("svg");u&&u.setAttribute("stroke",Re.color||"currentColor"),Re=null}B.setAttribute("aria-label","Start voice recognition")}}},go=(l,u)=>{var ne,Pe,rt,Ke,pe,Pt,it,Gt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),S=((ne=l==null?void 0:l.provider)==null?void 0:ne.type)==="runtype";if(!(y||S))return null;let L=h("div","persona-send-button-wrapper"),P=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");P.type="button",P.setAttribute("aria-label","Start voice recognition");let V=(Pe=l==null?void 0:l.iconName)!=null?Pe:"mic",$=(rt=u==null?void 0:u.size)!=null?rt:"40px",se=(Ke=l==null?void 0:l.iconSize)!=null?Ke:$,fe=parseFloat(se)||24,ke=(pe=l==null?void 0:l.backgroundColor)!=null?pe:u==null?void 0:u.backgroundColor,Ne=(Pt=l==null?void 0:l.iconColor)!=null?Pt:u==null?void 0:u.textColor;P.style.width=se,P.style.height=se,P.style.minWidth=se,P.style.minHeight=se,P.style.fontSize="18px",P.style.lineHeight="1";let Ae=Ne||"currentColor",I=me(V,fe,Ae,1.5);I?(P.appendChild(I),P.style.color=Ae):(P.textContent="\u{1F3A4}",P.style.color=Ae),ke?P.style.backgroundColor=ke:P.classList.add("persona-bg-persona-primary"),Ne?P.style.color=Ne:!Ne&&!(u!=null&&u.textColor)&&P.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(P.style.borderWidth=l.borderWidth,P.style.borderStyle="solid"),l!=null&&l.borderColor&&(P.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(P.style.paddingLeft=l.paddingX,P.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(P.style.paddingTop=l.paddingY,P.style.paddingBottom=l.paddingY),L.appendChild(P);let Te=(it=l==null?void 0:l.tooltipText)!=null?it:"Start voice recognition";if(((Gt=l==null?void 0:l.showTooltip)!=null?Gt:!1)&&Te){let jt=h("div","persona-send-button-tooltip");jt.textContent=Te,L.appendChild(jt)}return{micButton:P,micButtonWrapper:L}},ar=()=>{var u,y,S,R,L;if(!B||Re)return;let l=(u=r.voiceRecognition)!=null?u:{};Re={backgroundColor:B.style.backgroundColor,color:B.style.color,borderColor:B.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((L=(R=l.iconSize)!=null?R:(S=r.sendButton)==null?void 0:S.size)!=null?L:"40")||24}},ir=(l,u)=>{var L,P,V,$,se;if(!B)return;let y=B.querySelector("svg");y&&y.remove();let S=(se=Re==null?void 0:Re.iconSize)!=null?se:parseFloat(($=(V=(L=r.voiceRecognition)==null?void 0:L.iconSize)!=null?V:(P=r.sendButton)==null?void 0:P.size)!=null?$:"40")||24,R=me(l,S,u,1.5);R&&B.appendChild(R)},Un=()=>{B&&B.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Bn=()=>{var R,L;if(!B)return;ar();let l=(R=r.voiceRecognition)!=null?R:{},u=(L=l.recordingBackgroundColor)!=null?L:"#ef4444",y=l.recordingIconColor,S=l.recordingBorderColor;if(Un(),B.classList.add("persona-voice-recording"),B.style.backgroundColor=u,y){B.style.color=y;let P=B.querySelector("svg");P&&P.setAttribute("stroke",y)}S&&(B.style.borderColor=S),B.setAttribute("aria-label","Stop voice recognition")},mo=()=>{var V,$,se,fe,ke,Ne,Ae,I;if(!B)return;ar();let l=(V=r.voiceRecognition)!=null?V:{},u=H.getVoiceInterruptionMode(),y=($=l.processingIconName)!=null?$:"loader",S=(fe=(se=l.processingIconColor)!=null?se:Re==null?void 0:Re.color)!=null?fe:"",R=(Ne=(ke=l.processingBackgroundColor)!=null?ke:Re==null?void 0:Re.backgroundColor)!=null?Ne:"",L=(I=(Ae=l.processingBorderColor)!=null?Ae:Re==null?void 0:Re.borderColor)!=null?I:"";Un(),B.classList.add("persona-voice-processing"),B.style.backgroundColor=R,B.style.borderColor=L;let P=S||"currentColor";B.style.color=P,ir(y,P),B.setAttribute("aria-label","Processing voice input"),u==="none"&&(B.style.cursor="default")},fo=()=>{var se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke;if(!B)return;ar();let l=(se=r.voiceRecognition)!=null?se:{},u=H.getVoiceInterruptionMode(),y=u==="cancel"?"square":u==="barge-in"?"mic":"volume-2",S=(fe=l.speakingIconName)!=null?fe:y,R=(I=l.speakingIconColor)!=null?I:u==="barge-in"?(Ne=(ke=l.recordingIconColor)!=null?ke:Re==null?void 0:Re.color)!=null?Ne:"":(Ae=Re==null?void 0:Re.color)!=null?Ae:"",L=(ne=l.speakingBackgroundColor)!=null?ne:u==="barge-in"?(Te=l.recordingBackgroundColor)!=null?Te:"#ef4444":(Ee=Re==null?void 0:Re.backgroundColor)!=null?Ee:"",P=(Ke=l.speakingBorderColor)!=null?Ke:u==="barge-in"?(Pe=l.recordingBorderColor)!=null?Pe:"":(rt=Re==null?void 0:Re.borderColor)!=null?rt:"";Un(),B.classList.add("persona-voice-speaking"),B.style.backgroundColor=L,B.style.borderColor=P;let V=R||"currentColor";B.style.color=V,ir(S,V);let $=u==="cancel"?"Stop playback and re-record":u==="barge-in"?"Speak to interrupt":"Agent is speaking";B.setAttribute("aria-label",$),u==="none"&&(B.style.cursor="default"),u==="barge-in"&&B.classList.add("persona-voice-recording")},dn=()=>{var l,u,y;B&&(Un(),Re&&(B.style.backgroundColor=(l=Re.backgroundColor)!=null?l:"",B.style.color=(u=Re.color)!=null?u:"",B.style.borderColor=(y=Re.borderColor)!=null?y:"",ir(Re.iconName,Re.color||"currentColor"),Re=null),B.style.cursor="",B.setAttribute("aria-label","Start voice recognition"))},qn=()=>{var l,u;if(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"){let y=H.getVoiceStatus(),S=H.getVoiceInterruptionMode();if(S==="none"&&(y==="processing"||y==="speaking"))return;if(S==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ue.active=!1,Ue.manuallyDeactivated=!0,Kt(),rn("user"),dn()});return}H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),Ue.manuallyDeactivated=!H.isVoiceActive(),Kt(),rn("user"),H.isVoiceActive()?Bn():dn()});return}if(Qt){let y=X.value.trim();Ue.manuallyDeactivated=!0,Kt(),cn("user"),y&&(X.value="",X.style.height="auto",H.sendMessage(y))}else Ue.manuallyDeactivated=!1,Kt(),Vn("user")};pt=qn,B&&(B.addEventListener("click",qn),xt.push(()=>{var l,u;((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),dn()):cn("system"),B&&B.removeEventListener("click",qn)}));let ho=o.on("assistant:complete",()=>{kr&&(Ue.active||Ue.manuallyDeactivated||kr==="assistant"&&!Ue.lastUserMessageWasVoice||setTimeout(()=>{var l,u;!Ue.active&&!Ue.manuallyDeactivated&&(((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("auto"),H.isVoiceActive()&&Bn()}):Vn("auto"))},600))});xt.push(ho);let Q=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});xt.push(Q);let Fe=()=>{gt(!w,"user")},we=null,$e=null;if(v){let l=s.find(u=>u.renderLauncher);if(l!=null&&l.renderLauncher){let u=l.renderLauncher({config:r,defaultRenderer:()=>Yr(r,Fe).element,onToggle:Fe});u&&($e=u)}$e||(we=Yr(r,Fe))}we?e.appendChild(we.element):$e&&e.appendChild($e),rr(),Wn.render(r.suggestionChips,H,X,void 0,r.suggestionChipsConfig),Pr(),or(H.isStreaming()),_n(!0),io(),x&&(v?w&&setTimeout(()=>sr(),200):setTimeout(()=>sr(),0));let vt=()=>{var $,se,fe,ke,Ne,Ae,I,Te,Ee,ne,Pe,rt,Ke;let l=Jt(r),u=(se=($=r.launcher)==null?void 0:$.sidebarMode)!=null?se:!1,y=l||u||((ke=(fe=r.launcher)==null?void 0:fe.fullHeight)!=null?ke:!1),S=(Ne=e.ownerDocument.defaultView)!=null?Ne:window,R=(I=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?I:!0,L=(Ee=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?Ee:640,P=S.innerWidth<=L;if(R&&P&&v){On(),Xn(e,r);return}if(N&&(N=!1,On(),Xn(e,r)),!v&&!l){ie.style.height="",ie.style.width="";return}if(!u&&!l){let pe=(Pe=(ne=r==null?void 0:r.launcher)==null?void 0:ne.width)!=null?Pe:r==null?void 0:r.launcherWidth,Pt=pe!=null?pe:"min(400px, calc(100vw - 24px))";ie.style.width=Pt,ie.style.maxWidth=Pt}if(Nn(),!y){let pe=S.innerHeight,Pt=64,it=(Ke=(rt=r.launcher)==null?void 0:rt.heightOffset)!=null?Ke:0,Gt=Math.max(200,pe-Pt),jt=Math.min(640,Gt),qt=Math.max(200,jt-it);ie.style.height=`${qt}px`}};vt();let Ot=(Qs=e.ownerDocument.defaultView)!=null?Qs:window;Ot.addEventListener("resize",vt),xt.push(()=>Ot.removeEventListener("resize",vt)),Dn=G.scrollTop;let Ct=()=>{let l=G.scrollTop,u=G.scrollHeight,y=G.clientHeight,S=u-l-y,R=Math.abs(l-Dn);if(Dn=l,!tr&&!(R<=ao)){if(!Sn&&S<Mr){En=!1,Sn=!0;return}Sn&&S>Mr&&(En=!0,er=Date.now()+so,Sn=!1)}};G.addEventListener("scroll",Ct,{passive:!0}),xt.push(()=>G.removeEventListener("scroll",Ct)),xt.push(()=>{An&&cancelAnimationFrame(An)});let b=()=>{ce&&(bn&&(ce.removeEventListener("click",bn),bn=null),v?(ce.style.display="",bn=()=>{gt(!1,"user")},ce.addEventListener("click",bn)):ce.style.display="none")};b(),(()=>{let{clearChatButton:l}=qe;l&&l.addEventListener("click",()=>{H.clearMessages(),Hn.clear();try{localStorage.removeItem(xr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xr)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 u=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(u),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={},C.syncFromMetadata(),D==null||D.clear(),U==null||U.update()})})(),We&&We.addEventListener("submit",Ir),X==null||X.addEventListener("keydown",Wr),X==null||X.addEventListener("paste",Rr),xt.push(()=>{We&&We.removeEventListener("submit",Ir),X==null||X.removeEventListener("keydown",Wr),X==null||X.removeEventListener("paste",Rr)}),xt.push(()=>{H.cancel()}),we?xt.push(()=>{we==null||we.destroy()}):$e&&xt.push(()=>{$e==null||$e.remove()});let T={update(l){var aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,Fa,$a,Na,Oa,Da,_a,ja,Va,Ua,qa,za,Ja,Ka,Ya,Ga,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Fi,$i,Ni,Oi,Di,_i,ji,Vi,Ui,qi,zi;let u=r.toolCall,y=r.messageActions,S=(aa=r.layout)==null?void 0:aa.messages,R=r.colorScheme,L=r.loadingIndicator,P=r.iterationDisplay;r={...r,...l},On(),Xn(e,r),Ho(e,r),Bo(e,r),hn(),r.colorScheme!==R&&Ar();let V=Fo.getForInstance(r.plugins);s.length=0,s.push(...V),v=(la=(ia=r.launcher)==null?void 0:ia.enabled)!=null?la:!0,E=(da=(ca=r.launcher)==null?void 0:ca.autoExpand)!=null?da:!1,z=(ua=(pa=r.features)==null?void 0:pa.showReasoning)!=null?ua:!0,ge=(ma=(ga=r.features)==null?void 0:ga.showToolCalls)!=null?ma:!0;let $=Ie;if(Ie=(ha=(fa=r.features)==null?void 0:fa.showEventStreamToggle)!=null?ha:!1,Ie&&!$){if(D||(ee=new eo(ye),D=new Qr(te,ee),ee.open().then(()=>D==null?void 0:D.restore()).catch(()=>{}),H.setSSEEventCallback((O,Ye)=>{D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:O,timestamp:Date.now(),payload:JSON.stringify(Ye)})})),!ue&&je){let O=(ba=(ya=r.features)==null?void 0:ya.eventStream)==null?void 0:ba.classNames,Ye="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(O!=null&&O.toggleButton?" "+O.toggleButton:"");ue=h("button",Ye),ue.style.width="28px",ue.style.height="28px",ue.type="button",ue.setAttribute("aria-label","Event Stream"),ue.title="Event Stream";let mt=me("activity","18px","currentColor",1.5);mt&&ue.appendChild(mt);let Oe=qe.clearChatButtonWrapper,et=qe.closeButtonWrapper,It=Oe||et;It&&It.parentNode===je?je.insertBefore(ue,It):je.appendChild(ue),ue.addEventListener("click",()=>{oe?Be():Ce()})}}else!Ie&&$&&(Be(),ue&&(ue.remove(),ue=null),D==null||D.clear(),ee==null||ee.destroy(),D=null,ee=null);if(((xa=r.launcher)==null?void 0:xa.enabled)===!1&&we&&(we.destroy(),we=null),((va=r.launcher)==null?void 0:va.enabled)===!1&&$e&&($e.remove(),$e=null),((Ca=r.launcher)==null?void 0:Ca.enabled)!==!1&&!we&&!$e){let O=s.find(Ye=>Ye.renderLauncher);if(O!=null&&O.renderLauncher){let Ye=O.renderLauncher({config:r,defaultRenderer:()=>Yr(r,Fe).element,onToggle:Fe});Ye&&($e=Ye,e.appendChild($e))}$e||(we=Yr(r,Fe),e.appendChild(we.element))}we&&we.update(r),Me&&((wa=r.launcher)==null?void 0:wa.title)!==void 0&&(Me.textContent=r.launcher.title),nt&&((Sa=r.launcher)==null?void 0:Sa.subtitle)!==void 0&&(nt.textContent=r.launcher.subtitle);let se=(Aa=r.layout)==null?void 0:Aa.header;if((se==null?void 0:se.layout)!==M&&je){let O=se?Gr(r,se,{showClose:v,onClose:()=>gt(!1,"user")}):Fn({config:r,showClose:v,onClose:()=>gt(!1,"user")});je.replaceWith(O.header),je=O.header,Je=O.iconHolder,Me=O.headerTitle,nt=O.headerSubtitle,ce=O.closeButton,M=se==null?void 0:se.layout}else if(se&&(Je&&(Je.style.display=se.showIcon===!1?"none":""),Me&&(Me.style.display=se.showTitle===!1?"none":""),nt&&(nt.style.display=se.showSubtitle===!1?"none":""),ce&&(ce.style.display=se.showCloseButton===!1?"none":""),qe.clearChatButtonWrapper)){let O=se.showClearChat;if(O!==void 0){qe.clearChatButtonWrapper.style.display=O?"":"none";let{closeButtonWrapper:Ye}=qe;Ye&&!Ye.classList.contains("persona-absolute")&&(O?Ye.classList.remove("persona-ml-auto"):Ye.classList.add("persona-ml-auto"))}}let ke=((Ea=r.layout)==null?void 0:Ea.showHeader)!==!1;je&&(je.style.display=ke?"":"none");let Ne=((Ta=r.layout)==null?void 0:Ta.showFooter)!==!1;Ze&&(Ze.style.display=Ne?"":"none"),v!==q?v?gt(E,"auto"):(w=!0,rr()):E!==k&&gt(E,"auto"),k=E,q=v,vt(),b();let Te=JSON.stringify(l.toolCall)!==JSON.stringify(u),Ee=JSON.stringify(r.messageActions)!==JSON.stringify(y),ne=JSON.stringify((Ma=r.layout)==null?void 0:Ma.messages)!==JSON.stringify(S),Pe=((ka=r.loadingIndicator)==null?void 0:ka.render)!==(L==null?void 0:L.render)||((La=r.loadingIndicator)==null?void 0:La.renderIdle)!==(L==null?void 0:L.renderIdle)||((Pa=r.loadingIndicator)==null?void 0:Pa.showBubble)!==(L==null?void 0:L.showBubble),rt=r.iterationDisplay!==P;(Te||Ee||ne||Pe||rt)&&H&&(Er++,jn(be,H.getMessages(),ae));let pe=(Ia=r.launcher)!=null?Ia:{},Pt=(Wa=pe.headerIconHidden)!=null?Wa:!1,it=(Ha=(Ra=r.layout)==null?void 0:Ra.header)==null?void 0:Ha.showIcon,Gt=Pt||it===!1,jt=pe.headerIconName,qt=(Ba=pe.headerIconSize)!=null?Ba:"48px";if(Je){let O=j.querySelector(".persona-border-b-persona-divider"),Ye=O==null?void 0:O.querySelector(".persona-flex-col");if(Gt)Je.style.display="none",O&&Ye&&!O.contains(Ye)&&O.insertBefore(Ye,O.firstChild);else{if(Je.style.display="",Je.style.height=qt,Je.style.width=qt,O&&Ye&&(O.contains(Je)?Je.nextSibling!==Ye&&(Je.remove(),O.insertBefore(Je,Ye)):O.insertBefore(Je,Ye)),jt){let Oe=parseFloat(qt)||24,et=me(jt,Oe*.6,"#ffffff",2);et?Je.replaceChildren(et):Je.textContent=(Fa=pe.agentIconText)!=null?Fa:"\u{1F4AC}"}else if(pe.iconUrl){let Oe=Je.querySelector("img");if(Oe)Oe.src=pe.iconUrl,Oe.style.height=qt,Oe.style.width=qt;else{let et=document.createElement("img");et.src=pe.iconUrl,et.alt="",et.className="persona-rounded-xl persona-object-cover",et.style.height=qt,et.style.width=qt,Je.replaceChildren(et)}}else{let Oe=Je.querySelector("svg"),et=Je.querySelector("img");(Oe||et)&&Je.replaceChildren(),Je.textContent=($a=pe.agentIconText)!=null?$a:"\u{1F4AC}"}let mt=Je.querySelector("img");mt&&(mt.style.height=qt,mt.style.width=qt)}}let $t=(Oa=(Na=r.layout)==null?void 0:Na.header)==null?void 0:Oa.showTitle,sn=(_a=(Da=r.layout)==null?void 0:Da.header)==null?void 0:_a.showSubtitle;if(Me&&(Me.style.display=$t===!1?"none":""),nt&&(nt.style.display=sn===!1?"none":""),ce){((Va=(ja=r.layout)==null?void 0:ja.header)==null?void 0:Va.showCloseButton)===!1?ce.style.display="none":ce.style.display="";let Ye=(Ua=pe.closeButtonSize)!=null?Ua:"32px",mt=(qa=pe.closeButtonPlacement)!=null?qa:"inline";ce.style.height=Ye,ce.style.width=Ye;let{closeButtonWrapper:Oe}=qe,et=mt==="top-right",It=Oe==null?void 0:Oe.classList.contains("persona-absolute");if(Oe&&et!==It)if(Oe.remove(),et)Oe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",j.style.position="relative",j.appendChild(Oe);else{let Ge=(Ja=(za=pe.clearChat)==null?void 0:za.placement)!=null?Ja:"inline",Nt=(Ya=(Ka=pe.clearChat)==null?void 0:Ka.enabled)!=null?Ya:!0;Oe.className=Nt&&Ge==="inline"?"":"persona-ml-auto";let Xt=j.querySelector(".persona-border-b-persona-divider");Xt&&Xt.appendChild(Oe)}if(pe.closeButtonColor?(ce.style.color=pe.closeButtonColor,ce.classList.remove("persona-text-persona-muted")):(ce.style.color="",ce.classList.add("persona-text-persona-muted")),pe.closeButtonBackgroundColor?(ce.style.backgroundColor=pe.closeButtonBackgroundColor,ce.classList.remove("hover:persona-bg-gray-100")):(ce.style.backgroundColor="",ce.classList.add("hover:persona-bg-gray-100")),pe.closeButtonBorderWidth||pe.closeButtonBorderColor){let Ge=pe.closeButtonBorderWidth||"0px",Nt=pe.closeButtonBorderColor||"transparent";ce.style.border=`${Ge} solid ${Nt}`,ce.classList.remove("persona-border-none")}else ce.style.border="",ce.classList.add("persona-border-none");pe.closeButtonBorderRadius?(ce.style.borderRadius=pe.closeButtonBorderRadius,ce.classList.remove("persona-rounded-full")):(ce.style.borderRadius="",ce.classList.add("persona-rounded-full")),pe.closeButtonPaddingX?(ce.style.paddingLeft=pe.closeButtonPaddingX,ce.style.paddingRight=pe.closeButtonPaddingX):(ce.style.paddingLeft="",ce.style.paddingRight=""),pe.closeButtonPaddingY?(ce.style.paddingTop=pe.closeButtonPaddingY,ce.style.paddingBottom=pe.closeButtonPaddingY):(ce.style.paddingTop="",ce.style.paddingBottom="");let Dt=(Ga=pe.closeButtonIconName)!=null?Ga:"x",en=(Xa=pe.closeButtonIconText)!=null?Xa:"\xD7";ce.innerHTML="";let zt=me(Dt,"20px",pe.closeButtonColor||"",2);zt?ce.appendChild(zt):ce.textContent=en;let St=(Za=pe.closeButtonTooltipText)!=null?Za:"Close chat",tn=(Qa=pe.closeButtonShowTooltip)!=null?Qa:!0;if(ce.setAttribute("aria-label",St),Oe&&(Oe._cleanupTooltip&&(Oe._cleanupTooltip(),delete Oe._cleanupTooltip),tn&&St)){let Ge=null,Nt=()=>{if(Ge||!ce)return;let Kn=ce.ownerDocument,Or=Kn.body;if(!Or)return;Ge=vn(Kn,"div","persona-clear-chat-tooltip"),Ge.textContent=St;let Dr=vn(Kn,"div");Dr.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(Dr);let Yn=ce.getBoundingClientRect();Ge.style.position="fixed",Ge.style.left=`${Yn.left+Yn.width/2}px`,Ge.style.top=`${Yn.top-8}px`,Ge.style.transform="translate(-50%, -100%)",Or.appendChild(Ge)},Xt=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};Oe.addEventListener("mouseenter",Nt),Oe.addEventListener("mouseleave",Xt),ce.addEventListener("focus",Nt),ce.addEventListener("blur",Xt),Oe._cleanupTooltip=()=>{Xt(),Oe&&(Oe.removeEventListener("mouseenter",Nt),Oe.removeEventListener("mouseleave",Xt)),ce&&(ce.removeEventListener("focus",Nt),ce.removeEventListener("blur",Xt))}}}let{clearChatButton:_e,clearChatButtonWrapper:yt}=qe;if(_e){let O=(ei=pe.clearChat)!=null?ei:{},Ye=(ti=O.enabled)!=null?ti:!0,mt=(ri=(ni=r.layout)==null?void 0:ni.header)==null?void 0:ri.showClearChat,Oe=mt!==void 0?mt:Ye,et=(oi=O.placement)!=null?oi:"inline";if(yt){yt.style.display=Oe?"":"none";let{closeButtonWrapper:It}=qe;It&&!It.classList.contains("persona-absolute")&&(Oe?It.classList.remove("persona-ml-auto"):It.classList.add("persona-ml-auto"));let Dt=et==="top-right",en=yt.classList.contains("persona-absolute");if(Dt!==en&&Oe){if(yt.remove(),Dt)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",j.style.position="relative",j.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let St=j.querySelector(".persona-border-b-persona-divider"),tn=qe.closeButtonWrapper;St&&tn&&tn.parentElement===St?St.insertBefore(yt,tn):St&&St.appendChild(yt)}let zt=qe.closeButtonWrapper;zt&&!zt.classList.contains("persona-absolute")&&(Dt?zt.classList.add("persona-ml-auto"):zt.classList.remove("persona-ml-auto"))}}if(Oe){let It=(si=O.size)!=null?si:"32px";_e.style.height=It,_e.style.width=It;let Dt=(ai=O.iconName)!=null?ai:"refresh-cw",en=(ii=O.iconColor)!=null?ii:"";_e.innerHTML="";let zt=me(Dt,"20px",en||"",2);if(zt&&_e.appendChild(zt),en?(_e.style.color=en,_e.classList.remove("persona-text-persona-muted")):(_e.style.color="",_e.classList.add("persona-text-persona-muted")),O.backgroundColor?(_e.style.backgroundColor=O.backgroundColor,_e.classList.remove("hover:persona-bg-gray-100")):(_e.style.backgroundColor="",_e.classList.add("hover:persona-bg-gray-100")),O.borderWidth||O.borderColor){let Ge=O.borderWidth||"0px",Nt=O.borderColor||"transparent";_e.style.border=`${Ge} solid ${Nt}`,_e.classList.remove("persona-border-none")}else _e.style.border="",_e.classList.add("persona-border-none");O.borderRadius?(_e.style.borderRadius=O.borderRadius,_e.classList.remove("persona-rounded-full")):(_e.style.borderRadius="",_e.classList.add("persona-rounded-full")),O.paddingX?(_e.style.paddingLeft=O.paddingX,_e.style.paddingRight=O.paddingX):(_e.style.paddingLeft="",_e.style.paddingRight=""),O.paddingY?(_e.style.paddingTop=O.paddingY,_e.style.paddingBottom=O.paddingY):(_e.style.paddingTop="",_e.style.paddingBottom="");let St=(li=O.tooltipText)!=null?li:"Clear chat",tn=(ci=O.showTooltip)!=null?ci:!0;if(_e.setAttribute("aria-label",St),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),tn&&St)){let Ge=null,Nt=()=>{if(Ge||!_e)return;let Kn=_e.ownerDocument,Or=Kn.body;if(!Or)return;Ge=vn(Kn,"div","persona-clear-chat-tooltip"),Ge.textContent=St;let Dr=vn(Kn,"div");Dr.className="persona-clear-chat-tooltip-arrow",Ge.appendChild(Dr);let Yn=_e.getBoundingClientRect();Ge.style.position="fixed",Ge.style.left=`${Yn.left+Yn.width/2}px`,Ge.style.top=`${Yn.top-8}px`,Ge.style.transform="translate(-50%, -100%)",Or.appendChild(Ge)},Xt=()=>{Ge&&Ge.parentNode&&(Ge.parentNode.removeChild(Ge),Ge=null)};yt.addEventListener("mouseenter",Nt),yt.addEventListener("mouseleave",Xt),_e.addEventListener("focus",Nt),_e.addEventListener("blur",Xt),yt._cleanupTooltip=()=>{Xt(),yt&&(yt.removeEventListener("mouseenter",Nt),yt.removeEventListener("mouseleave",Xt)),_e&&(_e.removeEventListener("focus",Nt),_e.removeEventListener("blur",Xt))}}}}let yo=r.actionParsers&&r.actionParsers.length?r.actionParsers:[$o],bo=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[br.message,br.messageAndClick];C=No({parsers:yo,handlers:bo,getSessionMetadata:g,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),ae=Yl(r,C,Y),H.updateConfig(r),jn(be,H.getMessages(),ae),Wn.render(r.suggestionChips,H,X,void 0,r.suggestionChipsConfig),Pr(),or(H.isStreaming());let xo=((di=r.voiceRecognition)==null?void 0:di.enabled)===!0,vo=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Co=((ui=(pi=r.voiceRecognition)==null?void 0:pi.provider)==null?void 0:ui.type)==="runtype";if(xo&&(vo||Co))if(!B||!Z){let O=go(r.voiceRecognition,r.sendButton);O&&(B=O.micButton,Z=O.micButtonWrapper,Mt.insertBefore(Z,tt),B.addEventListener("click",qn),B.disabled=H.isStreaming())}else{let O=(gi=r.voiceRecognition)!=null?gi:{},Ye=(mi=r.sendButton)!=null?mi:{},mt=(fi=O.iconName)!=null?fi:"mic",Oe=(hi=Ye.size)!=null?hi:"40px",et=(yi=O.iconSize)!=null?yi:Oe,It=parseFloat(et)||24;B.style.width=et,B.style.height=et,B.style.minWidth=et,B.style.minHeight=et;let Dt=(xi=(bi=O.iconColor)!=null?bi:Ye.textColor)!=null?xi:"currentColor";B.innerHTML="";let en=me(mt,It,Dt,2);en?B.appendChild(en):B.textContent="\u{1F3A4}";let zt=(vi=O.backgroundColor)!=null?vi:Ye.backgroundColor;zt?(B.style.backgroundColor=zt,B.classList.remove("persona-bg-persona-primary")):(B.style.backgroundColor="",B.classList.add("persona-bg-persona-primary")),Dt?(B.style.color=Dt,B.classList.remove("persona-text-white")):!Dt&&!Ye.textColor&&(B.style.color="",B.classList.add("persona-text-white")),O.borderWidth?(B.style.borderWidth=O.borderWidth,B.style.borderStyle="solid"):(B.style.borderWidth="",B.style.borderStyle=""),O.borderColor?B.style.borderColor=O.borderColor:B.style.borderColor="",O.paddingX?(B.style.paddingLeft=O.paddingX,B.style.paddingRight=O.paddingX):(B.style.paddingLeft="",B.style.paddingRight=""),O.paddingY?(B.style.paddingTop=O.paddingY,B.style.paddingBottom=O.paddingY):(B.style.paddingTop="",B.style.paddingBottom="");let St=Z==null?void 0:Z.querySelector(".persona-send-button-tooltip"),tn=(Ci=O.tooltipText)!=null?Ci:"Start voice recognition";if(((wi=O.showTooltip)!=null?wi:!1)&&tn)if(St)St.textContent=tn,St.style.display="";else{let Nt=document.createElement("div");Nt.className="persona-send-button-tooltip",Nt.textContent=tn,Z==null||Z.insertBefore(Nt,B)}else St&&(St.style.display="none");Z.style.display="",B.disabled=H.isStreaming()}else B&&Z&&(Z.style.display="none",((Ai=(Si=r.voiceRecognition)==null?void 0:Si.provider)==null?void 0:Ai.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():Qt&&cn());if(((Ei=r.attachments)==null?void 0:Ei.enabled)===!0)if(!_||!J){let O=(Ti=r.attachments)!=null?Ti:{},mt=(ki=((Mi=r.sendButton)!=null?Mi:{}).size)!=null?ki:"40px";Le||(Le=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Le.style.display="none",We.insertBefore(Le,X)),xe||(xe=document.createElement("input"),xe.type="file",xe.accept=((Li=O.allowedTypes)!=null?Li:kn).join(","),xe.multiple=((Pi=O.maxFiles)!=null?Pi:4)>1,xe.style.display="none",xe.setAttribute("aria-label","Attach files"),We.insertBefore(xe,X)),_=h("div","persona-send-button-wrapper"),J=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),J.type="button",J.setAttribute("aria-label",(Ii=O.buttonTooltipText)!=null?Ii:"Attach file");let Oe=(Wi=O.buttonIconName)!=null?Wi:"paperclip",et=mt,It=parseFloat(et)||40,Dt=Math.round(It*.6);J.style.width=et,J.style.height=et,J.style.minWidth=et,J.style.minHeight=et,J.style.fontSize="18px",J.style.lineHeight="1",J.style.backgroundColor="transparent",J.style.color="var(--persona-primary, #111827)",J.style.border="none",J.style.borderRadius="6px",J.style.transition="background-color 0.15s ease",J.addEventListener("mouseenter",()=>{J.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),J.addEventListener("mouseleave",()=>{J.style.backgroundColor="transparent"});let en=me(Oe,Dt,"currentColor",1.5);en?J.appendChild(en):J.textContent="\u{1F4CE}",J.addEventListener("click",tn=>{tn.preventDefault(),xe==null||xe.click()}),_.appendChild(J);let zt=(Ri=O.buttonTooltipText)!=null?Ri:"Attach file",St=h("div","persona-send-button-tooltip");St.textContent=zt,_.appendChild(St),Ht.append(_),!He&&xe&&Le&&(He=ur.fromConfig(O),He.setPreviewsContainer(Le),xe.addEventListener("change",async()=>{He&&(xe!=null&&xe.files)&&(await He.handleFileSelect(xe.files),xe.value="")}))}else{_.style.display="";let O=(Hi=r.attachments)!=null?Hi:{};xe&&(xe.accept=((Bi=O.allowedTypes)!=null?Bi:kn).join(","),xe.multiple=((Fi=O.maxFiles)!=null?Fi:4)>1),He&&He.updateConfig({allowedTypes:O.allowedTypes,maxFileSize:O.maxFileSize,maxFiles:O.maxFiles})}else _&&(_.style.display="none"),He&&He.clearAttachments();let Et=($i=r.sendButton)!=null?$i:{},wo=(Ni=Et.useIcon)!=null?Ni:!1,Br=(Oi=Et.iconText)!=null?Oi:"\u2191",zn=Et.iconName,Jn=(Di=Et.tooltipText)!=null?Di:"Send message",wc=(_i=Et.showTooltip)!=null?_i:!1,Fr=(ji=Et.size)!=null?ji:"40px",So=Et.backgroundColor,xn=Et.textColor;if(wo){if(K.style.width=Fr,K.style.height=Fr,K.style.minWidth=Fr,K.style.minHeight=Fr,K.style.fontSize="18px",K.style.lineHeight="1",K.innerHTML="",zn){let O=parseFloat(Fr)||24,Ye=xn&&typeof xn=="string"&&xn.trim()?xn.trim():"currentColor",mt=me(zn,O,Ye,2);mt?(K.appendChild(mt),K.style.color=Ye):(K.textContent=Br,xn?K.style.color=xn:K.classList.add("persona-text-white"))}else K.textContent=Br,xn?K.style.color=xn:K.classList.add("persona-text-white");K.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",So?(K.style.backgroundColor=So,K.classList.remove("persona-bg-persona-primary")):K.classList.add("persona-bg-persona-primary")}else K.textContent=(Ui=(Vi=r.copy)==null?void 0:Vi.sendButtonLabel)!=null?Ui:"Send",K.style.width="",K.style.height="",K.style.minWidth="",K.style.minHeight="",K.style.fontSize="",K.style.lineHeight="",K.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",So?(K.style.backgroundColor=So,K.classList.remove("persona-bg-persona-accent")):K.classList.add("persona-bg-persona-accent"),xn?K.style.color=xn:K.classList.add("persona-text-white");Et.borderWidth?(K.style.borderWidth=Et.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),Et.borderColor?K.style.borderColor=Et.borderColor:K.style.borderColor="",Et.paddingX?(K.style.paddingLeft=Et.paddingX,K.style.paddingRight=Et.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),Et.paddingY?(K.style.paddingTop=Et.paddingY,K.style.paddingBottom=Et.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let $r=tt==null?void 0:tt.querySelector(".persona-send-button-tooltip");if(wc&&Jn)if($r)$r.textContent=Jn,$r.style.display="";else{let O=document.createElement("div");O.className="persona-send-button-tooltip",O.textContent=Jn,tt==null||tt.insertBefore(O,K)}else $r&&($r.style.display="none");let Nr=(qi=r.statusIndicator)!=null?qi:{},Sc=(zi=Nr.visible)!=null?zi:!0;if(Ve.style.display=Sc?"":"none",H){let O=H.getStatus(),Ye=mt=>{var Oe,et,It,Dt;return mt==="idle"?(Oe=Nr.idleText)!=null?Oe:Vt.idle:mt==="connecting"?(et=Nr.connectingText)!=null?et:Vt.connecting:mt==="connected"?(It=Nr.connectedText)!=null?It:Vt.connected:mt==="error"?(Dt=Nr.errorText)!=null?Dt:Vt.error:Vt[mt]};Ve.textContent=Ye(O)}},open(){v&&gt(!0,"api")},close(){v&&gt(!1,"api")},toggle(){v&&gt(!w,"api")},clearChat(){ln=!1,H.clearMessages(),Hn.clear();try{localStorage.removeItem(xr),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${xr}`)}catch(u){console.error("[AgentWidget] Failed to clear default localStorage:",u)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==xr)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(u){console.error("[AgentWidget] Failed to clear custom localStorage:",u)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let u=a.clear();u instanceof Promise&&u.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",u)}i={},C.syncFromMetadata(),D==null||D.clear(),U==null||U.update()},setMessage(l){return!X||H.isStreaming()?!1:(!w&&v&&gt(!0,"system"),X.value=l,X.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let u=(l==null?void 0:l.trim())||X.value.trim();return u?(!w&&v&&gt(!0,"system"),X.value="",X.style.height="auto",H.sendMessage(u),!0):!1},startVoiceRecognition(){var u,y;return H.isStreaming()?!1:((y=(u=r.voiceRecognition)==null?void 0:u.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!w&&v&&gt(!0,"system"),Ue.manuallyDeactivated=!1,Kt(),H.toggleVoice().then(()=>{Ue.active=H.isVoiceActive(),rn("user"),H.isVoiceActive()&&Bn()})),!0):Qt?!0:Hr()?(!w&&v&&gt(!0,"system"),Ue.manuallyDeactivated=!1,Kt(),Vn("user"),!0):!1},stopVoiceRecognition(){var l,u;return((u=(l=r.voiceRecognition)==null?void 0:l.provider)==null?void 0:u.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ue.active=!1,Ue.manuallyDeactivated=!0,Kt(),rn("user"),dn()}),!0):!1:Qt?(Ue.manuallyDeactivated=!0,Kt(),cn("user"),!0):!1},injectMessage(l){return!w&&v&&gt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!w&&v&&gt(!0,"system");let u=H.injectAssistantMessage(l);return F&&(F=!1,re&&(clearTimeout(re),re=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),u},injectUserMessage(l){return!w&&v&&gt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!w&&v&&gt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!w&&v&&gt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!w&&v&&gt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,u){return H.connectStream(l,u)},__pushEventStreamEvent(l){D&&D.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Ie||!D||Ce()},hideEventStream(){oe&&Be()},isEventStreamVisible(){return oe},showArtifacts(){an(r)&&(ln=!1,hn(),Qe==null||Qe.setMobileOpen(!0))},hideArtifacts(){an(r)&&(ln=!0,hn())},upsertArtifact(l){return an(r)?(ln=!1,H.upsertArtifact(l)):null},selectArtifact(l){an(r)&&H.selectArtifact(l)},clearArtifacts(){an(r)&&H.clearArtifacts()},focusInput(){return v&&!w||!X?!1:(X.focus(),!0)},async resolveApproval(l,u){let S=H.getMessages().find(R=>{var L;return R.variant==="approval"&&((L=R.approval)==null?void 0:L.id)===l});if(!(S!=null&&S.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(S.approval,u)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,u){return o.on(l,u)},off(l,u){o.off(l,u)},isOpen(){return v&&w},isVoiceActive(){return Ue.active},getState(){return{open:v&&w,launcherEnabled:v,voiceActive:Ue.active,streaming:H.isStreaming()}},showCSATFeedback(l){!w&&v&&gt(!0,"system");let u=be.querySelector(".persona-feedback-container");u&&u.remove();let y=Ts({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitCSATFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!w&&v&&gt(!0,"system");let u=be.querySelector(".persona-feedback-container");u&&u.remove();let y=Ms({onSubmit:async(S,R)=>{var L;H.isClientTokenMode()&&await H.submitNPSFeedback(S,R),(L=l==null?void 0:l.onSubmit)==null||L.call(l,S,R)},onDismiss:l==null?void 0:l.onDismiss,...l});be.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,u){return H.submitCSATFeedback(l,u)},async submitNPSFeedback(l,u){return H.submitNPSFeedback(l,u)},destroy(){xt.forEach(l=>l()),de.remove(),we==null||we.destroy(),$e==null||$e.remove(),bn&&ce.removeEventListener("click",bn)}};if((((ea=t==null?void 0:t.debugTools)!=null?ea:!1)||!!r.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,u={controller:T,getMessages:T.getMessages,getStatus:T.getStatus,getMetadata:T.getPersistentMetadata,updateMetadata:T.updatePersistentMetadata,clearHistory:()=>T.clearChat(),setVoiceActive:y=>y?T.startVoiceRecognition():T.stopVoiceRecognition()};window.AgentWidgetBrowser=u,xt.push(()=>{window.AgentWidgetBrowser===u&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),u=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.focusInput()};if(window.addEventListener("persona:focusInput",u),xt.push(()=>{window.removeEventListener("persona:focusInput",u)}),Ie){let V=se=>{let fe=se.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===l)&&T.showEventStream()},$=se=>{let fe=se.detail;(!(fe!=null&&fe.instanceId)||fe.instanceId===l)&&T.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",$),xt.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",$)})}let y=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.showArtifacts()},S=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.hideArtifacts()},R=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||$!=null&&$.artifact&&T.upsertArtifact($.artifact)},L=V=>{let $=V.detail;$!=null&&$.instanceId&&$.instanceId!==l||typeof($==null?void 0:$.id)=="string"&&T.selectArtifact($.id)},P=V=>{let $=V.detail;(!($!=null&&$.instanceId)||$.instanceId===l)&&T.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",S),window.addEventListener("persona:upsertArtifact",R),window.addEventListener("persona:selectArtifact",L),window.addEventListener("persona:clearArtifacts",P),xt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",S),window.removeEventListener("persona:upsertArtifact",R),window.removeEventListener("persona:selectArtifact",L),window.removeEventListener("persona:clearArtifacts",P)})}let W=Qd(r.persistState);if(W&&v){let l=ep(W.storage),u=`${W.keyPrefix}widget-open`,y=`${W.keyPrefix}widget-voice`,S=`${W.keyPrefix}widget-voice-mode`;if(l){let R=((ta=W.persist)==null?void 0:ta.openState)&&l.getItem(u)==="true",L=((na=W.persist)==null?void 0:na.voiceState)&&l.getItem(y)==="true",P=((ra=W.persist)==null?void 0:ra.voiceState)&&l.getItem(S)==="true";if(R&&setTimeout(()=>{T.open(),setTimeout(()=>{var V;if(L||P)T.startVoiceRecognition();else if((V=W.persist)!=null&&V.focusInput){let $=e.querySelector("textarea");$&&$.focus()}},100)},0),(oa=W.persist)!=null&&oa.openState&&(o.on("widget:opened",()=>{l.setItem(u,"true")}),o.on("widget:closed",()=>{l.setItem(u,"false")})),(sa=W.persist)!=null&&sa.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(S,V.viaVoice?"true":"false")})),W.clearOnChatClear){let V=()=>{l.removeItem(u),l.removeItem(y),l.removeItem(S)},$=()=>V();window.addEventListener("persona:clear-chat",$),xt.push(()=>{window.removeEventListener("persona:clear-chat",$)})}}}return T};var Gl=(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"},Ps=(e,n,t,r,s,o)=>{let a=Kr(s),i=o?a.width:a.collapsedWidth;e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=a.side,e.dataset.personaDockOpen=o?"true":"false",e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.flex="1 1 auto",n.style.minWidth="0",n.style.minHeight="0",n.style.position="relative",t.style.display="flex",t.style.flexDirection="column",t.style.flex=`0 0 ${i}`,t.style.width=i,t.style.maxWidth=i,t.style.minWidth=i,t.style.minHeight="0",t.style.position="relative",t.style.overflow="visible",t.style.transition="width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease",r.className="persona-host",r.style.height="100%",r.style.minHeight="0",r.style.display="flex",r.style.flexDirection="column",r.style.flex="1 1 auto",a.side==="left"?e.firstElementChild!==t&&e.replaceChildren(t,n):e.lastElementChild!==t&&e.replaceChildren(n,t)},tp=(e,n)=>{let t=e.ownerDocument.createElement("div");return Gl(t,n),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(r){Gl(t,r)},destroy(){t.remove()}}},np=(e,n)=>{var p,f,m,C;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"),d=t.createElement("aside"),c=t.createElement("div"),g=(f=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)==null||f?(C=(m=n==null?void 0:n.launcher)==null?void 0:m.autoExpand)!=null?C:!1:!0;return i.dataset.personaDockRole="content",d.dataset.personaDockRole="panel",c.dataset.personaDockRole="host",d.appendChild(c),r.insertBefore(a,e),i.appendChild(e),a.appendChild(i),a.appendChild(d),Ps(a,i,d,c,n,g),{mode:"docked",host:c,shell:a,syncWidgetState(v){let E=v.launcherEnabled?v.open:!0;g!==E&&(g=E,Ps(a,i,d,c,n,g))},updateConfig(v){var E,x;n=v,((x=(E=n==null?void 0:n.launcher)==null?void 0:E.enabled)!=null?x:!0)===!1&&(g=!0),Ps(a,i,d,c,n,g)},destroy(){r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Oo=(e,n)=>Jt(n)?np(e,n):tp(e,n);var Is={},rp=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},op=()=>{try{if(typeof Is!="undefined"&&Is.url)return new URL("../widget.css",Is.url).href}catch{}return null},Xl=(e,n)=>{let t=op(),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)}},Zl=e=>{var E;let n=rp(e.target),t=e.useShadowDom===!0,r=n.ownerDocument,s=e.config,o=Oo(n,s),a,i=[],d=(x,k)=>{var w,F;let M=!((F=(w=k==null?void 0:k.launcher)==null?void 0:w.enabled)!=null?F:!0)||Jt(k),N=r.createElement("div");if(N.id="persona-root",M&&(N.style.height="100%",N.style.display="flex",N.style.flexDirection="column",N.style.flex="1",N.style.minHeight="0"),t){let re=x.attachShadow({mode:"open"});re.appendChild(N),Xl(re,r)}else x.appendChild(N),Xl(x,r);return n.id&&N.setAttribute("data-persona-instance",n.id),N},c=()=>{o.syncWidgetState(a.getState())},g=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let x=d(o.host,s);a=Ls(x,s,{debugTools:e.debugTools}),g()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};p(),(E=e.onReady)==null||E.call(e);let m=x=>{f(),o.destroy(),o=Oo(n,x),s=x,p()},C={update(x){var N,w,F,re,Y,ae;let k={...s,...x,launcher:{...(N=s==null?void 0:s.launcher)!=null?N:{},...(w=x==null?void 0:x.launcher)!=null?w:{},dock:{...(re=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?re:{},...(ae=(Y=x==null?void 0:x.launcher)==null?void 0:Y.dock)!=null?ae:{}}}},q=Jt(s),M=Jt(k);if(q!==M){m(k);return}s=k,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},v=new Proxy(C,{get(x,k,q){if(k==="host")return o.host;if(k in x)return Reflect.get(x,k,q);let M=a[k];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=v),v};var rc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),sp=new Set(["button","a","input","select","textarea","details","summary"]),ap=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ws=/\b(product|card|item|listing|result)\b/i,Hs=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,ip=3e3,lp=100;function oc(e){let n=typeof e.className=="string"?e.className:"";if(Ws.test(n)||e.id&&Ws.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let r=e.attributes[t];if(r.name.startsWith("data-")&&Ws.test(r.value))return!0}return!1}function sc(e){var n;return Hs.test(((n=e.textContent)!=null?n:"").trim())}function ac(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 cp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ql(e){let n=e.match(Hs);return n?n[0]:null}function ec(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 dp(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 pp="commerce-card",up="result-card";function tc(e){return!oc(e)||!sc(e)||!ac(e)&&!cp(e)?0:5200}function nc(e){var r;return!oc(e)||sc(e)||!ac(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 ic=[{id:pp,scoreElement(e){return tc(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||Hs.test(r)&&r.length<32)}return!0},formatSummary(e,n){var d,c,g;if(tc(e)===0)return null;let{title:t,href:r}=ec(e),s=(g=(c=Ql(((d=e.textContent)!=null?d:"").trim()))!=null?c:Ql(n.text))!=null?g:"",o=dp(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(`
96
- `)}},{id:up,scoreElement(e){return nc(e)},formatSummary(e,n){if(nc(e)===0)return null;let{title:t,href:r}=ec(e);return[r&&t?`[${t}](${r})`:t||n.text.trim().slice(0,120),`selector: ${n.selector}`].filter(Boolean).join(`
97
- `)}}];function gp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function mp(e){var g,p,f,m,C,v,E,x,k,q,M,N,w;let n=(g=e.options)!=null?g:{},t=(f=(p=n.maxElements)!=null?p:e.maxElements)!=null?f:80,r=(C=(m=n.excludeSelector)!=null?m:e.excludeSelector)!=null?C:".persona-host",s=(E=(v=n.maxTextLength)!=null?v:e.maxTextLength)!=null?E:200,o=(k=(x=n.visibleOnly)!=null?x:e.visibleOnly)!=null?k:!0,a=(q=n.root)!=null?q:e.root,i=(M=n.mode)!=null?M:"structured",d=(N=n.maxCandidates)!=null?N:Math.max(500,t*10),c=(w=e.rules)!=null?w:ic;return i==="simple"&&e.rules&&e.rules.length>0?(gp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function Rs(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var fp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function hp(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"||sp.has(n)||t&&ap.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function lc(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 yp(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 d=e.getAttribute("role");d&&(n.role=d);for(let c=0;c<e.attributes.length;c++){let g=e.attributes[c];g.name.startsWith("data-")&&(n[g.name]=g.value)}return n}function cc(e){let n=e.tagName.toLowerCase();if(e.id){let s=`#${Rs(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of fp){let o=e.getAttribute(s);if(o){let a=`${n}[${s}="${Rs(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=>Rs(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 d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}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 bp(e){return e==="static"?lp:ip}function dc(e,n){var s;let t=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,n);return{selector:cc(e),tagName:t,text:r,role:e.getAttribute("role"),interactivity:hp(e),attributes:yp(e)}}function xp(e,n,t,r){let s=bp(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 vp(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 Cp(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,g=c.tagName.toLowerCase();if(rc.has(g)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!lc(c)){i=a.nextNode();continue}let p=dc(c,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(E=>E==="role");if(!f&&!m){i=a.nextNode();continue}if(r.has(p.selector)){i=a.nextNode();continue}r.add(p.selector);let{score:C,formattingRule:v}=xp(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:C,formattingRule:v}),o+=1}i=a.nextNode()}s.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,f=g.enriched.interactivity==="static"?1:0;return p!==f?p-f:g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;vp(d,c)||d.push(c)}return d.sort((c,g)=>{let p=c.enriched.interactivity==="static"?1:0,f=g.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&g.score!==c.score?g.score-c.score:c.domIndex-g.domIndex}),d.map(c=>{var f;let g;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(g=m)}let p={...c.enriched};return g&&(p.formattedSummary=g),p})}function wp(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 d=o,c=d.tagName.toLowerCase();if(rc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!lc(d)){o=s.nextNode();continue}let g=dc(d,e.maxTextLength),p=g.text.length>0,f=Object.keys(g.attributes).length>0&&!Object.keys(g.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}r.has(g.selector)||(r.add(g.selector),t.push(g))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Sp(e={}){var r;let n=mp(e),t=(r=n.root)!=null?r:document.body;return t?n.mode==="simple"?wp(n,t):Cp(n,t):[]}var Do=100;function Ap(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:
95
+ `}if(!A&&!l){let Qt="max-height: -moz-available !important; max-height: stretch !important;",dn=g?"":"padding-top: 1.25em !important;";se.style.cssText+=Qt+dn}};Jn(),or(e,n),jo(e,n),zo(e,n);let bt=[];tn&&bt.push(()=>{tn==null||tn.disconnect(),tn=null}),bt.push(()=>{sn==null||sn(),sn=null,ir(),pt&&(pt.remove(),pt=null),Xe==null||Xe.element.style.removeProperty("width"),Xe==null||Xe.element.style.removeProperty("maxWidth")}),Ce&&bt.push(()=>{fe!==null&&(cancelAnimationFrame(fe),fe=null),V==null||V.destroy(),V=null,J==null||J.destroy(),J=null,ce=null});let Cn=null,Pr=()=>{Cn&&(Cn(),Cn=null),n.colorScheme==="auto"&&(Cn=ms(()=>{or(e,n)}))};Pr(),bt.push(()=>{Cn&&(Cn(),Cn=null)});let On=Fl(Qe),wn=null,D,Fn=!1,$n=El(),Ir=0,Ln=!0,Kn=0,Wr=0,Pn=null,In=!1,lr=0,cr=!1,lo=125,co=2e3,po=5,Rr=50,dr=new Map,qe={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Hr=(oa=(ra=n.voiceRecognition)==null?void 0:ra.autoResume)!=null?oa:!1,an=l=>{o.emit("voice:state",{active:qe.active,source:l,timestamp:Date.now()})},Gt=()=>{p(l=>({...l,voiceState:{active:qe.active,timestamp:Date.now(),manuallyDeactivated:qe.manuallyDeactivated}}))},uo=()=>{var A,k;if(((A=n.voiceRecognition)==null?void 0:A.enabled)===!1)return;let l=Rs(i.voiceState),g=!!l.active,y=Number((k=l.timestamp)!=null?k:0);qe.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<Qd&&setTimeout(()=>{var I,L;qe.active||(qe.manuallyDeactivated=!1,((L=(I=n.voiceRecognition)==null?void 0:I.provider)==null?void 0:L.type)==="runtype"?D.toggleVoice().then(()=>{qe.active=D.isVoiceActive(),an("restore"),D.isVoiceActive()&&_n()}):Zn("restore"))},1e3)},go=()=>D?Ql(D.getMessages()).filter(l=>!l.__skipPersist):[];function Br(l){if(!(a!=null&&a.save))return;let y={messages:l?Ql(l):D?go():[],metadata:i};try{let A=a.save(y);A instanceof Promise&&A.catch(k=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",k)})}catch(A){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",A)}}let Yn=(l=!1)=>{if(!Ln)return;let g=Date.now();In&&g<lr&&!l||(In&&g>=lr&&(In=!1),!(!l&&!Fn)&&(g-Wr<lo||(Wr=g,Pn&&cancelAnimationFrame(Pn),Pn=requestAnimationFrame(()=>{In||!Ln||(cr=!0,te.scrollTop=te.scrollHeight,Kn=te.scrollTop,requestAnimationFrame(()=>{cr=!1}),Pn=null)}))))},Wn=null,mo=()=>se.querySelector("#persona-scroll-container")||te,fo=(l,g=500)=>{let y=l.scrollTop,A=l.clientHeight,k=l.scrollHeight,I=k-y;if(y+A>=k-2||Math.abs(I)<5)return;Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let j=performance.now(),O=he=>1-Math.pow(1-he,3),oe=he=>{let Se=l.scrollHeight;Se!==k&&(k=Se,I=k-y);let Re=he-j,Le=Math.min(Re/g,1),B=O(Le),Pe=y+I*B;l.scrollTop=Pe,Le<1?Wn=requestAnimationFrame(oe):(l.scrollTop=l.scrollHeight,Wn=null)};Wn=requestAnimationFrame(oe)},ho=l=>{let g=new Map;l.forEach(y=>{let A=dr.get(y.id);g.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}))}),dr.clear(),g.forEach((y,A)=>{dr.set(A,y)})},Gn=(l,g,y)=>{var he,Se,Re,Le;let A=document.createElement("div"),I=(()=>{var Pe;let B=s.find(Ie=>Ie.renderLoadingIndicator);if(B!=null&&B.renderLoadingIndicator)return B.renderLoadingIndicator;if((Pe=n.loadingIndicator)!=null&&Pe.render)return n.loadingIndicator.render})(),L=new Set;g.forEach(B=>{var ge,It;L.add(B.id);let Pe=Al(B,Ir),Ie=Tl($n,B.id,Pe);if(Ie){A.appendChild(Ie.cloneNode(!0));return}let ae=null,He=s.find(lt=>!!(B.variant==="reasoning"&&lt.renderReasoning||B.variant==="tool"&&lt.renderToolCall||B.variant==="approval"&&lt.renderApproval||!B.variant&&lt.renderMessage)),et=(ge=n.layout)==null?void 0:ge.messages;if(He)if(B.variant==="reasoning"&&B.reasoning&&He.renderReasoning){if(!q)return;ae=He.renderReasoning({message:B,defaultRenderer:()=>ys(B),config:n})}else if(B.variant==="tool"&&B.toolCall&&He.renderToolCall){if(!ee)return;ae=He.renderToolCall({message:B,defaultRenderer:()=>bs(B,n),config:n})}else if(B.variant==="approval"&&B.approval&&He.renderApproval){if(n.approval===!1)return;ae=He.renderApproval({message:B,defaultRenderer:()=>xs(B,n),config:n})}else He.renderMessage&&(ae=He.renderMessage({message:B,defaultRenderer:()=>{let lt=so(B,y,et,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n});return B.role!=="user"&&ws(lt,B,n,D),lt},config:n}));if(!ae&&B.role==="assistant"&&!B.variant&&n.enableComponentStreaming!==!1&&Ls(B)){let Zt=Ps(B);if(Zt){let Ut=ks(Zt,{config:n,message:B,transform:y});if(Ut)if(n.wrapComponentDirectiveInBubble!==!1){let Nt=document.createElement("div");if(Nt.className=["vanilla-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Nt.id=`bubble-${B.id}`,Nt.setAttribute("data-message-id",B.id),B.content&&B.content.trim()){let cn=document.createElement("div");cn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",cn.innerHTML=y({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}else{let Nt=document.createElement("div");if(Nt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Nt.id=`bubble-${B.id}`,Nt.setAttribute("data-message-id",B.id),Nt.setAttribute("data-persona-component-directive","true"),B.content&&B.content.trim()){let cn=document.createElement("div");cn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",cn.innerHTML=y({text:B.content,message:B,streaming:!!B.streaming,raw:B.rawContent}),Nt.appendChild(cn)}Nt.appendChild(Ut),ae=Nt}}}if(!ae)if(B.variant==="reasoning"&&B.reasoning){if(!q)return;ae=ys(B)}else if(B.variant==="tool"&&B.toolCall){if(!ee)return;ae=bs(B,n)}else if(B.variant==="approval"&&B.approval){if(n.approval===!1)return;ae=xs(B,n)}else{let lt=(It=n.layout)==null?void 0:It.messages;lt!=null&&lt.renderUserMessage&&B.role==="user"?ae=lt.renderUserMessage({message:B,config:n,streaming:!!B.streaming}):lt!=null&&lt.renderAssistantMessage&&B.role==="assistant"?ae=lt.renderAssistantMessage({message:B,config:n,streaming:!!B.streaming}):ae=so(B,y,lt,n.messageActions,ut,{loadingIndicatorRenderer:I,widgetConfig:n}),B.role!=="user"&&ae&&ws(ae,B,n,D)}let Je=document.createElement("div");Je.className="persona-flex",Je.id=`wrapper-${B.id}`,Je.setAttribute("data-wrapper-id",B.id),B.role==="user"&&Je.classList.add("persona-justify-end"),(ae==null?void 0:ae.getAttribute("data-persona-component-directive"))==="true"&&Je.classList.add("persona-w-full"),Je.appendChild(ae),Ml($n,B.id,Pe,Je),A.appendChild(Je)}),kl($n,L);let j=g.some(B=>B.role==="assistant"&&B.streaming),O=g[g.length-1],oe=(O==null?void 0:O.role)==="assistant"&&!O.streaming&&O.variant!=="approval";if(Fn&&g.some(B=>B.role==="user")&&!j&&!oe){let B={config:n,streaming:!0,location:"standalone",defaultRenderer:Cr},Pe=s.find(ae=>ae.renderLoadingIndicator),Ie=null;if(Pe!=null&&Pe.renderLoadingIndicator&&(Ie=Pe.renderLoadingIndicator(B)),Ie===null&&((he=n.loadingIndicator)!=null&&he.render)&&(Ie=n.loadingIndicator.render(B)),Ie===null&&(Ie=Cr()),Ie){let ae=document.createElement("div"),He=((Se=n.loadingIndicator)==null?void 0:Se.showBubble)!==!1;ae.className=He?["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(" "),ae.setAttribute("data-typing-indicator","true"),ae.appendChild(Ie);let et=document.createElement("div");et.className="persona-flex",et.id="wrapper-typing-indicator",et.setAttribute("data-wrapper-id","typing-indicator"),et.appendChild(ae),A.appendChild(et)}}if(!Fn&&g.length>0){let B=g[g.length-1],Pe={config:n,lastMessage:B,messageCount:g.length},Ie=s.find(He=>He.renderIdleIndicator),ae=null;if(Ie!=null&&Ie.renderIdleIndicator&&(ae=Ie.renderIdleIndicator(Pe)),ae===null&&((Re=n.loadingIndicator)!=null&&Re.renderIdle)&&(ae=n.loadingIndicator.renderIdle(Pe)),ae){let He=document.createElement("div"),et=((Le=n.loadingIndicator)==null?void 0:Le.showBubble)!==!1;He.className=et?["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(" "),He.setAttribute("data-idle-indicator","true"),He.appendChild(ae);let Je=document.createElement("div");Je.className="persona-flex",Je.id="wrapper-idle-indicator",Je.setAttribute("data-wrapper-id","idle-indicator"),Je.appendChild(He),A.appendChild(Je)}}Sl(l,A),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let B=mo();fo(B)})})},Xn=()=>{var O,oe,he,Se,Re;if(!b)return;let l=zt(n),g=(O=e.ownerDocument.defaultView)!=null?O:window,y=(he=(oe=n.launcher)==null?void 0:oe.mobileBreakpoint)!=null?he:640,A=(Re=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?Re:!0,k=g.innerWidth<=y,I=A&&k&&b,L=hn(n).reveal;W?(se.style.removeProperty("display"),se.style.display=l?"flex":"",se.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-95","persona-opacity-0"),re.classList.add("persona-scale-100","persona-opacity-100"),Te?Te.element.style.display="none":Fe&&(Fe.style.display="none")):(l?l&&(L==="overlay"||L==="push")&&!I?(se.style.removeProperty("display"),se.style.display="flex",se.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(se.style.setProperty("display","none","important"),se.classList.remove("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(se.style.display="",se.classList.add("persona-pointer-events-none","persona-opacity-0"),re.classList.remove("persona-scale-100","persona-opacity-100"),re.classList.add("persona-scale-95","persona-opacity-0")),Te?Te.element.style.display=l?"none":"":Fe&&(Fe.style.display=l?"none":""))},mt=(l,g="user")=>{if(!b||W===l)return;let y=W;W=l,Xn(),W&&(xt(),Yn(!0));let A={open:W,source:g,timestamp:Date.now()};W&&!y?o.emit("widget:opened",A):!W&&y&&o.emit("widget:closed",A),o.emit("widget:state",{open:W,launcherEnabled:b,voiceActive:qe.active,streaming:D.isStreaming()})},pr=l=>{Y.disabled=l,N&&(N.disabled=l),On.buttons.forEach(g=>{g.disabled=l}),nt.dataset.personaComposerStreaming=l?"true":"false",nt.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},ur=()=>{qe.active||G&&G.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>ur(),200)});let Dr=()=>{var g,y,A,k,I,L,j,O,oe,he;Mt.textContent=(y=(g=n.copy)==null?void 0:g.welcomeTitle)!=null?y:"Hello \u{1F44B}",qt.textContent=(k=(A=n.copy)==null?void 0:A.welcomeSubtitle)!=null?k:"Ask anything about your account or products.",G.placeholder=(L=(I=n.copy)==null?void 0:I.inputPlaceholder)!=null?L:"How can I help...",(O=(j=n.sendButton)==null?void 0:j.useIcon)!=null&&O||(Y.textContent=(he=(oe=n.copy)==null?void 0:oe.sendButtonLabel)!=null?he:"Send"),G.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',G.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};if(n.clientToken&&(n={...n,getStoredSessionId:()=>{let l=i.sessionId;return typeof l=="string"?l:null},setStoredSessionId:l=>{p(g=>({...g,sessionId:l}))}}),D=new Zr(n,{onMessagesChanged(l){Gn(de,l,le),D&&(l.some(k=>k.role==="user")?On.render([],D,G,l):On.render(n.suggestionChips,D,G,l,n.suggestionChipsConfig)),Yn(!Fn),ho(l);let g=[...l].reverse().find(A=>A.role==="user"),y=qe.lastUserMessageId;g&&g.id!==y&&(qe.lastUserMessageId=g.id,o.emit("user:message",g)),qe.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Br(l)},onStatusChanged(l){var A;let g=(A=n.statusIndicator)!=null?A:{},y=k=>{var I,L,j,O;return k==="idle"?(I=g.idleText)!=null?I:Vt.idle:k==="connecting"?(L=g.connectingText)!=null?L:Vt.connecting:k==="connected"?(j=g.connectedText)!=null?j:Vt.connected:k==="error"?(O=g.errorText)!=null?O:Vt.error:Vt[k]};je.textContent=y(l)},onStreamingChanged(l){Fn=l,pr(l),D&&Gn(de,D.getMessages(),le),l||Yn(!0)},onVoiceStatusChanged(l){var g,y;if(((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype")switch(l){case"listening":break;case"processing":mn(),bo();break;case"speaking":mn(),xo();break;default:l==="idle"&&D.isBargeInActive()?(mn(),_n(),N==null||N.setAttribute("aria-label","End voice session")):(qe.active=!1,mn(),an("system"),Gt());break}},onArtifactsState(l){un=l,vn()}}),Mn.current=D,((aa=(sa=n.voiceRecognition)==null?void 0:sa.provider)==null?void 0:aa.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)}),J&&D.setSSEEventCallback((l,g)=>{J==null||J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),d&&d.then(l=>{var g;l&&(l.metadata&&(i=Rs(l.metadata),x.syncFromMetadata()),(g=l.messages)!=null&&g.length&&D.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let Nr=l=>{var k;l.preventDefault();let g=G.value.trim(),y=(k=Ee==null?void 0:Ee.hasAttachments())!=null?k:!1;if(!g&&!y)return;let A;y&&(A=[],A.push(...Ee.getContentParts()),g&&A.push(ds(g))),G.value="",G.style.height="auto",D.sendMessage(g,{contentParts:A}),y&&Ee.clearAttachments()},Or=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),Y.click())},Fr=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!Ee)return;let g=tp(l.clipboardData);g.length!==0&&(l.preventDefault(),await Ee.handleFiles(g))},Jt=null,nn=!1,Rn=null,De=null,$r=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Zn=(l="user")=>{var I,L,j,O,oe,he,Se,Re;if(nn||D.isStreaming())return;let g=$r();if(!g)return;Jt=new g;let A=(L=((I=n.voiceRecognition)!=null?I:{}).pauseDuration)!=null?L:2e3;Jt.continuous=!0,Jt.interimResults=!0,Jt.lang="en-US";let k=G.value;Jt.onresult=Le=>{let B="",Pe="";for(let ae=0;ae<Le.results.length;ae++){let He=Le.results[ae],et=He[0].transcript;He.isFinal?B+=et+" ":Pe=et}let Ie=k+B+Pe;G.value=Ie,Rn&&clearTimeout(Rn),(B||Pe)&&(Rn=window.setTimeout(()=>{let ae=G.value.trim();ae&&Jt&&nn&&(gn(),G.value="",G.style.height="auto",D.sendMessage(ae,{viaVoice:!0}))},A))},Jt.onerror=Le=>{Le.error!=="no-speech"&&gn()},Jt.onend=()=>{if(nn){let Le=G.value.trim();Le&&Le!==k.trim()&&(G.value="",G.style.height="auto",D.sendMessage(Le,{viaVoice:!0})),gn()}};try{if(Jt.start(),nn=!0,qe.active=!0,l!=="system"&&(qe.manuallyDeactivated=!1),an(l),Gt(),N){let Le=(j=n.voiceRecognition)!=null?j:{};De={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(O=Le.iconName)!=null?O:"mic",iconSize:parseFloat((Se=(he=Le.iconSize)!=null?he:(oe=n.sendButton)==null?void 0:oe.size)!=null?Se:"40")||24};let B=(Re=Le.recordingBackgroundColor)!=null?Re:"#ef4444",Pe=Le.recordingIconColor,Ie=Le.recordingBorderColor;if(N.classList.add("persona-voice-recording"),N.style.backgroundColor=B,Pe){N.style.color=Pe;let ae=N.querySelector("svg");ae&&ae.setAttribute("stroke",Pe)}Ie&&(N.style.borderColor=Ie),N.setAttribute("aria-label","Stop voice recognition")}}catch{gn("system")}},gn=(l="user")=>{if(nn){if(nn=!1,Rn&&(clearTimeout(Rn),Rn=null),Jt){try{Jt.stop()}catch{}Jt=null}if(qe.active=!1,an(l),Gt(),N){if(N.classList.remove("persona-voice-recording"),De){N.style.backgroundColor=De.backgroundColor,N.style.color=De.color,N.style.borderColor=De.borderColor;let g=N.querySelector("svg");g&&g.setAttribute("stroke",De.color||"currentColor"),De=null}N.setAttribute("aria-label","Start voice recognition")}}},yo=(l,g)=>{var ae,He,et,Je,ge,It,lt,Zt;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),A=((ae=l==null?void 0:l.provider)==null?void 0:ae.type)==="runtype";if(!(y||A))return null;let I=h("div","persona-send-button-wrapper"),L=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");L.type="button",L.setAttribute("aria-label","Start voice recognition");let j=(He=l==null?void 0:l.iconName)!=null?He:"mic",O=(et=g==null?void 0:g.size)!=null?et:"40px",oe=(Je=l==null?void 0:l.iconSize)!=null?Je:O,he=parseFloat(oe)||24,Se=(ge=l==null?void 0:l.backgroundColor)!=null?ge:g==null?void 0:g.backgroundColor,Re=(It=l==null?void 0:l.iconColor)!=null?It:g==null?void 0:g.textColor;L.style.width=oe,L.style.height=oe,L.style.minWidth=oe,L.style.minHeight=oe,L.style.fontSize="18px",L.style.lineHeight="1";let Le=Re||"currentColor",B=me(j,he,Le,1.5);B?(L.appendChild(B),L.style.color=Le):(L.textContent="\u{1F3A4}",L.style.color=Le),Se?L.style.backgroundColor=Se:L.classList.add("persona-bg-persona-primary"),Re?L.style.color=Re:!Re&&!(g!=null&&g.textColor)&&L.classList.add("persona-text-white"),l!=null&&l.borderWidth&&(L.style.borderWidth=l.borderWidth,L.style.borderStyle="solid"),l!=null&&l.borderColor&&(L.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(L.style.paddingLeft=l.paddingX,L.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(L.style.paddingTop=l.paddingY,L.style.paddingBottom=l.paddingY),I.appendChild(L);let Pe=(lt=l==null?void 0:l.tooltipText)!=null?lt:"Start voice recognition";if(((Zt=l==null?void 0:l.showTooltip)!=null?Zt:!1)&&Pe){let Ut=h("div","persona-send-button-tooltip");Ut.textContent=Pe,I.appendChild(Ut)}return{micButton:L,micButtonWrapper:I}},gr=()=>{var g,y,A,k,I;if(!N||De)return;let l=(g=n.voiceRecognition)!=null?g:{};De={backgroundColor:N.style.backgroundColor,color:N.style.color,borderColor:N.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((I=(k=l.iconSize)!=null?k:(A=n.sendButton)==null?void 0:A.size)!=null?I:"40")||24}},mr=(l,g)=>{var I,L,j,O,oe;if(!N)return;let y=N.querySelector("svg");y&&y.remove();let A=(oe=De==null?void 0:De.iconSize)!=null?oe:parseFloat((O=(j=(I=n.voiceRecognition)==null?void 0:I.iconSize)!=null?j:(L=n.sendButton)==null?void 0:L.size)!=null?O:"40")||24,k=me(l,A,g,1.5);k&&N.appendChild(k)},Qn=()=>{N&&N.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},_n=()=>{var k,I;if(!N)return;gr();let l=(k=n.voiceRecognition)!=null?k:{},g=(I=l.recordingBackgroundColor)!=null?I:"#ef4444",y=l.recordingIconColor,A=l.recordingBorderColor;if(Qn(),N.classList.add("persona-voice-recording"),N.style.backgroundColor=g,y){N.style.color=y;let L=N.querySelector("svg");L&&L.setAttribute("stroke",y)}A&&(N.style.borderColor=A),N.setAttribute("aria-label","Stop voice recognition")},bo=()=>{var j,O,oe,he,Se,Re,Le,B;if(!N)return;gr();let l=(j=n.voiceRecognition)!=null?j:{},g=D.getVoiceInterruptionMode(),y=(O=l.processingIconName)!=null?O:"loader",A=(he=(oe=l.processingIconColor)!=null?oe:De==null?void 0:De.color)!=null?he:"",k=(Re=(Se=l.processingBackgroundColor)!=null?Se:De==null?void 0:De.backgroundColor)!=null?Re:"",I=(B=(Le=l.processingBorderColor)!=null?Le:De==null?void 0:De.borderColor)!=null?B:"";Qn(),N.classList.add("persona-voice-processing"),N.style.backgroundColor=k,N.style.borderColor=I;let L=A||"currentColor";N.style.color=L,mr(y,L),N.setAttribute("aria-label","Processing voice input"),g==="none"&&(N.style.cursor="default")},xo=()=>{var oe,he,Se,Re,Le,B,Pe,Ie,ae,He,et,Je;if(!N)return;gr();let l=(oe=n.voiceRecognition)!=null?oe:{},g=D.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",A=(he=l.speakingIconName)!=null?he:y,k=(B=l.speakingIconColor)!=null?B:g==="barge-in"?(Re=(Se=l.recordingIconColor)!=null?Se:De==null?void 0:De.color)!=null?Re:"":(Le=De==null?void 0:De.color)!=null?Le:"",I=(ae=l.speakingBackgroundColor)!=null?ae:g==="barge-in"?(Pe=l.recordingBackgroundColor)!=null?Pe:"#ef4444":(Ie=De==null?void 0:De.backgroundColor)!=null?Ie:"",L=(Je=l.speakingBorderColor)!=null?Je:g==="barge-in"?(He=l.recordingBorderColor)!=null?He:"":(et=De==null?void 0:De.borderColor)!=null?et:"";Qn(),N.classList.add("persona-voice-speaking"),N.style.backgroundColor=I,N.style.borderColor=L;let j=k||"currentColor";N.style.color=j,mr(A,j);let O=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";N.setAttribute("aria-label",O),g==="none"&&(N.style.cursor="default"),g==="barge-in"&&N.classList.add("persona-voice-recording")},mn=()=>{var l,g,y;N&&(Qn(),De&&(N.style.backgroundColor=(l=De.backgroundColor)!=null?l:"",N.style.color=(g=De.color)!=null?g:"",N.style.borderColor=(y=De.borderColor)!=null?y:"",mr(De.iconName,De.color||"currentColor"),De=null),N.style.cursor="",N.setAttribute("aria-label","Start voice recognition"))},er=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.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(()=>{qe.active=!1,qe.manuallyDeactivated=!0,Gt(),an("user"),mn()});return}D.toggleVoice().then(()=>{qe.active=D.isVoiceActive(),qe.manuallyDeactivated=!D.isVoiceActive(),Gt(),an("user"),D.isVoiceActive()?_n():mn()});return}if(nn){let y=G.value.trim();qe.manuallyDeactivated=!0,Gt(),gn("user"),y&&(G.value="",G.style.height="auto",D.sendMessage(y))}else qe.manuallyDeactivated=!1,Gt(),Zn("user")};st=er,N&&(N.addEventListener("click",er),bt.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(D.isVoiceActive()&&D.toggleVoice(),mn()):gn("system"),N&&N.removeEventListener("click",er)}));let vo=o.on("assistant:complete",()=>{Hr&&(qe.active||qe.manuallyDeactivated||Hr==="assistant"&&!qe.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!qe.active&&!qe.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.toggleVoice().then(()=>{qe.active=D.isVoiceActive(),an("auto"),D.isVoiceActive()&&_n()}):Zn("auto"))},600))});bt.push(vo);let Z=o.on("action:resubmit",()=>{setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)});bt.push(Z);let Oe=()=>{mt(!W,"user")},Te=null,Fe=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>no(n,Oe).element,onToggle:Oe});g&&(Fe=g)}Fe||(Te=no(n,Oe))}Te?e.appendChild(Te.element):Fe&&e.appendChild(Fe),Xn(),On.render(n.suggestionChips,D,G,void 0,n.suggestionChipsConfig),Dr(),pr(D.isStreaming()),Yn(!0),uo(),v&&(b?W&&setTimeout(()=>ur(),200):setTimeout(()=>ur(),0));let xt=()=>{var O,oe,he,Se,Re,Le,B,Pe,Ie,ae,He,et,Je;let l=zt(n),g=(oe=(O=n.launcher)==null?void 0:O.sidebarMode)!=null?oe:!1,y=l||g||((Se=(he=n.launcher)==null?void 0:he.fullHeight)!=null?Se:!1),A=(Re=e.ownerDocument.defaultView)!=null?Re:window,k=(B=(Le=n.launcher)==null?void 0:Le.mobileFullscreen)!=null?B:!0,I=(Ie=(Pe=n.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Ie:640,L=A.innerWidth<=I,j=k&&L&&b;try{if(j){Jn(),or(e,n);return}if(P&&(P=!1,Jn(),or(e,n)),!b&&!l){re.style.height="",re.style.width="";return}if(!g&&!l){let ge=(He=(ae=n==null?void 0:n.launcher)==null?void 0:ae.width)!=null?He:n==null?void 0:n.launcherWidth,It=ge!=null?ge:"min(400px, calc(100vw - 24px))";re.style.width=It,re.style.maxWidth=It}if(Vn(),!y){let ge=A.innerHeight,It=64,lt=(Je=(et=n.launcher)==null?void 0:et.heightOffset)!=null?Je:0,Zt=Math.max(200,ge-It),Ut=Math.min(640,Zt),Kt=Math.max(200,Ut-lt);re.style.height=`${Kt}px`}}finally{Xn()}};xt();let $t=(ia=e.ownerDocument.defaultView)!=null?ia:window;$t.addEventListener("resize",xt),bt.push(()=>$t.removeEventListener("resize",xt)),Kn=te.scrollTop;let vt=()=>{let l=te.scrollTop,g=te.scrollHeight,y=te.clientHeight,A=g-l-y,k=Math.abs(l-Kn);if(Kn=l,!cr&&!(k<=po)){if(!Ln&&A<Rr){In=!1,Ln=!0;return}Ln&&A>Rr&&(In=!0,lr=Date.now()+co,Ln=!1)}};te.addEventListener("scroll",vt,{passive:!0}),bt.push(()=>te.removeEventListener("scroll",vt)),bt.push(()=>{Pn&&cancelAnimationFrame(Pn)});let C=()=>{ue&&(wn&&(ue.removeEventListener("click",wn),wn=null),b?(ue.style.display="",wn=()=>{mt(!1,"user")},ue.addEventListener("click",wn)):ue.style.display="none")};C(),(()=>{let{clearChatButton:l}=Ue;l&&l.addEventListener("click",()=>{D.clearMessages(),$n.clear();try{localStorage.removeItem(Tr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Tr)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 g=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(g),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={},x.syncFromMetadata(),J==null||J.clear(),V==null||V.update()})})(),Ne&&Ne.addEventListener("submit",Nr),G==null||G.addEventListener("keydown",Or),G==null||G.addEventListener("paste",Fr),bt.push(()=>{Ne&&Ne.removeEventListener("submit",Nr),G==null||G.removeEventListener("keydown",Or),G==null||G.removeEventListener("paste",Fr)}),bt.push(()=>{D.cancel()}),Te?bt.push(()=>{Te==null||Te.destroy()}):Fe&&bt.push(()=>{Fe==null||Fe.remove()});let M={update(l){var ma,fa,ha,ya,ba,xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Pa,Ia,Wa,Ra,Ha,Ba,Da,Na,Oa,Fa,$a,_a,ja,za,qa,Ua,Va,Ja,Ka,Ya,Ga,Xa,Za,Qa,ei,ti,ni,ri,oi,si,ai,ii,li,ci,di,pi,ui,gi,mi,fi,hi,yi,bi,xi,vi,Ci,wi,Si,Ai,Ei,Ti,Mi,ki,Li,Pi,Ii,Wi,Ri,Hi,Bi,Di,Ni,Oi,Fi,$i,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Yi,Gi,Xi,Zi,Qi,el;let g=n.toolCall,y=n.messageActions,A=(ma=n.layout)==null?void 0:ma.messages,k=n.colorScheme,I=n.loadingIndicator,L=n.iterationDisplay;n={...n,...l},Jn(),or(e,n),jo(e,n),zo(e,n),vn(),n.colorScheme!==k&&Pr();let j=qo.getForInstance(n.plugins);s.length=0,s.push(...j),b=(ha=(fa=n.launcher)==null?void 0:fa.enabled)!=null?ha:!0,S=(ba=(ya=n.launcher)==null?void 0:ya.autoExpand)!=null?ba:!1,q=(va=(xa=n.features)==null?void 0:xa.showReasoning)!=null?va:!0,ee=(wa=(Ca=n.features)==null?void 0:Ca.showToolCalls)!=null?wa:!0;let O=Ce;if(Ce=(Aa=(Sa=n.features)==null?void 0:Sa.showEventStreamToggle)!=null?Aa:!1,Ce&&!O){if(J||(ce=new io(ye),J=new ao(Q,ce),ce.open().then(()=>J==null?void 0:J.restore()).catch(()=>{}),D.setSSEEventCallback(($,Ge)=>{J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:$,timestamp:Date.now(),payload:JSON.stringify(Ge)})})),!pe&&Ve){let $=(Ta=(Ea=n.features)==null?void 0:Ea.eventStream)==null?void 0:Ta.classNames,Ge="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-text-persona-muted hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+($!=null&&$.toggleButton?" "+$.toggleButton:"");pe=h("button",Ge),pe.style.width="28px",pe.style.height="28px",pe.type="button",pe.setAttribute("aria-label","Event Stream"),pe.title="Event Stream";let ft=me("activity","18px","currentColor",1.5);ft&&pe.appendChild(ft);let $e=Ue.clearChatButtonWrapper,rt=Ue.closeButtonWrapper,Wt=$e||rt;Wt&&Wt.parentNode===Ve?Ve.insertBefore(pe,Wt):Ve.appendChild(pe),pe.addEventListener("click",()=>{ne?ze():We()})}}else!Ce&&O&&(ze(),pe&&(pe.remove(),pe=null),J==null||J.clear(),ce==null||ce.destroy(),J=null,ce=null);if(((Ma=n.launcher)==null?void 0:Ma.enabled)===!1&&Te&&(Te.destroy(),Te=null),((ka=n.launcher)==null?void 0:ka.enabled)===!1&&Fe&&(Fe.remove(),Fe=null),((La=n.launcher)==null?void 0:La.enabled)!==!1&&!Te&&!Fe){let $=s.find(Ge=>Ge.renderLauncher);if($!=null&&$.renderLauncher){let Ge=$.renderLauncher({config:n,defaultRenderer:()=>no(n,Oe).element,onToggle:Oe});Ge&&(Fe=Ge,e.appendChild(Fe))}Fe||(Te=no(n,Oe),e.appendChild(Te.element))}Te&&Te.update(n),ke&&((Pa=n.launcher)==null?void 0:Pa.title)!==void 0&&(ke.textContent=n.launcher.title),ot&&((Ia=n.launcher)==null?void 0:Ia.subtitle)!==void 0&&(ot.textContent=n.launcher.subtitle);let oe=(Wa=n.layout)==null?void 0:Wa.header;if((oe==null?void 0:oe.layout)!==w&&Ve){let $=oe?ro(n,oe,{showClose:b,onClose:()=>mt(!1,"user")}):jn({config:n,showClose:b,onClose:()=>mt(!1,"user")});Ve.replaceWith($.header),Ve=$.header,Ye=$.iconHolder,ke=$.headerTitle,ot=$.headerSubtitle,ue=$.closeButton,w=oe==null?void 0:oe.layout}else if(oe&&(Ye&&(Ye.style.display=oe.showIcon===!1?"none":""),ke&&(ke.style.display=oe.showTitle===!1?"none":""),ot&&(ot.style.display=oe.showSubtitle===!1?"none":""),ue&&(ue.style.display=oe.showCloseButton===!1?"none":""),Ue.clearChatButtonWrapper)){let $=oe.showClearChat;if($!==void 0){Ue.clearChatButtonWrapper.style.display=$?"":"none";let{closeButtonWrapper:Ge}=Ue;Ge&&!Ge.classList.contains("persona-absolute")&&($?Ge.classList.remove("persona-ml-auto"):Ge.classList.add("persona-ml-auto"))}}let Se=((Ra=n.layout)==null?void 0:Ra.showHeader)!==!1;Ve&&(Ve.style.display=Se?"":"none");let Re=((Ha=n.layout)==null?void 0:Ha.showFooter)!==!1;nt&&(nt.style.display=Re?"":"none"),b!==F?b?mt(S,"auto"):(W=!0,Xn()):S!==T&&mt(S,"auto"),T=S,F=b,xt(),C();let Pe=JSON.stringify(l.toolCall)!==JSON.stringify(g),Ie=JSON.stringify(n.messageActions)!==JSON.stringify(y),ae=JSON.stringify((Ba=n.layout)==null?void 0:Ba.messages)!==JSON.stringify(A),He=((Da=n.loadingIndicator)==null?void 0:Da.render)!==(I==null?void 0:I.render)||((Na=n.loadingIndicator)==null?void 0:Na.renderIdle)!==(I==null?void 0:I.renderIdle)||((Oa=n.loadingIndicator)==null?void 0:Oa.showBubble)!==(I==null?void 0:I.showBubble),et=n.iterationDisplay!==L;(Pe||Ie||ae||He||et)&&D&&(Ir++,Gn(de,D.getMessages(),le));let ge=(Fa=n.launcher)!=null?Fa:{},It=($a=ge.headerIconHidden)!=null?$a:!1,lt=(ja=(_a=n.layout)==null?void 0:_a.header)==null?void 0:ja.showIcon,Zt=It||lt===!1,Ut=ge.headerIconName,Kt=(za=ge.headerIconSize)!=null?za:"48px";if(Ye){let $=z.querySelector(".persona-border-b-persona-divider"),Ge=$==null?void 0:$.querySelector(".persona-flex-col");if(Zt)Ye.style.display="none",$&&Ge&&!$.contains(Ge)&&$.insertBefore(Ge,$.firstChild);else{if(Ye.style.display="",Ye.style.height=Kt,Ye.style.width=Kt,$&&Ge&&($.contains(Ye)?Ye.nextSibling!==Ge&&(Ye.remove(),$.insertBefore(Ye,Ge)):$.insertBefore(Ye,Ge)),Ut){let $e=parseFloat(Kt)||24,rt=me(Ut,$e*.6,"#ffffff",2);rt?Ye.replaceChildren(rt):Ye.textContent=(qa=ge.agentIconText)!=null?qa:"\u{1F4AC}"}else if(ge.iconUrl){let $e=Ye.querySelector("img");if($e)$e.src=ge.iconUrl,$e.style.height=Kt,$e.style.width=Kt;else{let rt=document.createElement("img");rt.src=ge.iconUrl,rt.alt="",rt.className="persona-rounded-xl persona-object-cover",rt.style.height=Kt,rt.style.width=Kt,Ye.replaceChildren(rt)}}else{let $e=Ye.querySelector("svg"),rt=Ye.querySelector("img");($e||rt)&&Ye.replaceChildren(),Ye.textContent=(Ua=ge.agentIconText)!=null?Ua:"\u{1F4AC}"}let ft=Ye.querySelector("img");ft&&(ft.style.height=Kt,ft.style.width=Kt)}}let Nt=(Ja=(Va=n.layout)==null?void 0:Va.header)==null?void 0:Ja.showTitle,cn=(Ya=(Ka=n.layout)==null?void 0:Ka.header)==null?void 0:Ya.showSubtitle;if(ke&&(ke.style.display=Nt===!1?"none":""),ot&&(ot.style.display=cn===!1?"none":""),ue){((Xa=(Ga=n.layout)==null?void 0:Ga.header)==null?void 0:Xa.showCloseButton)===!1?ue.style.display="none":ue.style.display="";let Ge=(Za=ge.closeButtonSize)!=null?Za:"32px",ft=(Qa=ge.closeButtonPlacement)!=null?Qa:"inline";ue.style.height=Ge,ue.style.width=Ge;let{closeButtonWrapper:$e}=Ue,rt=ft==="top-right",Wt=$e==null?void 0:$e.classList.contains("persona-absolute");if($e&&rt!==Wt)if($e.remove(),rt)$e.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",z.style.position="relative",z.appendChild($e);else{let Ze=(ti=(ei=ge.clearChat)==null?void 0:ei.placement)!=null?ti:"inline",Ot=(ri=(ni=ge.clearChat)==null?void 0:ni.enabled)!=null?ri:!0;$e.className=Ot&&Ze==="inline"?"":"persona-ml-auto";let en=z.querySelector(".persona-border-b-persona-divider");en&&en.appendChild($e)}if(ue.style.color=ge.closeButtonColor||bn.actionIconColor,ge.closeButtonBackgroundColor?(ue.style.backgroundColor=ge.closeButtonBackgroundColor,ue.classList.remove("hover:persona-bg-gray-100")):(ue.style.backgroundColor="",ue.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let Ze=ge.closeButtonBorderWidth||"0px",Ot=ge.closeButtonBorderColor||"transparent";ue.style.border=`${Ze} solid ${Ot}`,ue.classList.remove("persona-border-none")}else ue.style.border="",ue.classList.add("persona-border-none");ge.closeButtonBorderRadius?(ue.style.borderRadius=ge.closeButtonBorderRadius,ue.classList.remove("persona-rounded-full")):(ue.style.borderRadius="",ue.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(ue.style.paddingLeft=ge.closeButtonPaddingX,ue.style.paddingRight=ge.closeButtonPaddingX):(ue.style.paddingLeft="",ue.style.paddingRight=""),ge.closeButtonPaddingY?(ue.style.paddingTop=ge.closeButtonPaddingY,ue.style.paddingBottom=ge.closeButtonPaddingY):(ue.style.paddingTop="",ue.style.paddingBottom="");let jt=(oi=ge.closeButtonIconName)!=null?oi:"x",fn=(si=ge.closeButtonIconText)!=null?si:"\xD7";ue.innerHTML="";let Yt=me(jt,"20px","currentColor",2);Yt?ue.appendChild(Yt):ue.textContent=fn;let St=(ai=ge.closeButtonTooltipText)!=null?ai:"Close chat",rn=(ii=ge.closeButtonShowTooltip)!=null?ii:!0;if(ue.setAttribute("aria-label",St),$e&&($e._cleanupTooltip&&($e._cleanupTooltip(),delete $e._cleanupTooltip),rn&&St)){let Ze=null,Ot=()=>{if(Ze||!ue)return;let tr=ue.ownerDocument,Ur=tr.body;if(!Ur)return;Ze=An(tr,"div","persona-clear-chat-tooltip"),Ze.textContent=St;let Vr=An(tr,"div");Vr.className="persona-clear-chat-tooltip-arrow",Ze.appendChild(Vr);let nr=ue.getBoundingClientRect();Ze.style.position="fixed",Ze.style.left=`${nr.left+nr.width/2}px`,Ze.style.top=`${nr.top-8}px`,Ze.style.transform="translate(-50%, -100%)",Ur.appendChild(Ze)},en=()=>{Ze&&Ze.parentNode&&(Ze.parentNode.removeChild(Ze),Ze=null)};$e.addEventListener("mouseenter",Ot),$e.addEventListener("mouseleave",en),ue.addEventListener("focus",Ot),ue.addEventListener("blur",en),$e._cleanupTooltip=()=>{en(),$e&&($e.removeEventListener("mouseenter",Ot),$e.removeEventListener("mouseleave",en)),ue&&(ue.removeEventListener("focus",Ot),ue.removeEventListener("blur",en))}}}let{clearChatButton:Ke,clearChatButtonWrapper:yt}=Ue;if(Ke){let $=(li=ge.clearChat)!=null?li:{},Ge=(ci=$.enabled)!=null?ci:!0,ft=(pi=(di=n.layout)==null?void 0:di.header)==null?void 0:pi.showClearChat,$e=ft!==void 0?ft:Ge,rt=(ui=$.placement)!=null?ui:"inline";if(yt){yt.style.display=$e?"":"none";let{closeButtonWrapper:Wt}=Ue;Wt&&!Wt.classList.contains("persona-absolute")&&($e?Wt.classList.remove("persona-ml-auto"):Wt.classList.add("persona-ml-auto"));let jt=rt==="top-right",fn=yt.classList.contains("persona-absolute");if(jt!==fn&&$e){if(yt.remove(),jt)yt.className="persona-absolute persona-top-4 persona-z-50",yt.style.right="48px",z.style.position="relative",z.appendChild(yt);else{yt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",yt.style.right="";let St=z.querySelector(".persona-border-b-persona-divider"),rn=Ue.closeButtonWrapper;St&&rn&&rn.parentElement===St?St.insertBefore(yt,rn):St&&St.appendChild(yt)}let Yt=Ue.closeButtonWrapper;Yt&&!Yt.classList.contains("persona-absolute")&&(jt?Yt.classList.add("persona-ml-auto"):Yt.classList.remove("persona-ml-auto"))}}if($e){let Wt=(gi=$.size)!=null?gi:"32px";Ke.style.height=Wt,Ke.style.width=Wt;let jt=(mi=$.iconName)!=null?mi:"refresh-cw",fn=(fi=$.iconColor)!=null?fi:"";Ke.style.color=fn||bn.actionIconColor,Ke.innerHTML="";let Yt=me(jt,"20px","currentColor",2);if(Yt&&Ke.appendChild(Yt),$.backgroundColor?(Ke.style.backgroundColor=$.backgroundColor,Ke.classList.remove("hover:persona-bg-gray-100")):(Ke.style.backgroundColor="",Ke.classList.add("hover:persona-bg-gray-100")),$.borderWidth||$.borderColor){let Ze=$.borderWidth||"0px",Ot=$.borderColor||"transparent";Ke.style.border=`${Ze} solid ${Ot}`,Ke.classList.remove("persona-border-none")}else Ke.style.border="",Ke.classList.add("persona-border-none");$.borderRadius?(Ke.style.borderRadius=$.borderRadius,Ke.classList.remove("persona-rounded-full")):(Ke.style.borderRadius="",Ke.classList.add("persona-rounded-full")),$.paddingX?(Ke.style.paddingLeft=$.paddingX,Ke.style.paddingRight=$.paddingX):(Ke.style.paddingLeft="",Ke.style.paddingRight=""),$.paddingY?(Ke.style.paddingTop=$.paddingY,Ke.style.paddingBottom=$.paddingY):(Ke.style.paddingTop="",Ke.style.paddingBottom="");let St=(hi=$.tooltipText)!=null?hi:"Clear chat",rn=(yi=$.showTooltip)!=null?yi:!0;if(Ke.setAttribute("aria-label",St),yt&&(yt._cleanupTooltip&&(yt._cleanupTooltip(),delete yt._cleanupTooltip),rn&&St)){let Ze=null,Ot=()=>{if(Ze||!Ke)return;let tr=Ke.ownerDocument,Ur=tr.body;if(!Ur)return;Ze=An(tr,"div","persona-clear-chat-tooltip"),Ze.textContent=St;let Vr=An(tr,"div");Vr.className="persona-clear-chat-tooltip-arrow",Ze.appendChild(Vr);let nr=Ke.getBoundingClientRect();Ze.style.position="fixed",Ze.style.left=`${nr.left+nr.width/2}px`,Ze.style.top=`${nr.top-8}px`,Ze.style.transform="translate(-50%, -100%)",Ur.appendChild(Ze)},en=()=>{Ze&&Ze.parentNode&&(Ze.parentNode.removeChild(Ze),Ze=null)};yt.addEventListener("mouseenter",Ot),yt.addEventListener("mouseleave",en),Ke.addEventListener("focus",Ot),Ke.addEventListener("blur",en),yt._cleanupTooltip=()=>{en(),yt&&(yt.removeEventListener("mouseenter",Ot),yt.removeEventListener("mouseleave",en)),Ke&&(Ke.removeEventListener("focus",Ot),Ke.removeEventListener("blur",en))}}}}let Co=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Uo],wo=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Er.message,Er.messageAndClick];x=Vo({parsers:Co,handlers:wo,getSessionMetadata:u,updateSessionMetadata:p,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),le=ec(n,x,ve),D.updateConfig(n),Gn(de,D.getMessages(),le),On.render(n.suggestionChips,D,G,void 0,n.suggestionChipsConfig),Dr(),pr(D.isStreaming());let So=((bi=n.voiceRecognition)==null?void 0:bi.enabled)===!0,Ao=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Eo=((vi=(xi=n.voiceRecognition)==null?void 0:xi.provider)==null?void 0:vi.type)==="runtype";if(So&&(Ao||Eo))if(!N||!X){let $=yo(n.voiceRecognition,n.sendButton);$&&(N=$.micButton,X=$.micButtonWrapper,kt.insertBefore(X,tt),N.addEventListener("click",er),N.disabled=D.isStreaming())}else{let $=(Ci=n.voiceRecognition)!=null?Ci:{},Ge=(wi=n.sendButton)!=null?wi:{},ft=(Si=$.iconName)!=null?Si:"mic",$e=(Ai=Ge.size)!=null?Ai:"40px",rt=(Ei=$.iconSize)!=null?Ei:$e,Wt=parseFloat(rt)||24;N.style.width=rt,N.style.height=rt,N.style.minWidth=rt,N.style.minHeight=rt;let jt=(Mi=(Ti=$.iconColor)!=null?Ti:Ge.textColor)!=null?Mi:"currentColor";N.innerHTML="";let fn=me(ft,Wt,jt,2);fn?N.appendChild(fn):N.textContent="\u{1F3A4}";let Yt=(ki=$.backgroundColor)!=null?ki:Ge.backgroundColor;Yt?(N.style.backgroundColor=Yt,N.classList.remove("persona-bg-persona-primary")):(N.style.backgroundColor="",N.classList.add("persona-bg-persona-primary")),jt?(N.style.color=jt,N.classList.remove("persona-text-white")):!jt&&!Ge.textColor&&(N.style.color="",N.classList.add("persona-text-white")),$.borderWidth?(N.style.borderWidth=$.borderWidth,N.style.borderStyle="solid"):(N.style.borderWidth="",N.style.borderStyle=""),$.borderColor?N.style.borderColor=$.borderColor:N.style.borderColor="",$.paddingX?(N.style.paddingLeft=$.paddingX,N.style.paddingRight=$.paddingX):(N.style.paddingLeft="",N.style.paddingRight=""),$.paddingY?(N.style.paddingTop=$.paddingY,N.style.paddingBottom=$.paddingY):(N.style.paddingTop="",N.style.paddingBottom="");let St=X==null?void 0:X.querySelector(".persona-send-button-tooltip"),rn=(Li=$.tooltipText)!=null?Li:"Start voice recognition";if(((Pi=$.showTooltip)!=null?Pi:!1)&&rn)if(St)St.textContent=rn,St.style.display="";else{let Ot=document.createElement("div");Ot.className="persona-send-button-tooltip",Ot.textContent=rn,X==null||X.insertBefore(Ot,N)}else St&&(St.style.display="none");X.style.display="",N.disabled=D.isStreaming()}else N&&X&&(X.style.display="none",((Wi=(Ii=n.voiceRecognition)==null?void 0:Ii.provider)==null?void 0:Wi.type)==="runtype"?D.isVoiceActive()&&D.toggleVoice():nn&&gn());if(((Ri=n.attachments)==null?void 0:Ri.enabled)===!0)if(!be||!_){let $=(Hi=n.attachments)!=null?Hi:{},ft=(Di=((Bi=n.sendButton)!=null?Bi:{}).size)!=null?Di:"40px";Ae||(Ae=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Ae.style.display="none",Ne.insertBefore(Ae,G)),xe||(xe=document.createElement("input"),xe.type="file",xe.accept=((Ni=$.allowedTypes)!=null?Ni:Hn).join(","),xe.multiple=((Oi=$.maxFiles)!=null?Oi:4)>1,xe.style.display="none",xe.setAttribute("aria-label","Attach files"),Ne.insertBefore(xe,G)),be=h("div","persona-send-button-wrapper"),_=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),_.type="button",_.setAttribute("aria-label",(Fi=$.buttonTooltipText)!=null?Fi:"Attach file");let $e=($i=$.buttonIconName)!=null?$i:"paperclip",rt=ft,Wt=parseFloat(rt)||40,jt=Math.round(Wt*.6);_.style.width=rt,_.style.height=rt,_.style.minWidth=rt,_.style.minHeight=rt,_.style.fontSize="18px",_.style.lineHeight="1",_.style.backgroundColor="transparent",_.style.color="var(--persona-primary, #111827)",_.style.border="none",_.style.borderRadius="6px",_.style.transition="background-color 0.15s ease",_.addEventListener("mouseenter",()=>{_.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),_.addEventListener("mouseleave",()=>{_.style.backgroundColor="transparent"});let fn=me($e,jt,"currentColor",1.5);fn?_.appendChild(fn):_.textContent="\u{1F4CE}",_.addEventListener("click",rn=>{rn.preventDefault(),xe==null||xe.click()}),be.appendChild(_);let Yt=(_i=$.buttonTooltipText)!=null?_i:"Attach file",St=h("div","persona-send-button-tooltip");St.textContent=Yt,be.appendChild(St),Ht.append(be),!Ee&&xe&&Ae&&(Ee=xr.fromConfig($),Ee.setPreviewsContainer(Ae),xe.addEventListener("change",async()=>{Ee&&(xe!=null&&xe.files)&&(await Ee.handleFileSelect(xe.files),xe.value="")}))}else{be.style.display="";let $=(ji=n.attachments)!=null?ji:{};xe&&(xe.accept=((zi=$.allowedTypes)!=null?zi:Hn).join(","),xe.multiple=((qi=$.maxFiles)!=null?qi:4)>1),Ee&&Ee.updateConfig({allowedTypes:$.allowedTypes,maxFileSize:$.maxFileSize,maxFiles:$.maxFiles})}else be&&(be.style.display="none"),Ee&&Ee.clearAttachments();let Et=(Ui=n.sendButton)!=null?Ui:{},To=(Vi=Et.useIcon)!=null?Vi:!1,_r=(Ji=Et.iconText)!=null?Ji:"\u2191",Qt=Et.iconName,dn=(Ki=Et.tooltipText)!=null?Ki:"Send message",Mo=(Yi=Et.showTooltip)!=null?Yi:!1,jr=(Gi=Et.size)!=null?Gi:"40px",ko=Et.backgroundColor,Sn=Et.textColor;if(To){if(Y.style.width=jr,Y.style.height=jr,Y.style.minWidth=jr,Y.style.minHeight=jr,Y.style.fontSize="18px",Y.style.lineHeight="1",Y.innerHTML="",Qt){let $=parseFloat(jr)||24,Ge=Sn&&typeof Sn=="string"&&Sn.trim()?Sn.trim():"currentColor",ft=me(Qt,$,Ge,2);ft?(Y.appendChild(ft),Y.style.color=Ge):(Y.textContent=_r,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white"))}else Y.textContent=_r,Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");Y.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-primary")):Y.classList.add("persona-bg-persona-primary")}else Y.textContent=(Zi=(Xi=n.copy)==null?void 0:Xi.sendButtonLabel)!=null?Zi:"Send",Y.style.width="",Y.style.height="",Y.style.minWidth="",Y.style.minHeight="",Y.style.fontSize="",Y.style.lineHeight="",Y.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",ko?(Y.style.backgroundColor=ko,Y.classList.remove("persona-bg-persona-accent")):Y.classList.add("persona-bg-persona-accent"),Sn?Y.style.color=Sn:Y.classList.add("persona-text-white");Et.borderWidth?(Y.style.borderWidth=Et.borderWidth,Y.style.borderStyle="solid"):(Y.style.borderWidth="",Y.style.borderStyle=""),Et.borderColor?Y.style.borderColor=Et.borderColor:Y.style.borderColor="",Et.paddingX?(Y.style.paddingLeft=Et.paddingX,Y.style.paddingRight=Et.paddingX):(Y.style.paddingLeft="",Y.style.paddingRight=""),Et.paddingY?(Y.style.paddingTop=Et.paddingY,Y.style.paddingBottom=Et.paddingY):(Y.style.paddingTop="",Y.style.paddingBottom="");let zr=tt==null?void 0:tt.querySelector(".persona-send-button-tooltip");if(Mo&&dn)if(zr)zr.textContent=dn,zr.style.display="";else{let $=document.createElement("div");$.className="persona-send-button-tooltip",$.textContent=dn,tt==null||tt.insertBefore($,Y)}else zr&&(zr.style.display="none");let qr=(Qi=n.statusIndicator)!=null?Qi:{},Pc=(el=qr.visible)!=null?el:!0;if(je.style.display=Pc?"":"none",D){let $=D.getStatus(),Ge=ft=>{var $e,rt,Wt,jt;return ft==="idle"?($e=qr.idleText)!=null?$e:Vt.idle:ft==="connecting"?(rt=qr.connectingText)!=null?rt:Vt.connecting:ft==="connected"?(Wt=qr.connectedText)!=null?Wt:Vt.connected:ft==="error"?(jt=qr.errorText)!=null?jt:Vt.error:Vt[ft]};je.textContent=Ge($)}},open(){b&&mt(!0,"api")},close(){b&&mt(!1,"api")},toggle(){b&&mt(!W,"api")},clearChat(){K=!1,D.clearMessages(),$n.clear();try{localStorage.removeItem(Tr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Tr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Tr)try{localStorage.removeItem(n.clearChatHistoryStorageKey),n.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${n.clearChatHistoryStorageKey}`)}catch(g){console.error("[AgentWidget] Failed to clear custom localStorage:",g)}let l=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(l),a!=null&&a.clear)try{let g=a.clear();g instanceof Promise&&g.catch(y=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)})}catch(g){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",g)}i={},x.syncFromMetadata(),J==null||J.clear(),V==null||V.update()},setMessage(l){return!G||D.isStreaming()?!1:(!W&&b&&mt(!0,"system"),G.value=l,G.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(D.isStreaming())return!1;let g=(l==null?void 0:l.trim())||G.value.trim();return g?(!W&&b&&mt(!0,"system"),G.value="",G.style.height="auto",D.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return D.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(D.isVoiceActive()||(!W&&b&&mt(!0,"system"),qe.manuallyDeactivated=!1,Gt(),D.toggleVoice().then(()=>{qe.active=D.isVoiceActive(),an("user"),D.isVoiceActive()&&_n()})),!0):nn?!0:$r()?(!W&&b&&mt(!0,"system"),qe.manuallyDeactivated=!1,Gt(),Zn("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?D.isVoiceActive()?(D.toggleVoice().then(()=>{qe.active=!1,qe.manuallyDeactivated=!0,Gt(),an("user"),mn()}),!0):!1:nn?(qe.manuallyDeactivated=!0,Gt(),gn("user"),!0):!1},injectMessage(l){return!W&&b&&mt(!0,"system"),D.injectMessage(l)},injectAssistantMessage(l){!W&&b&&mt(!0,"system");let g=D.injectAssistantMessage(l);return R&&(R=!1,U&&(clearTimeout(U),U=null),setTimeout(()=>{D&&!D.isStreaming()&&D.continueConversation()},100)),g},injectUserMessage(l){return!W&&b&&mt(!0,"system"),D.injectUserMessage(l)},injectSystemMessage(l){return!W&&b&&mt(!0,"system"),D.injectSystemMessage(l)},injectMessageBatch(l){return!W&&b&&mt(!0,"system"),D.injectMessageBatch(l)},injectTestMessage(l){!W&&b&&mt(!0,"system"),D.injectTestEvent(l)},async connectStream(l,g){return D.connectStream(l,g)},__pushEventStreamEvent(l){J&&J.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!Ce||!J||We()},hideEventStream(){ne&&ze()},isEventStreamVisible(){return ne},showArtifacts(){pn(n)&&(K=!1,vn(),Xe==null||Xe.setMobileOpen(!0))},hideArtifacts(){pn(n)&&(K=!0,vn())},upsertArtifact(l){return pn(n)?(K=!1,D.upsertArtifact(l)):null},selectArtifact(l){pn(n)&&D.selectArtifact(l)},clearArtifacts(){pn(n)&&D.clearArtifacts()},focusInput(){return b&&!W||!G?!1:(G.focus(),!0)},async resolveApproval(l,g){let A=D.getMessages().find(k=>{var I;return k.variant==="approval"&&((I=k.approval)==null?void 0:I.id)===l});if(!(A!=null&&A.approval))throw new Error(`Approval not found: ${l}`);return D.resolveApproval(A.approval,g)},getMessages(){return D.getMessages()},getStatus(){return D.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){p(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&W},isVoiceActive(){return qe.active},getState(){return{open:b&&W,launcherEnabled:b,voiceActive:qe.active,streaming:D.isStreaming()}},showCSATFeedback(l){!W&&b&&mt(!0,"system");let g=de.querySelector(".persona-feedback-container");g&&g.remove();let y=Is({onSubmit:async(A,k)=>{var I;D.isClientTokenMode()&&await D.submitCSATFeedback(A,k),(I=l==null?void 0:l.onSubmit)==null||I.call(l,A,k)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!W&&b&&mt(!0,"system");let g=de.querySelector(".persona-feedback-container");g&&g.remove();let y=Ws({onSubmit:async(A,k)=>{var I;D.isClientTokenMode()&&await D.submitNPSFeedback(A,k),(I=l==null?void 0:l.onSubmit)==null||I.call(l,A,k)},onDismiss:l==null?void 0:l.onDismiss,...l});de.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return D.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return D.submitNPSFeedback(l,g)},destroy(){bt.forEach(l=>l()),se.remove(),Te==null||Te.destroy(),Fe==null||Fe.remove(),wn&&ue.removeEventListener("click",wn)}};if((((la=t==null?void 0:t.debugTools)!=null?la:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:M,getMessages:M.getMessages,getStatus:M.getStatus,getMetadata:M.getPersistentMetadata,updateMetadata:M.updatePersistentMetadata,clearHistory:()=>M.clearChat(),setVoiceActive:y=>y?M.startVoiceRecognition():M.stopVoiceRecognition()};window.AgentWidgetBrowser=g,bt.push(()=>{window.AgentWidgetBrowser===g&&(window.AgentWidgetBrowser=l)})}if(typeof window!="undefined"){let l=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),g=j=>{let O=j.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&M.focusInput()};if(window.addEventListener("persona:focusInput",g),bt.push(()=>{window.removeEventListener("persona:focusInput",g)}),Ce){let j=oe=>{let he=oe.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&M.showEventStream()},O=oe=>{let he=oe.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&M.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",O),bt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",O)})}let y=j=>{let O=j.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&M.showArtifacts()},A=j=>{let O=j.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&M.hideArtifacts()},k=j=>{let O=j.detail;O!=null&&O.instanceId&&O.instanceId!==l||O!=null&&O.artifact&&M.upsertArtifact(O.artifact)},I=j=>{let O=j.detail;O!=null&&O.instanceId&&O.instanceId!==l||typeof(O==null?void 0:O.id)=="string"&&M.selectArtifact(O.id)},L=j=>{let O=j.detail;(!(O!=null&&O.instanceId)||O.instanceId===l)&&M.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",A),window.addEventListener("persona:upsertArtifact",k),window.addEventListener("persona:selectArtifact",I),window.addEventListener("persona:clearArtifacts",L),bt.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",A),window.removeEventListener("persona:upsertArtifact",k),window.removeEventListener("persona:selectArtifact",I),window.removeEventListener("persona:clearArtifacts",L)})}let H=np(n.persistState);if(H&&b){let l=rp(H.storage),g=`${H.keyPrefix}widget-open`,y=`${H.keyPrefix}widget-voice`,A=`${H.keyPrefix}widget-voice-mode`;if(l){let k=((ca=H.persist)==null?void 0:ca.openState)&&l.getItem(g)==="true",I=((da=H.persist)==null?void 0:da.voiceState)&&l.getItem(y)==="true",L=((pa=H.persist)==null?void 0:pa.voiceState)&&l.getItem(A)==="true";if(k&&setTimeout(()=>{M.open(),setTimeout(()=>{var j;if(I||L)M.startVoiceRecognition();else if((j=H.persist)!=null&&j.focusInput){let O=e.querySelector("textarea");O&&O.focus()}},100)},0),(ua=H.persist)!=null&&ua.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ga=H.persist)!=null&&ga.voiceState&&(o.on("voice:state",j=>{l.setItem(y,j.active?"true":"false")}),o.on("user:message",j=>{l.setItem(A,j.viaVoice?"true":"false")})),H.clearOnChatClear){let j=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(A)},O=()=>j();window.addEventListener("persona:clear-chat",O),bt.push(()=>{window.removeEventListener("persona:clear-chat",O)})}}}return M};var op=(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},tc=(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"},Os=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=""},nc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",Os(e)},Bs=e=>{e.style.transition=""},Ds=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=""},Ns=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Jo=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},sp=(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))},ap=(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)},rc=(e,r,t,n,s,o,a)=>{var x,b,S,v;let i=hn(o),d=i.reveal==="push";sp(e,r,t,n,d),ap(e,r,t,n,i.side,d),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,u=(b=(x=o==null?void 0:o.launcher)==null?void 0:x.mobileFullscreen)!=null?b:!0,p=(v=(S=o==null?void 0:o.launcher)==null?void 0:S.mobileBreakpoint)!=null?v:640,f=c!=null?c.innerWidth<=p:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Ds(r),Bs(n),nc(n),Ns(t),Jo(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="9999",n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",d&&(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"),nc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Ds(r),Bs(n),Ns(t),Jo(s,n);let T=i.animate?"transform 180ms ease":"none",F=i.side==="right"?"translateX(100%)":"translateX(-100%)",w=a?"translateX(0)":F;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=T,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",Bs(n),Os(n),Jo(s,n);let T=op(i.width,e.clientWidth),F=Math.max(0,e.clientWidth),w=i.animate?"transform 180ms ease":"none",P=i.side==="right"?a?`translateX(-${T}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${T}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=`${F+T}px`,r.style.transition=w,r.style.transform=P,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${F}px`,t.style.maxWidth=`${F}px`,t.style.minWidth=`${F}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="",Ds(r),Os(n),Ns(t),Jo(s,n);let T=i.reveal==="emerge";T?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let F=a?i.width:"0px",w=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",P=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${F}`,n.style.width=F,n.style.maxWidth=F,n.style.minWidth=F,n.style.minHeight="0",n.style.position="relative",n.style.overflow=T||P?"hidden":"visible",n.style.transition=w,T&&(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")}},ip=(e,r)=>{let t=e.ownerDocument.createElement("div");return tc(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){tc(t,n)},destroy(){t.remove()}}},lp=(e,r)=>{var T,F,w,P;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"),d=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),p=(F=(T=r==null?void 0:r.launcher)==null?void 0:T.enabled)==null||F?(P=(w=r==null?void 0:r.launcher)==null?void 0:w.autoExpand)!=null?P:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),d.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},x=()=>{m(),hn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{rc(a,i,d,c,u,r,p)}),f.observe(a))},b=()=>{rc(a,i,d,c,u,r,p),x()},S=a.ownerDocument.defaultView,v=()=>{b()};return S==null||S.addEventListener("resize",v),hn(r).reveal==="push"?(i.appendChild(d),i.appendChild(c),a.appendChild(i)):(a.appendChild(d),a.appendChild(c)),b(),{mode:"docked",host:u,shell:a,syncWidgetState(W){let R=W.launcherEnabled?W.open:!0;p!==R&&(p=R,b())},updateConfig(W){var R,U;r=W,((U=(R=r==null?void 0:r.launcher)==null?void 0:R.enabled)!=null?U:!0)===!1&&(p=!0),b()},destroy(){S==null||S.removeEventListener("resize",v),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Ko=(e,r)=>zt(r)?lp(e,r):ip(e,r);var Fs={},cp=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},dp=()=>{try{if(typeof Fs!="undefined"&&Fs.url)return new URL("../widget.css",Fs.url).href}catch{}return null},oc=(e,r)=>{let t=dp(),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)}},sc=e=>{var S;let r=cp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Ko(r,s),a,i=[],d=(v,T)=>{var W,R;let w=!((R=(W=T==null?void 0:T.launcher)==null?void 0:W.enabled)!=null?R:!0)||zt(T),P=n.createElement("div");if(P.setAttribute("data-persona-root","true"),w&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),t){let U=v.attachShadow({mode:"open"});U.appendChild(P),oc(U,n)}else v.appendChild(P),oc(v,n);return r.id&&P.setAttribute("data-persona-instance",r.id),P},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(v=>v()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},p=()=>{let v=d(o.host,s);a=Hs(v,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(v=>v()),i=[],a.destroy()};p(),(S=e.onReady)==null||S.call(e);let m=v=>{f(),o.destroy(),o=Ko(r,v),s=v,p()},x={update(v){var P,W,R,U,ve,le;let T={...s,...v,launcher:{...(P=s==null?void 0:s.launcher)!=null?P:{},...(W=v==null?void 0:v.launcher)!=null?W:{},dock:{...(U=(R=s==null?void 0:s.launcher)==null?void 0:R.dock)!=null?U:{},...(le=(ve=v==null?void 0:v.launcher)==null?void 0:ve.dock)!=null?le:{}}}},F=zt(s),w=zt(T);if(F!==w){m(T);return}s=T,o.updateConfig(s),a.update(v),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},b=new Proxy(x,{get(v,T,F){if(T==="host")return o.host;if(T in v)return Reflect.get(v,T,F);let w=a[T];return typeof w=="function"?w.bind(a):w}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=b),b};var dc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),pp=new Set(["button","a","input","select","textarea","details","summary"]),up=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),$s=/\b(product|card|item|listing|result)\b/i,js=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,gp=3e3,mp=100;function pc(e){let r=typeof e.className=="string"?e.className:"";if($s.test(r)||e.id&&$s.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&$s.test(n.value))return!0}return!1}function uc(e){var r;return js.test(((r=e.textContent)!=null?r:"").trim())}function gc(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 fp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function ac(e){let r=e.match(js);return r?r[0]:null}function ic(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 hp(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 yp="commerce-card",bp="result-card";function lc(e){return!pc(e)||!uc(e)||!gc(e)&&!fp(e)?0:5200}function cc(e){var n;return!pc(e)||uc(e)||!gc(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 mc=[{id:yp,scoreElement(e){return lc(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||js.test(n)&&n.length<32)}return!0},formatSummary(e,r){var d,c,u;if(lc(e)===0)return null;let{title:t,href:n}=ic(e),s=(u=(c=ac(((d=e.textContent)!=null?d:"").trim()))!=null?c:ac(r.text))!=null?u:"",o=hp(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(`
96
+ `)}},{id:bp,scoreElement(e){return cc(e)},formatSummary(e,r){if(cc(e)===0)return null;let{title:t,href:n}=ic(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
97
+ `)}}];function xp(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function vp(e){var u,p,f,m,x,b,S,v,T,F,w,P,W;let r=(u=e.options)!=null?u:{},t=(f=(p=r.maxElements)!=null?p:e.maxElements)!=null?f:80,n=(x=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?x:".persona-host",s=(S=(b=r.maxTextLength)!=null?b:e.maxTextLength)!=null?S:200,o=(T=(v=r.visibleOnly)!=null?v:e.visibleOnly)!=null?T:!0,a=(F=r.root)!=null?F:e.root,i=(w=r.mode)!=null?w:"structured",d=(P=r.maxCandidates)!=null?P:Math.max(500,t*10),c=(W=e.rules)!=null?W:mc;return i==="simple"&&e.rules&&e.rules.length>0?(xp(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:d,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function _s(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Cp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function wp(e){let r=e.tagName.toLowerCase(),t=e.getAttribute("role");return r==="a"&&e.hasAttribute("href")?"navigable":r==="input"||r==="select"||r==="textarea"||t==="textbox"||t==="combobox"||t==="listbox"||t==="spinbutton"?"input":r==="button"||t==="button"||pp.has(r)||t&&up.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function fc(e){if(e.hidden)return!1;try{let r=getComputedStyle(e);if(r.display==="none"||r.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function Sp(e){let r={},t=e.id;t&&(r.id=t);let n=e.getAttribute("href");n&&(r.href=n);let s=e.getAttribute("aria-label");s&&(r["aria-label"]=s);let o=e.getAttribute("type");o&&(r.type=o);let a=e.getAttribute("value");a&&(r.value=a);let i=e.getAttribute("name");i&&(r.name=i);let d=e.getAttribute("role");d&&(r.role=d);for(let c=0;c<e.attributes.length;c++){let u=e.attributes[c];u.name.startsWith("data-")&&(r[u.name]=u.value)}return r}function hc(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${_s(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Cp){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${_s(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=`${r}.${t.map(a=>_s(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 > ${r}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let n=e.parentElement;if(n){let o=Array.from(n.querySelectorAll(`:scope > ${r}`)).indexOf(e);if(o>=0)return`${r}:nth-of-type(${o+1})`}return r}function Ap(e){return e==="static"?mp:gp}function yc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:hc(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:wp(e),attributes:Sp(e)}}function Ep(e,r,t,n){let s=Ap(r.interactivity),o=null;for(let a of t){let i=a.scoreElement(e,r,n);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function Tp(e,r){var t;for(let n of e)if(r.el!==n.el&&(t=n.formattingRule)!=null&&t.shouldSuppressDescendant&&n.el.contains(r.el)&&n.formattingRule.shouldSuppressDescendant(n.el,r.el,r.enriched))return!0;return!1}function Mp(e,r){let t={doc:r.ownerDocument,maxTextLength:e.maxTextLength},n=new Set,s=[],o=0,a=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let c=i,u=c.tagName.toLowerCase();if(dc.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!fc(c)){i=a.nextNode();continue}let p=yc(c,e.maxTextLength),f=p.text.length>0,m=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(S=>S==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(p.selector)){i=a.nextNode();continue}n.add(p.selector);let{score:x,formattingRule:b}=Ep(c,p,e.rules,t);s.push({el:c,domIndex:o,enriched:p,score:x,formattingRule:b}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let d=[];for(let c of s){if(d.length>=e.maxElements)break;Tp(d,c)||d.push(c)}return d.sort((c,u)=>{let p=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return p!==f?p-f:p===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),d.map(c=>{var f;let u;if((f=c.formattingRule)!=null&&f.formatSummary){let m=c.formattingRule.formatSummary(c.el,c.enriched,t);m&&(u=m)}let p={...c.enriched};return u&&(p.formattedSummary=u),p})}function kp(e,r){let t=[],n=new Set,s=document.createTreeWalker(r,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&t.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,c=d.tagName.toLowerCase();if(dc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!fc(d)){o=s.nextNode();continue}let u=yc(d,e.maxTextLength),p=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!p&&!f){o=s.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let d of t)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function Lp(e={}){var n;let r=vp(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?kp(r,t):Mp(r,t):[]}var Yo=100;function Pp(e,r={}){var o;if(e.length===0)return"No page elements found.";let t=(o=r.mode)!=null?o:"structured",n=[];if(t==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&n.push(`Structured summaries:
98
98
  ${a.map(i=>`- ${i.split(`
99
99
  `).join(`
100
100
  `)}`).join(`
101
- `)}`)}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,Do)}" (clickable)`);r.push(`Interactive elements:
101
+ `)}`)}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,Yo)}" (clickable)`);n.push(`Interactive elements:
102
102
  ${a.join(`
103
- `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Do)}" (navigable)`);r.push(`Navigation links:
103
+ `)}`)}if(s.navigable.length>0){let a=s.navigable.map(i=>`- ${i.selector}${i.attributes.href?`[href="${i.attributes.href}"]`:""}: "${i.text.substring(0,Yo)}" (navigable)`);n.push(`Navigation links:
104
104
  ${a.join(`
105
- `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Do)}" (input)`);r.push(`Form inputs:
105
+ `)}`)}if(s.input.length>0){let a=s.input.map(i=>`- ${i.selector}${i.attributes.type?`[type="${i.attributes.type}"]`:""}: "${i.text.substring(0,Yo)}" (input)`);n.push(`Form inputs:
106
106
  ${a.join(`
107
- `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Do)}"`);r.push(`Content:
107
+ `)}`)}if(s.static.length>0){let a=s.static.map(i=>`- ${i.selector}: "${i.text.substring(0,Yo)}"`);n.push(`Content:
108
108
  ${a.join(`
109
- `)}`)}return r.join(`
109
+ `)}`)}return n.join(`
110
110
 
111
- `)}var pc={name:"@runtypelabs/persona",version:"2.3.1",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{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",postcss:"^8.4.38",rimraf:"^5.0.5",tailwindcss:"^3.4.10",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=18.17.0"},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 vr=pc.version;function Ln(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(n=>n.toString()).join(", ")}]`:e.toString()}function Tp(e){if(e)return{getHeaders:Ln(e.getHeaders),onFeedback:Ln(e.onFeedback),onCopy:Ln(e.onCopy),requestMiddleware:Ln(e.requestMiddleware),actionHandlers:Ln(e.actionHandlers),actionParsers:Ln(e.actionParsers),postprocessMessage:Ln(e.postprocessMessage),contextProviders:Ln(e.contextProviders),streamParser:Ln(e.streamParser)}}var uc=`({ text, message }: any) => {
111
+ `)}var bc={name:"@runtypelabs/persona",version:"3.1.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && npm run build:styles && npm run build:client && npm run build:installer","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{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 Mr=bc.version;function Bn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function Wp(e){if(e)return{getHeaders:Bn(e.getHeaders),onFeedback:Bn(e.onFeedback),onCopy:Bn(e.onCopy),requestMiddleware:Bn(e.requestMiddleware),actionHandlers:Bn(e.actionHandlers),actionParsers:Bn(e.actionParsers),postprocessMessage:Bn(e.postprocessMessage),contextProviders:Bn(e.contextProviders),streamParser:Bn(e.streamParser)}}var xc=`({ text, message }: any) => {
112
112
  const jsonSource = (message as any).rawContent || text || message.content;
113
113
  if (!jsonSource || typeof jsonSource !== 'string') return null;
114
114
  let cleanJson = jsonSource
@@ -121,7 +121,7 @@ ${a.join(`
121
121
  if (parsed.action) return { type: parsed.action, payload: parsed };
122
122
  } catch (e) { return null; }
123
123
  return null;
124
- }`,gc=`function(ctx) {
124
+ }`,vc=`function(ctx) {
125
125
  var jsonSource = ctx.message.rawContent || ctx.text || ctx.message.content;
126
126
  if (!jsonSource || typeof jsonSource !== 'string') return null;
127
127
  var cleanJson = jsonSource
@@ -134,7 +134,7 @@ ${a.join(`
134
134
  if (parsed.action) return { type: parsed.action, payload: parsed };
135
135
  } catch (e) { return null; }
136
136
  return null;
137
- }`,mc=`(action: any, context: any) => {
137
+ }`,Cc=`(action: any, context: any) => {
138
138
  if (action.type !== 'nav_then_click') return;
139
139
  const payload = action.payload || action.raw || {};
140
140
  const url = payload?.page;
@@ -151,7 +151,7 @@ ${a.join(`
151
151
  const targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
152
152
  window.location.href = targetUrl;
153
153
  return { handled: true, displayText: text };
154
- }`,fc=`function(action, context) {
154
+ }`,wc=`function(action, context) {
155
155
  if (action.type !== 'nav_then_click') return;
156
156
  var payload = action.payload || action.raw || {};
157
157
  var url = payload.page;
@@ -168,24 +168,24 @@ ${a.join(`
168
168
  var targetUrl = url.startsWith('http') ? url : new URL(url, window.location.origin).toString();
169
169
  window.location.href = targetUrl;
170
170
  return { handled: true, displayText: text };
171
- }`,Mp=`(parsed: any) => {
171
+ }`,Rp=`(parsed: any) => {
172
172
  if (!parsed || typeof parsed !== 'object') return null;
173
173
  if (parsed.action === 'nav_then_click') return 'Navigating...';
174
174
  if (parsed.action === 'message') return parsed.text || '';
175
175
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
176
176
  return parsed.text || null;
177
- }`,kp=`function(parsed) {
177
+ }`,Hp=`function(parsed) {
178
178
  if (!parsed || typeof parsed !== 'object') return null;
179
179
  if (parsed.action === 'nav_then_click') return 'Navigating...';
180
180
  if (parsed.action === 'message') return parsed.text || '';
181
181
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
182
182
  return parsed.text || null;
183
- }`;function Lp(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 _o(e){var n,t;return(t=(n=e.parserType)!=null?n:Lp(e.streamParser))!=null?t:"plain"}function jo(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 Vo(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 Uo(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 qo(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,d])=>{typeof d=="string"?t.push(`${n} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${n} ${i}: ${d},`)}),t.push(`${n} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${n} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${n} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${n} ${d}: ${c},`))}),t.push(`${n} },`)):typeof a=="string"?t.push(`${n} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${n} ${o}: ${a},`))}),t.push(`${n} },`)),t.push(`${n}},`))}return t}function Bs(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 hc(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}: {`),hc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${r}: ${JSON.stringify(s)},`)}})}function zo(e,n,t,r){t&&(e.push(`${r}${n}: {`),hc(e,t,`${r} `),e.push(`${r}},`))}function Pp(e,n="esm",t){let r={...e};delete r.postprocessMessage,delete r.initialMessages;let s=t?{...t,hooks:Tp(t.hooks)}:void 0;return n==="esm"?Ip(r,s):n==="script-installer"?Hp(r):n==="script-advanced"?Fp(r,s):n==="react-component"?Wp(r,s):n==="react-advanced"?Rp(r,s):Bp(r,s)}function Ip(e,n){let t=n==null?void 0:n.hooks,r=_o(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&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&zo(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(...jo(e," ")),o.push(...Vo(e," ",t)),o.push(...Uo(e," ")),o.push(...qo(e," ")),o.push(...Bs(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(`
184
- `)}function Wp(e,n){let t=n==null?void 0:n.hooks,r=_o(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&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&zo(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(...jo(e," ")),o.push(...Vo(e," ",t)),o.push(...Uo(e," ")),o.push(...qo(e," ")),o.push(...Bs(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(`
185
- `)}function Rp(e,n){let t=n==null?void 0:n.hooks,r=["// ChatWidgetAdvanced.tsx","'use client'; // Required for Next.js - remove for Vite/CRA","","import { useEffect } from 'react';","import '@runtypelabs/persona/widget.css';","import {"," initAgentWidget,"," createFlexibleJsonStreamParser,"," defaultJsonActionParser,"," defaultActionHandlers,"," markdownPostprocessor","} from '@runtypelabs/persona';","import type { AgentWidgetInitHandle } from '@runtypelabs/persona';","","const STORAGE_KEY = 'chat-widget-state';","const PROCESSED_ACTIONS_KEY = 'chat-widget-processed-actions';","","// Types for DOM elements","interface PageElement {"," type: string;"," tagName: string;"," selector: string;"," innerText: string;"," href?: string;","}","","interface DOMContext {"," page_elements: PageElement[];"," page_element_count: number;"," element_types: Record<string, number>;"," page_url: string;"," page_title: string;"," timestamp: string;","}","","// DOM context provider - extracts page elements for AI context","const collectDOMContext = (): DOMContext => {"," const selectors = {",` products: '[data-product-id], .product-card, .product-item, [role="article"]',`,` buttons: 'button, [role="button"], .btn',`," links: 'a[href]',"," inputs: 'input, textarea, select'"," };",""," const elements: PageElement[] = [];"," Object.entries(selectors).forEach(([type, selector]) => {"," document.querySelectorAll(selector).forEach((element) => {"," if (!(element instanceof HTMLElement)) return;"," "," // Exclude elements within the widget"," const widgetHost = element.closest('.persona-host');"," if (widgetHost) return;"," "," const text = element.innerText?.trim();"," if (!text) return;",""," const selectorString ="," element.id ? `#${element.id}` :"," element.getAttribute('data-testid') ? `[data-testid=\"${element.getAttribute('data-testid')}\"]` :"," element.getAttribute('data-product-id') ? `[data-product-id=\"${element.getAttribute('data-product-id')}\"]` :"," element.tagName.toLowerCase();",""," const elementData: PageElement = {"," type,"," tagName: element.tagName.toLowerCase(),"," selector: selectorString,"," innerText: text.substring(0, 200)"," };",""," if (type === 'links' && element instanceof HTMLAnchorElement && element.href) {"," elementData.href = element.href;"," }",""," elements.push(elementData);"," });"," });",""," const counts = elements.reduce((acc, el) => {"," acc[el.type] = (acc[el.type] || 0) + 1;"," return acc;"," }, {} as Record<string, number>);",""," return {"," page_elements: elements.slice(0, 50),"," page_element_count: elements.length,"," element_types: counts,"," page_url: window.location.href,"," page_title: document.title,"," timestamp: new Date().toISOString()"," };","};","","export function ChatWidgetAdvanced() {"," useEffect(() => {"," let handle: AgentWidgetInitHandle | null = null;",""," // Load saved state"," const loadSavedMessages = () => {"," const savedState = localStorage.getItem(STORAGE_KEY);"," if (savedState) {"," try {"," const { messages } = JSON.parse(savedState);"," return messages || [];"," } catch (e) {"," console.error('Failed to load saved state:', e);"," }"," }"," return [];"," };",""," handle = initAgentWidget({"," target: 'body',"," config: {"];return e.apiUrl&&r.push(` apiUrl: "${e.apiUrl}",`),e.clientToken&&r.push(` clientToken: "${e.clientToken}",`),e.flowId&&r.push(` flowId: "${e.flowId}",`),e.theme&&(r.push(" theme: {"),Object.entries(e.theme).forEach(([s,o])=>{r.push(` ${s}: "${o}",`)}),r.push(" },")),e.launcher&&zo(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(...jo(e," ")),r.push(...Vo(e," ",t)),r.push(...Uo(e," ")),r.push(...qo(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(${Mp}),`)),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(` ${uc}`),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(` ${uc}`),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(` ${mc}`),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(` ${mc}`),r.push(" ],")),t!=null&&t.postprocessMessage?r.push(` postprocessMessage: ${t.postprocessMessage},`):r.push(" postprocessMessage: ({ text }) => markdownPostprocessor(text),"),t!=null&&t.requestMiddleware?(r.push(" // Request middleware (custom merged with DOM context)"),r.push(" requestMiddleware: ({ payload, config }) => {"),r.push(` const customResult = (${t.requestMiddleware})({ payload, config });`),r.push(" const merged = customResult || payload;"),r.push(" return {"),r.push(" ...merged,"),r.push(" metadata: { ...merged.metadata, ...collectDOMContext() }"),r.push(" };"),r.push(" }")):(r.push(" requestMiddleware: ({ payload }) => {"),r.push(" return {"),r.push(" ...payload,"),r.push(" metadata: collectDOMContext()"),r.push(" };"),r.push(" }")),r.push(" }"),r.push(" });"),r.push(""),r.push(" // Save state on message events"),r.push(" const handleMessage = () => {"),r.push(" const session = handle?.getSession?.();"),r.push(" if (session) {"),r.push(" localStorage.setItem(STORAGE_KEY, JSON.stringify({"),r.push(" messages: session.messages,"),r.push(" timestamp: new Date().toISOString()"),r.push(" }));"),r.push(" }"),r.push(" };"),r.push(""),r.push(" // Clear state on clear chat"),r.push(" const handleClearChat = () => {"),r.push(" localStorage.removeItem(STORAGE_KEY);"),r.push(" localStorage.removeItem(PROCESSED_ACTIONS_KEY);"),r.push(" };"),r.push(""),r.push(" window.addEventListener('persona:message', handleMessage);"),r.push(" window.addEventListener('persona:clear-chat', handleClearChat);"),r.push(""),r.push(" // Cleanup on unmount"),r.push(" return () => {"),r.push(" window.removeEventListener('persona:message', handleMessage);"),r.push(" window.removeEventListener('persona:clear-chat', handleClearChat);"),r.push(" if (handle) {"),r.push(" handle.destroy();"),r.push(" }"),r.push(" };"),r.push(" }, []);"),r.push(""),r.push(" return null; // Widget injects itself into the DOM"),r.push("}"),r.push(""),r.push("// Usage: Collects DOM context for AI-powered navigation"),r.push("// Features:"),r.push("// - Extracts page elements (products, buttons, links)"),r.push("// - Persists chat history across page loads"),r.push("// - Handles navigation actions (nav_then_click)"),r.push("// - Processes structured JSON actions from AI"),r.push("//"),r.push("// Example usage in Next.js:"),r.push("// import { ChatWidgetAdvanced } from './components/ChatWidgetAdvanced';"),r.push("//"),r.push("// export default function RootLayout({ children }) {"),r.push("// return ("),r.push('// <html lang="en">'),r.push("// <body>"),r.push("// {children}"),r.push("// <ChatWidgetAdvanced />"),r.push("// </body>"),r.push("// </html>"),r.push("// );"),r.push("// }"),r.join(`
186
- `)}function yc(e){var s;let n=_o(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,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([g,p])=>{g!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[g]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(r.layout=o)}return r}function Hp(e){let n=yc(e),t=JSON.stringify(n,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vr}/dist/install.global.js" data-config='${t}'></script>`}function Bp(e,n){let t=n==null?void 0:n.hooks,r=_o(e),s=r!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.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&&(o.push(" theme: {"),Object.entries(e.theme).forEach(([a,i])=>{o.push(` ${a}: "${i}",`)}),o.push(" },")),e.launcher&&zo(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(...jo(e," ")),o.push(...Vo(e," ",t)),o.push(...Uo(e," ")),o.push(...qo(e," ")),o.push(...Bs(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(`
187
- `)}function Fp(e,n){let t=n==null?void 0:n.hooks,r=yc(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(r,null,2).split(`
183
+ }`;function Bp(e){if(!e)return null;let r=e.toString();return r.includes("createJsonStreamParser")||r.includes("partial-json")?"json":r.includes("createRegexJsonParser")||r.includes("regex")?"regex-json":r.includes("createXmlParser")||r.includes("<text>")?"xml":null}function Go(e){var r,t;return(t=(r=e.parserType)!=null?r:Bp(e.streamParser))!=null?t:"plain"}function Xo(e,r){let t=[];return e.toolCall&&(t.push(`${r}toolCall: {`),Object.entries(e.toolCall).forEach(([n,s])=>{typeof s=="string"&&t.push(`${r} ${n}: "${s}",`)}),t.push(`${r}},`)),t}function Zo(e,r,t){let n=[],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)&&(n.push(`${r}messageActions: {`),e.messageActions&&Object.entries(e.messageActions).forEach(([a,i])=>{a==="onFeedback"||a==="onCopy"||(typeof i=="string"?n.push(`${r} ${a}: "${i}",`):typeof i=="boolean"&&n.push(`${r} ${a}: ${i},`))}),t!=null&&t.onFeedback&&n.push(`${r} onFeedback: ${t.onFeedback},`),t!=null&&t.onCopy&&n.push(`${r} onCopy: ${t.onCopy},`),n.push(`${r}},`)),n}function Qo(e,r){let t=[];if(e.markdown){let n=e.markdown.options&&Object.keys(e.markdown.options).length>0,s=e.markdown.disableDefaultStyles!==void 0;(n||s)&&(t.push(`${r}markdown: {`),n&&(t.push(`${r} options: {`),Object.entries(e.markdown.options).forEach(([o,a])=>{typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`)}),t.push(`${r} },`)),s&&t.push(`${r} disableDefaultStyles: ${e.markdown.disableDefaultStyles},`),t.push(`${r}},`))}return t}function es(e,r){let t=[];if(e.layout){let n=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");(n||s)&&(t.push(`${r}layout: {`),n&&(t.push(`${r} header: {`),Object.entries(e.layout.header).forEach(([o,a])=>{o!=="render"&&(typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),s&&(t.push(`${r} messages: {`),Object.entries(e.layout.messages).forEach(([o,a])=>{o==="renderUserMessage"||o==="renderAssistantMessage"||(o==="avatar"&&typeof a=="object"&&a!==null?(t.push(`${r} avatar: {`),Object.entries(a).forEach(([i,d])=>{typeof d=="string"?t.push(`${r} ${i}: "${d}",`):typeof d=="boolean"&&t.push(`${r} ${i}: ${d},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([d])=>d!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([d,c])=>{d!=="format"&&(typeof c=="string"?t.push(`${r} ${d}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${d}: ${c},`))}),t.push(`${r} },`)):typeof a=="string"?t.push(`${r} ${o}: "${a}",`):typeof a=="boolean"&&t.push(`${r} ${o}: ${a},`))}),t.push(`${r} },`)),t.push(`${r}},`))}return t}function zs(e,r){let t=[];return e&&(e.getHeaders&&t.push(`${r}getHeaders: ${e.getHeaders},`),e.requestMiddleware&&t.push(`${r}requestMiddleware: ${e.requestMiddleware},`),e.actionParsers&&t.push(`${r}actionParsers: ${e.actionParsers},`),e.actionHandlers&&t.push(`${r}actionHandlers: ${e.actionHandlers},`),e.contextProviders&&t.push(`${r}contextProviders: ${e.contextProviders},`),e.streamParser&&t.push(`${r}streamParser: ${e.streamParser},`)),t}function Sc(e,r,t){Object.entries(r).forEach(([n,s])=>{if(!(s===void 0||typeof s=="function")){if(Array.isArray(s)){e.push(`${t}${n}: ${JSON.stringify(s)},`);return}if(s&&typeof s=="object"){e.push(`${t}${n}: {`),Sc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function qn(e,r,t,n){t&&(e.push(`${n}${r}: {`),Sc(e,t,`${n} `),e.push(`${n}},`))}function Dp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:Wp(t.hooks)}:void 0;return r==="esm"?Np(n,s):r==="script-installer"?$p(n):r==="script-advanced"?jp(n,s):r==="react-component"?Op(n,s):r==="react-advanced"?Fp(n,s):_p(n,s)}function Np(e,r){let t=r==null?void 0:r.hooks,n=Go(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&qn(o,"theme",e.theme," "),e.launcher&&qn(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(...Xo(e," ")),o.push(...Zo(e," ",t)),o.push(...Qo(e," ")),o.push(...es(e," ")),o.push(...zs(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(`
184
+ `)}function Op(e,r){let t=r==null?void 0:r.hooks,n=Go(e),s=n!=="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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&qn(o,"theme",e.theme," "),e.launcher&&qn(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(...Xo(e," ")),o.push(...Zo(e," ",t)),o.push(...Qo(e," ")),o.push(...es(e," ")),o.push(...zs(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(`
185
+ `)}function Fp(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&&qn(n,"theme",e.theme," "),e.launcher&&qn(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(...Xo(e," ")),n.push(...Zo(e," ",t)),n.push(...Qo(e," ")),n.push(...es(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(${Rp}),`)),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(` ${xc}`),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(` ${xc}`),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(` ${Cc}`),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(` ${Cc}`),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(`
186
+ `)}function Ac(e){var s;let r=Go(e),t=r!=="plain",n={};if(e.apiUrl&&(n.apiUrl=e.apiUrl),e.clientToken&&(n.clientToken=e.clientToken),e.flowId&&(n.flowId=e.flowId),t&&(n.parserType=r),e.theme&&(n.theme=e.theme),e.launcher&&(n.launcher=e.launcher),e.copy&&(n.copy=e.copy),e.sendButton&&(n.sendButton=e.sendButton),e.voiceRecognition&&(n.voiceRecognition=e.voiceRecognition),e.statusIndicator&&(n.statusIndicator=e.statusIndicator),e.features&&(n.features=e.features),((s=e.suggestionChips)==null?void 0:s.length)>0&&(n.suggestionChips=e.suggestionChips),e.suggestionChipsConfig&&(n.suggestionChipsConfig=e.suggestionChipsConfig),e.debug&&(n.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&&(n.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&&(n.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&&(n.markdown=o)}if(e.layout){let o={};if(e.layout.header){let a={};Object.entries(e.layout.header).forEach(([i,d])=>{i!=="render"&&(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,d])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof d=="object"&&d!==null)a.avatar=d;else if(i==="timestamp"&&typeof d=="object"&&d!==null){let c={};Object.entries(d).forEach(([u,p])=>{u!=="format"&&(typeof p=="string"||typeof p=="boolean")&&(c[u]=p)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof d=="string"||typeof d=="boolean")&&(a[i]=d)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function $p(e){let r=Ac(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Mr}/dist/install.global.js" data-config='${t}'></script>`}function _p(e,r){let t=r==null?void 0:r.hooks,n=Go(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Mr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Mr}/dist/index.global.js"></script>`,"","<!-- Initialize widget -->","<script>"," window.AgentWidget.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: "${n}",`),e.theme&&typeof e.theme=="object"&&Object.keys(e.theme).length>0&&qn(o,"theme",e.theme," "),e.launcher&&qn(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(...Xo(e," ")),o.push(...Zo(e," ",t)),o.push(...Qo(e," ")),o.push(...es(e," ")),o.push(...zs(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(`
187
+ `)}function jp(e,r){let t=r==null?void 0:r.hooks,n=Ac(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
188
188
  `).map((a,i)=>i===0?a:" "+a).join(`
189
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${vr}/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(${kp});`),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(` ${gc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${gc}`),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(` ${fc}`),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(` ${fc}`),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,"," 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(`
190
- `)}function $p(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #1d4ed8)"}}}function Np(){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 Op(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:Cn(e.colors.primary,.95),100:Cn(e.colors.primary,.9),200:Cn(e.colors.primary,.8),300:Cn(e.colors.primary,.7),400:Cn(e.colors.primary,.6),500:e.colors.primary,600:Cn(e.colors.primary,.8),700:Cn(e.colors.primary,.7),800:Cn(e.colors.primary,.6),900:Cn(e.colors.primary,.5),950:Cn(e.colors.primary,.45)}}),{...n,palette:t}}}}function Dp(){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 _p(){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 Cn(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 jp(e){return{name:e.name,version:e.version,transform:e.transform||(n=>n),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var bc={id:"shop",label:"Shopping Assistant",config:{theme:{primary:"#111827",accent:"#1d4ed8",surface:"#ffffff",muted:"#6b7280",container:"#f8fafc",border:"#f1f5f9",divider:"#f1f5f9",messageBorder:"#f1f5f9",inputBackground:"#ffffff",callToAction:"#000000",callToActionBackground:"#ffffff",sendButtonBackgroundColor:"#111827",sendButtonTextColor:"#ffffff",radiusSm:"0.75rem",radiusMd:"1rem",radiusLg:"1.5rem",launcherRadius:"9999px",buttonRadius:"9999px"},launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},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?"]}},xc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:{panelBorderRadius:"0",panelShadow:"none"}}},vc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:{panelBorderRadius:"0",panelShadow:"none"}}},Cc={shop:bc,minimal:xc,fullscreen:vc};function Vp(e){return Cc[e]}var rf=Zl;export{cr as AgentWidgetClient,zr as AgentWidgetSession,ur as AttachmentManager,cl as DEFAULT_COMPONENTS,ql as DEFAULT_DARK_THEME,Ul as DEFAULT_LIGHT_THEME,il as DEFAULT_PALETTE,ll as DEFAULT_SEMANTIC,ft as DEFAULT_WIDGET_CONFIG,Cc as PRESETS,vc as PRESET_FULLSCREEN,xc as PRESET_MINIMAL,bc as PRESET_SHOP,ed as THEME_ZONES,vr as VERSION,$p as accessibilityPlugin,Np as animationsPlugin,Xn as applyThemeVariables,gr as attachHeaderToContainer,Op as brandPlugin,Xr as buildComposer,Sl as buildDefaultHeader,Fn as buildHeader,Gr as buildHeaderWithLayout,Al as buildMinimalHeader,Sp as collectEnrichedPageContext,$n as componentRegistry,No as createActionManager,Ls as createAgentExperience,rs as createBestAvailableVoiceProvider,xd as createBubbleWithLayout,Ts as createCSATFeedback,Kd as createComponentMiddleware,ws as createComponentStreamParser,Xi as createDefaultSanitizer,Mc as createDirectivePostprocessor,Bc as createFlexibleJsonStreamParser,Vc as createImagePart,Zo as createJsonStreamParser,Cs as createLocalStorageAdapter,Ao as createMarkdownProcessor,lr as createMarkdownProcessorFromConfig,Pl as createMessageActions,Ms as createNPSFeedback,Go as createPlainTextParser,jp as createPlugin,Xo as createRegexJsonParser,Zr as createStandardBubble,ns as createTextPart,Jr as createTheme,ds as createThemeObserver,mr as createTypingIndicator,pr as createVoiceProvider,Oo as createWidgetHostLayout,Qo as createXmlParser,rf as default,br as defaultActionHandlers,$o as defaultJsonActionParser,ic as defaultParseRules,Ro as detectColorScheme,kc as directivePostprocessor,_r as escapeHtml,Es as extractComponentDirectiveFromMessage,Uc as fileToImagePart,Ap as formatEnrichedContext,dr as generateAssistantMessageId,Pp as generateCodeSnippet,Nc as generateMessageId,cc as generateStableSelector,Ur as generateUserMessageId,hl as getActiveTheme,fl as getColorScheme,Dc as getDisplayText,El as getHeaderLayout,jc as getImageParts,Vp as getPreset,As as hasComponentDirective,_c as hasImages,ps as headerLayouts,_p as highContrastPlugin,Zl as initAgentWidget,Jd as isComponentDirectiveType,Jt as isDockedMountMode,Io as isVoiceSupported,Ki as markdownPostprocessor,xs as mergeWithDefaults,is as migrateV1Theme,Oc as normalizeContent,Fo as pluginRegistry,Dp as reducedMotionPlugin,Ss as renderComponentDirective,Ll as renderLoadingIndicatorWithFallback,Kr as resolveDockConfig,jr as resolveSanitizer,os as resolveTokens,ss as themeToCssVariables,qc as validateImageFile,pl as validateTheme,td as validateV1Theme};
189
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Mr}/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(${Hp});`),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(` ${vc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${vc}`),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(` ${wc}`),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(` ${wc}`),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,"," 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(`
190
+ `)}function zp(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #1d4ed8)"}}}function qp(){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 Up(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:En(e.colors.primary,.95),100:En(e.colors.primary,.9),200:En(e.colors.primary,.8),300:En(e.colors.primary,.7),400:En(e.colors.primary,.6),500:e.colors.primary,600:En(e.colors.primary,.8),700:En(e.colors.primary,.7),800:En(e.colors.primary,.6),900:En(e.colors.primary,.5),950:En(e.colors.primary,.45)}}),{...r,palette:t}}}}function Vp(){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 Jp(){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 En(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 Kp(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var Yp={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"}}},Ec={components:{panel:{borderRadius:"0",shadow:"none"}}},Tc={id:"shop",label:"Shopping Assistant",config:{theme:Yp,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:"min(400px, calc(100vw - 24px))"},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?"]}},Mc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Ec}},kc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Ec}},Lc={shop:Tc,minimal:Mc,fullscreen:kc};function Gp(e){return Lc[e]}var Ef=sc;export{hr as AgentWidgetClient,Zr as AgentWidgetSession,xr as AttachmentManager,yl as DEFAULT_COMPONENTS,fl as DEFAULT_PALETTE,hl as DEFAULT_SEMANTIC,ht as DEFAULT_WIDGET_CONFIG,Lc as PRESETS,kc as PRESET_FULLSCREEN,Mc as PRESET_MINIMAL,Tc as PRESET_SHOP,id as THEME_ZONES,Mr as VERSION,zp as accessibilityPlugin,qp as animationsPlugin,or as applyThemeVariables,vr as attachHeaderToContainer,Up as brandPlugin,oo as buildComposer,Ll as buildDefaultHeader,jn as buildHeader,ro as buildHeaderWithLayout,Pl as buildMinimalHeader,Lp as collectEnrichedPageContext,zn as componentRegistry,Vo as createActionManager,Hs as createAgentExperience,ps as createBestAvailableVoiceProvider,Sd as createBubbleWithLayout,Is as createCSATFeedback,fs as createComboButton,Xd as createComponentMiddleware,Ms as createComponentStreamParser,sl as createDefaultSanitizer,Hc as createDirectivePostprocessor,sr as createDropdownMenu,jc as createFlexibleJsonStreamParser,_t as createIconButton,Gc as createImagePart,as as createJsonStreamParser,_o as createLabelButton,Ts as createLocalStorageAdapter,Lo as createMarkdownProcessor,fr as createMarkdownProcessorFromConfig,Dl as createMessageActions,Ws as createNPSFeedback,os as createPlainTextParser,Kp as createPlugin,ss as createRegexJsonParser,so as createStandardBubble,ds as createTextPart,eo as createTheme,ms as createThemeObserver,md as createToggleGroup,Cr as createTypingIndicator,br as createVoiceProvider,Ko as createWidgetHostLayout,is as createXmlParser,Ef as default,Er as defaultActionHandlers,Uo as defaultJsonActionParser,mc as defaultParseRules,Oo as detectColorScheme,Bc as directivePostprocessor,Jr as escapeHtml,Ps as extractComponentDirectiveFromMessage,Xc as fileToImagePart,Pp as formatEnrichedContext,yr as generateAssistantMessageId,Dp as generateCodeSnippet,Uc as generateMessageId,hc as generateStableSelector,Gr as generateUserMessageId,Fo as getActiveTheme,wl as getColorScheme,Jc as getDisplayText,Il as getHeaderLayout,Yc as getImageParts,Gp as getPreset,Ls as hasComponentDirective,Kc as hasImages,hs as headerLayouts,Jp as highContrastPlugin,sc as initAgentWidget,Gd as isComponentDirectiveType,zt as isDockedMountMode,Do as isVoiceSupported,nl as markdownPostprocessor,As as mergeWithDefaults,Vc as normalizeContent,qo as pluginRegistry,Vp as reducedMotionPlugin,ks as renderComponentDirective,Bl as renderLoadingIndicatorWithFallback,hn as resolveDockConfig,Kr as resolveSanitizer,us as resolveTokens,gs as themeToCssVariables,Zc as validateImageFile,bl as validateTheme};
191
191
  //# sourceMappingURL=index.js.map