@runtypelabs/persona 3.5.2 → 3.6.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 (45) hide show
  1. package/dist/index.cjs +30 -30
  2. package/dist/index.cjs.map +1 -1
  3. package/dist/index.d.cts +14 -0
  4. package/dist/index.d.ts +14 -0
  5. package/dist/index.global.js +41 -41
  6. package/dist/index.global.js.map +1 -1
  7. package/dist/index.js +29 -29
  8. package/dist/index.js.map +1 -1
  9. package/dist/theme-editor.cjs +17728 -0
  10. package/dist/theme-editor.d.cts +3857 -0
  11. package/dist/theme-editor.d.ts +3857 -0
  12. package/dist/theme-editor.js +17623 -0
  13. package/dist/theme-reference.cjs +1 -1
  14. package/dist/theme-reference.d.cts +14 -0
  15. package/dist/theme-reference.d.ts +14 -0
  16. package/dist/theme-reference.js +1 -1
  17. package/dist/widget.css +29 -25
  18. package/package.json +9 -7
  19. package/src/components/artifact-card.ts +1 -1
  20. package/src/components/composer-builder.ts +16 -29
  21. package/src/components/demo-carousel.ts +4 -4
  22. package/src/components/event-stream-view.ts +1 -1
  23. package/src/components/header-builder.ts +2 -2
  24. package/src/components/launcher.ts +9 -0
  25. package/src/components/message-bubble.ts +9 -3
  26. package/src/components/suggestions.ts +1 -1
  27. package/src/defaults.ts +9 -9
  28. package/src/styles/widget.css +29 -25
  29. package/src/theme-editor/color-utils.ts +252 -0
  30. package/src/theme-editor/index.ts +130 -0
  31. package/src/theme-editor/presets.ts +144 -0
  32. package/src/theme-editor/preview-utils.ts +265 -0
  33. package/src/theme-editor/preview.ts +445 -0
  34. package/src/theme-editor/role-mappings.ts +331 -0
  35. package/src/theme-editor/sections.ts +952 -0
  36. package/src/theme-editor/state.ts +298 -0
  37. package/src/theme-editor/types.ts +177 -0
  38. package/src/theme-editor.ts +2 -0
  39. package/src/types/theme.ts +1 -0
  40. package/src/ui.ts +53 -58
  41. package/src/utils/plugins.ts +1 -1
  42. package/src/utils/theme.test.ts +10 -8
  43. package/src/utils/theme.ts +11 -11
  44. package/src/utils/tokens.ts +88 -41
  45. package/widget.css +0 -1
package/dist/index.js CHANGED
@@ -1,10 +1,10 @@
1
- import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new zc({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=qc(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},xr=e=>e?Io({markedOptions:e.options,renderer:e.renderer}):Io(),Uc=Io(),ll=e=>Uc(e),Yr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),il=e=>`%%FORM_PLACEHOLDER_${e}%%`,dl=(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=il(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=il(r.length);return r.push({token:o,type:s}),o}),t},Vc=e=>{let r=xr(e);return t=>{let n=[],s=dl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${cl(i)}"></div>`;o=o.replace(p,u)}),o}},Jc=e=>{let r=[],t=dl(e,r),n=ll(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cl(o)}"></div>`;n=n.replace(a,p)}),n};import Kc from"dompurify";var Gc={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"]},Yc=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,pl=()=>{let e=Kc(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:")&&!Yc.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Gc)},Xr=e=>e===!1?null:typeof e=="function"?e:pl();import{parse as ul,STR as gl,OBJ as ml}from"partial-json";var Po=e=>e.replace(/\\n/g,`
1
+ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=e==null?void 0:e.markedOptions,t=new zc({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=qc(e==null?void 0:e.renderer);return n&&t.use({renderer:n}),a=>t.parse(a)},Cr=e=>e?Io({markedOptions:e.options,renderer:e.renderer}):Io(),Vc=Io(),ll=e=>Vc(e),Yr=e=>e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;"),cl=e=>e.replace(/"/g,"&quot;").replace(/</g,"&lt;").replace(/>/g,"&gt;"),il=e=>`%%FORM_PLACEHOLDER_${e}%%`,dl=(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=il(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=il(r.length);return r.push({token:o,type:s}),o}),t},Uc=e=>{let r=Cr(e);return t=>{let n=[],s=dl(t,n),o=r(s);return n.forEach(({token:a,type:i})=>{let p=new RegExp(a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),u=`<div class="persona-form-directive" data-tv-form="${cl(i)}"></div>`;o=o.replace(p,u)}),o}},Jc=e=>{let r=[],t=dl(e,r),n=ll(t);return r.forEach(({token:s,type:o})=>{let a=new RegExp(s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),p=`<div class="persona-form-directive" data-tv-form="${cl(o)}"></div>`;n=n.replace(a,p)}),n};import Kc from"dompurify";var Gc={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"]},Yc=/^data:image\/(?:png|jpe?g|gif|webp|bmp|x-icon|avif)/i,pl=()=>{let e=Kc(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:")&&!Yc.test(n)&&(t.attrValue="",t.keepAttr=!1)}}),r=>e.sanitize(r,Gc)},Xr=e=>e===!1?null:typeof e=="function"?e:pl();import{parse as ul,STR as gl,OBJ as ml}from"partial-json";var Po=e=>e.replace(/\\n/g,`
2
2
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Zr=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)}},Xc=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`},fl=e=>e.status==="complete"?Xc(e):e.status==="pending"?"Waiting":"",Zc=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 hl=e=>e.status==="complete"?Zc(e):"Using tool...",Qc=()=>{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
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()=>{}}},Wo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},is=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ls=()=>{var r;let e=Qc();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)}},cs=()=>{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=ul(t,gl|ml);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:()=>{}}},ed=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=ul(o,gl|ml),p=s(i);p!==null&&(r=p)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},ds=()=>{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 td="https://api.runtype.com/v1/dispatch",ps="https://api.runtype.com",us=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 nd(e){switch(e){case"json":return cs;case"regex-json":return ls;case"xml":return ds;default:return is}}var vr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:td,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:nd(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$/,""))||ps;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$/,""))||ps}/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 p=await this.initSession();if(new Date>=new Date(p.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,d={sessionId:p.sessionId,messages:r.messages.filter(us).map(m=>{var v,A,b;return{id:m.id,role:m.role,content:(b=(A=(v=m.contentParts)!=null?v:m.llmContent)!=null?A:m.rawContent)!=null?b: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",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let 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 A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(f.status===429){let A=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(p){let c=p instanceof Error?p:new Error(String(p));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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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$/,""))||ps}/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(us).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(us).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let p=u=>{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(),...u!==void 0&&{partId:u}};return n.current=d,s(d),d},c=u=>n.current?n.current:p(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae,re,ye,Ce,Qe,he,Pe,Ne,ot,At,Oe,Jn,xn,Kn,Dn,cr,Nn,Mn,et,X,an,rn,Wr,vn,ht,ln,kn,Rr,dr,Hr,Gn,Cn,Yn,Et,wn,Br,On,Sn,H,$n,Fn,Dr,Ln,Xn,Nr,In,Pn,pr,ur,uo,go,mo,Or,gr,Ve,$r,cn,Qt,fo,ho,Fr,Zn,Wn,yo,bo,xo,rs,Qn,er,bt,mr,fr,_r,jr,zr,qr,Yt,on,Rn,$e,Ur,tr,gn,vo,hr,yr,nr,_n,Co,wo,mn,rr;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),p=0,c=()=>i+p++,u=Q=>{let Ye=Q.reasoning?{...Q.reasoning,chunks:[...Q.reasoning.chunks]}:void 0,st=Q.toolCall?{...Q.toolCall,chunks:Q.toolCall.chunks?[...Q.toolCall.chunks]:void 0}:void 0,_e=Q.tools?Q.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...Q,reasoning:Ye,toolCall:st,tools:_e}},d=Q=>{t({type:"message",message:u(Q)})},f=null,m={current:null},v={current:null},A=new Map,b=new Map,x={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},F=Q=>{if(Q==null)return null;try{return String(Q)}catch{return null}},S=Q=>{var Ye,st,_e,qe,Lt;return F((Lt=(qe=(_e=(st=(Ye=Q.stepId)!=null?Ye:Q.step_id)!=null?st:Q.step)!=null?_e:Q.parentId)!=null?qe:Q.flowStepId)!=null?Lt:Q.flow_step_id)},I=Q=>{var Ye,st,_e,qe,Lt,Tt,C;return F((C=(Tt=(Lt=(qe=(_e=(st=(Ye=Q.callId)!=null?Ye:Q.call_id)!=null?st:Q.requestId)!=null?_e:Q.request_id)!=null?qe:Q.toolCallId)!=null?Lt:Q.tool_call_id)!=null?Tt:Q.stepId)!=null?C:Q.step_id)},O=()=>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()},d(f),f),k=(Q,Ye)=>{x.lastId=Ye,Q&&x.byStep.set(Q,Ye)},V=(Q,Ye)=>{var Lt;let st=(Lt=Q.reasoningId)!=null?Lt:Q.id,_e=S(Q);if(st){let Tt=String(st);return k(_e,Tt),Tt}if(_e){let Tt=x.byStep.get(_e);if(Tt)return x.lastId=Tt,Tt}if(x.lastId&&!Ye)return x.lastId;if(!Ye)return null;let qe=`reason-${c()}`;return k(_e,qe),qe},ge=Q=>{let Ye=A.get(Q);if(Ye)return Ye;let st={id:`reason-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Q,status:"streaming",chunks:[]}};return A.set(Q,st),d(st),st},ie=(Q,Ye)=>{M.lastId=Ye,Q&&M.byCall.set(Q,Ye)},_=new Set,ne=new Map,Te=new Set,le=new Map,ke=Q=>{if(!Q)return!1;let Ye=Q.replace(/_+/g,"_").replace(/^_|_$/g,"");return Ye==="emit_artifact_markdown"||Ye==="emit_artifact_component"},de=(Q,Ye)=>{var Lt;let st=(Lt=Q.toolId)!=null?Lt:Q.id,_e=I(Q);if(st){let Tt=String(st);return ie(_e,Tt),Tt}if(_e){let Tt=M.byCall.get(_e);if(Tt)return M.lastId=Tt,Tt}if(M.lastId&&!Ye)return M.lastId;if(!Ye)return null;let qe=`tool-${c()}`;return ie(_e,qe),qe},Y=Q=>{let Ye=b.get(Q);if(Ye)return Ye;let st={id:`tool-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Q,status:"pending"}};return b.set(Q,st),d(st),st},ce=Q=>{if(typeof Q=="number"&&Number.isFinite(Q))return Q;if(typeof Q=="string"){let Ye=Number(Q);if(!Number.isNaN(Ye)&&Number.isFinite(Ye))return Ye;let st=Date.parse(Q);if(!Number.isNaN(st))return st}return Date.now()},q=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},G=new Map,ve=new Map,xe=null,Ke=new Map,Xe=(mt=this.config.iterationDisplay)!=null?mt:"separate";for(;;){let{done:Q,value:Ye}=await s.read();if(Q)break;a+=o.decode(Ye,{stream:!0});let st=a.split(`
4
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async 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()=>{}}},Wo=e=>{try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{return null}return null},is=()=>{let e={processChunk:r=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},ls=()=>{var r;let e=Qc();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)}},cs=()=>{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=ul(t,gl|ml);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:()=>{}}},ed=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=ul(o,gl|ml),p=s(i);p!==null&&(r=p)}catch{}return t=o.length,{text:r||"",raw:o}},close:()=>{}}},ds=()=>{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 td="https://api.runtype.com/v1/dispatch",ps="https://api.runtype.com",us=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 nd(e){switch(e){case"json":return cs;case"regex-json":return ls;case"xml":return ds;default:return is}}var wr=class{constructor(r={}){this.config=r;this.clientSession=null;this.sessionInitPromise=null;var t,n,s;this.apiUrl=(t=r.apiUrl)!=null?t:td,this.headers={"Content-Type":"application/json",...r.headers},this.debug=!!r.debug,this.createStreamParser=(n=r.streamParser)!=null?n:nd(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$/,""))||ps;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$/,""))||ps}/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 p=await this.initSession();if(new Date>=new Date(p.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,d={sessionId:p.sessionId,messages:r.messages.filter(us).map(m=>{var v,A,b;return{id:m.id,role:m.role,content:(b=(A=(v=m.contentParts)!=null?v:m.llmContent)!=null?A:m.rawContent)!=null?b: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",d);let f=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(d),signal:n.signal});if(!f.ok){let 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 A=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:A}),A}if(f.status===429){let A=new Error(m.hint||"Message limit reached for this session.");throw t({type:"error",error:A}),A}let v=new Error(m.error||"Failed to send message");throw t({type:"error",error:v}),v}if(!f.body){let m=new Error("No response body received");throw t({type:"error",error:m}),m}t({type:"status",status:"connected"});try{await this.streamResponse(f.body,t,r.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(p){let c=p instanceof Error?p:new Error(String(p));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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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 p=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:p}),p}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$/,""))||ps}/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(us).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(us).sort((s,o)=>{let a=new Date(s.createdAt).getTime(),i=new Date(o.createdAt).getTime();return a-i}).map(s=>{var o,a,i;return{role:s.role,content:(i=(a=(o=s.contentParts)!=null?o:s.llmContent)!=null?a:s.rawContent)!=null?i:s.content,createdAt:s.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}};if(this.contextProviders.length){let s={};await Promise.all(this.contextProviders.map(async o=>{try{let a=await o({messages:r,config:this.config});a&&typeof a=="object"&&Object.assign(s,a)}catch(a){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",a)}})),Object.keys(s).length&&(n.context=s)}if(this.requestMiddleware)try{let s=await this.requestMiddleware({payload:{...n},config:this.config});if(s&&typeof s=="object")return s}catch(s){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",s)}return n}async handleCustomSSEEvent(r,t,n,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(r);if(i===null)return!1;let p=u=>{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(),...u!==void 0&&{partId:u}};return n.current=d,s(d),d},c=u=>n.current?n.current:p(u);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(n.current&&(n.current.streaming=!1,s(n.current)),p(i.partId)),i.partId!==void 0&&(a.current=i.partId);let u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,s(u)}return i.done&&(n.current&&(n.current.streaming=!1,s(n.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(r,t,n){var ft,We,nt,ke,D,se,te,z,oe,Ie,Z,G,je,Ue,St,jt,zt,J,Pe,ht,yt,Qe,it,Wt,qt,pe,T,Ee,re,be,we,ze,fe,Re,Be,rt,At,_e,Yn,Sn,Xn,An,ur,On,Pn,et,an,fn,en,$n,ln,dt,Yt,X,Wn,Fn,Hr,Zn,En,Qn,Et,Tn,Br,_n,Mn,H,jn,zn,Dr,hn,er,Nr,Rn,yn,gr,mr,uo,go,mo,Or,fr,Je,$r,pn,tn,fo,ho,Fr,tr,Hn,yo,bo,xo,rs,nr,rr,bt,hr,yr,_r,jr,zr,qr,Xt,cn,Bn,De,Vr,or,bn,vo,br,xr,sr,qn,Co,wo,xn,ar;let s=r.getReader(),o=new TextDecoder,a="",i=Date.now(),p=0,c=()=>i+p++,u=Q=>{let Xe=Q.reasoning?{...Q.reasoning,chunks:[...Q.reasoning.chunks]}:void 0,ot=Q.toolCall?{...Q.toolCall,chunks:Q.toolCall.chunks?[...Q.toolCall.chunks]:void 0}:void 0,$e=Q.tools?Q.tools.map(qe=>({...qe,chunks:qe.chunks?[...qe.chunks]:void 0})):void 0;return{...Q,reasoning:Xe,toolCall:ot,tools:$e}},d=Q=>{t({type:"message",message:u(Q)})},f=null,m={current:null},v={current:null},A=new Map,b=new Map,x={lastId:null,byStep:new Map},M={lastId:null,byCall:new Map},F=Q=>{if(Q==null)return null;try{return String(Q)}catch{return null}},S=Q=>{var Xe,ot,$e,qe,Lt;return F((Lt=(qe=($e=(ot=(Xe=Q.stepId)!=null?Xe:Q.step_id)!=null?ot:Q.step)!=null?$e:Q.parentId)!=null?qe:Q.flowStepId)!=null?Lt:Q.flow_step_id)},I=Q=>{var Xe,ot,$e,qe,Lt,Tt,C;return F((C=(Tt=(Lt=(qe=($e=(ot=(Xe=Q.callId)!=null?Xe:Q.call_id)!=null?ot:Q.requestId)!=null?$e:Q.request_id)!=null?qe:Q.toolCallId)!=null?Lt:Q.tool_call_id)!=null?Tt:Q.stepId)!=null?C:Q.step_id)},O=()=>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()},d(f),f),k=(Q,Xe)=>{x.lastId=Xe,Q&&x.byStep.set(Q,Xe)},U=(Q,Xe)=>{var Lt;let ot=(Lt=Q.reasoningId)!=null?Lt:Q.id,$e=S(Q);if(ot){let Tt=String(ot);return k($e,Tt),Tt}if($e){let Tt=x.byStep.get($e);if(Tt)return x.lastId=Tt,Tt}if(x.lastId&&!Xe)return x.lastId;if(!Xe)return null;let qe=`reason-${c()}`;return k($e,qe),qe},ue=Q=>{let Xe=A.get(Q);if(Xe)return Xe;let ot={id:`reason-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:c(),reasoning:{id:Q,status:"streaming",chunks:[]}};return A.set(Q,ot),d(ot),ot},ie=(Q,Xe)=>{M.lastId=Xe,Q&&M.byCall.set(Q,Xe)},_=new Set,ne=new Map,Me=new Set,le=new Map,Le=Q=>{if(!Q)return!1;let Xe=Q.replace(/_+/g,"_").replace(/^_|_$/g,"");return Xe==="emit_artifact_markdown"||Xe==="emit_artifact_component"},de=(Q,Xe)=>{var Lt;let ot=(Lt=Q.toolId)!=null?Lt:Q.id,$e=I(Q);if(ot){let Tt=String(ot);return ie($e,Tt),Tt}if($e){let Tt=M.byCall.get($e);if(Tt)return M.lastId=Tt,Tt}if(M.lastId&&!Xe)return M.lastId;if(!Xe)return null;let qe=`tool-${c()}`;return ie($e,qe),qe},Y=Q=>{let Xe=b.get(Q);if(Xe)return Xe;let ot={id:`tool-${Q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:c(),toolCall:{id:Q,status:"pending"}};return b.set(Q,ot),d(ot),ot},ce=Q=>{if(typeof Q=="number"&&Number.isFinite(Q))return Q;if(typeof Q=="string"){let Xe=Number(Q);if(!Number.isNaN(Xe)&&Number.isFinite(Xe))return Xe;let ot=Date.parse(Q);if(!Number.isNaN(ot))return ot}return Date.now()},q=Q=>{if(typeof Q=="string")return Q;if(Q==null)return"";try{return JSON.stringify(Q)}catch{return String(Q)}},K=new Map,Ce=new Map,ve=null,Ge=new Map,Ze=(ft=this.config.iterationDisplay)!=null?ft:"separate";for(;;){let{done:Q,value:Xe}=await s.read();if(Q)break;a+=o.decode(Xe,{stream:!0});let ot=a.split(`
5
5
 
6
- `);a=(Be=st.pop())!=null?Be:"";for(let _e of st){let qe=_e.split(`
7
- `),Lt="message",Tt="";for(let B of qe)B.startsWith("event:")?Lt=B.replace("event:","").trim():B.startsWith("data:")&&(Tt+=B.replace("data:","").trim());if(!Tt)continue;let C;try{C=JSON.parse(Tt)}catch(B){t({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let Fe=Lt!=="message"?Lt:(rt=C.type)!=null?rt:"message";if((Me=this.onSSEEvent)==null||Me.call(this,Fe,C),this.parseSSEEvent){m.current=f;let B=await this.handleCustomSSEEvent(C,t,m,d,c,v);if(m.current&&m.current!==f&&(f=m.current),B)continue}if(Fe==="reason_start"){let B=(D=V(C,!0))!=null?D:`reason-${c()}`,w=ge(B);w.reasoning=(se=w.reasoning)!=null?se:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(z=w.reasoning.startedAt)!=null?z:ce((te=C.startedAt)!=null?te:C.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",d(w)}else if(Fe==="reason_delta"||Fe==="reason_chunk"){let B=(Le=(oe=V(C,!1))!=null?oe:V(C,!0))!=null?Le:`reason-${c()}`,w=ge(B);w.reasoning=(Z=w.reasoning)!=null?Z:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(ze=w.reasoning.startedAt)!=null?ze:ce((J=C.startedAt)!=null?J:C.timestamp);let $=(qt=(St=(Ue=C.reasoningText)!=null?Ue:C.text)!=null?St:C.delta)!=null?qt:"";if($&&C.hidden!==!0&&w.reasoning.chunks.push(String($)),w.reasoning.status=C.done?"complete":"streaming",C.done){w.reasoning.completedAt=ce((Ut=C.completedAt)!=null?Ut:C.timestamp);let ee=(K=w.reasoning.startedAt)!=null?K:Date.now();w.reasoning.durationMs=Math.max(0,((Ie=w.reasoning.completedAt)!=null?Ie:Date.now())-ee)}w.streaming=w.reasoning.status!=="complete",d(w)}else if(Fe==="reason_complete"){let B=(yt=(ft=V(C,!1))!=null?ft:V(C,!0))!=null?yt:`reason-${c()}`,w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce((Ze=C.completedAt)!=null?Ze:C.timestamp);let ee=(it=w.reasoning.startedAt)!=null?it:Date.now();w.reasoning.durationMs=Math.max(0,((Wt=w.reasoning.completedAt)!=null?Wt:Date.now())-ee),w.streaming=!1,d(w)}let $=S(C);$&&x.byStep.delete($)}else if(Fe==="tool_start"){let B=(Vt=de(C,!0))!=null?Vt:`tool-${c()}`,w=(ue=C.toolName)!=null?ue:C.name;if(ke(w)){_.add(B);continue}let $=Y(B),ee=(T=$.toolCall)!=null?T:{id:B,status:"pending"};ee.name=w!=null?w:ee.name,ee.status="running",C.args!==void 0?ee.args=C.args:C.parameters!==void 0&&(ee.args=C.parameters),ee.startedAt=(re=ee.startedAt)!=null?re:ce((Ae=C.startedAt)!=null?Ae:C.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,$.toolCall=ee,$.streaming=!0;let Ee=C.agentContext;(Ee||C.executionId)&&($.agentMetadata={executionId:(ye=Ee==null?void 0:Ee.executionId)!=null?ye:C.executionId,iteration:(Ce=Ee==null?void 0:Ee.iteration)!=null?Ce:C.iteration}),d($)}else if(Fe==="tool_chunk"||Fe==="tool_delta"){let B=(he=(Qe=de(C,!1))!=null?Qe:de(C,!0))!=null?he:`tool-${c()}`;if(_.has(B))continue;let w=Y(B),$=(Pe=w.toolCall)!=null?Pe:{id:B,status:"running"};$.startedAt=(ot=$.startedAt)!=null?ot:ce((Ne=C.startedAt)!=null?Ne:C.timestamp);let ee=(Jn=(Oe=(At=C.text)!=null?At:C.delta)!=null?Oe:C.message)!=null?Jn:"";ee&&($.chunks=(xn=$.chunks)!=null?xn:[],$.chunks.push(String(ee))),$.status="running",w.toolCall=$,w.streaming=!0;let Ee=C.agentContext;(Ee||C.executionId)&&(w.agentMetadata=(cr=w.agentMetadata)!=null?cr:{executionId:(Kn=Ee==null?void 0:Ee.executionId)!=null?Kn:C.executionId,iteration:(Dn=Ee==null?void 0:Ee.iteration)!=null?Dn:C.iteration}),d(w)}else if(Fe==="tool_complete"){let B=(Mn=(Nn=de(C,!1))!=null?Nn:de(C,!0))!=null?Mn:`tool-${c()}`;if(_.has(B)){_.delete(B);continue}let w=Y(B),$=(et=w.toolCall)!=null?et:{id:B,status:"running"};$.status="complete",C.result!==void 0&&($.result=C.result),typeof C.duration=="number"&&($.duration=C.duration),$.completedAt=ce((X=C.completedAt)!=null?X:C.timestamp);let ee=(an=C.duration)!=null?an:C.executionTime;if(typeof ee=="number")$.durationMs=ee;else{let Rt=(rn=$.startedAt)!=null?rn:Date.now();$.durationMs=Math.max(0,((Wr=$.completedAt)!=null?Wr:Date.now())-Rt)}w.toolCall=$,w.streaming=!1;let Ee=C.agentContext;(Ee||C.executionId)&&(w.agentMetadata=(ln=w.agentMetadata)!=null?ln:{executionId:(vn=Ee==null?void 0:Ee.executionId)!=null?vn:C.executionId,iteration:(ht=Ee==null?void 0:Ee.iteration)!=null?ht:C.iteration}),d(w);let ct=I(C);ct&&M.byCall.delete(ct)}else if(Fe==="step_chunk"||Fe==="step_delta"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=O(),ee=(Hr=(dr=(Rr=(kn=C.text)!=null?kn:C.delta)!=null?Rr:C.content)!=null?dr:C.chunk)!=null?Hr:"";if(ee){let ct=((Gn=ve.get($.id))!=null?Gn:"")+ee;$.rawContent=ct,G.has($.id)||G.set($.id,this.createStreamParser());let Rt=G.get($.id),Mt=ct.trim().startsWith("{")||ct.trim().startsWith("[");if(Mt&&ve.set($.id,ct),Rt.__isPlainTextParser===!0){$.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($);continue}let Ht=Rt.processChunk(ct);if(Ht instanceof Promise)Ht.then(dt=>{var It;let ut=typeof dt=="string"?dt:(It=dt==null?void 0:dt.text)!=null?It:null;if(ut!==null&&ut.trim()!==""){let gt=f;gt&&gt.id===$.id&&(gt.content=ut,d(gt))}else if(!Mt&&!ct.trim().startsWith("<")){let gt=f;gt&&gt.id===$.id&&(gt.content+=ee,ve.delete(gt.id),G.delete(gt.id),gt.rawContent=void 0,d(gt))}}).catch(()=>{$.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($)});else{let dt=typeof Ht=="string"?Ht:(Cn=Ht==null?void 0:Ht.text)!=null?Cn:null;dt!==null&&dt.trim()!==""?($.content=dt,d($)):!Mt&&!ct.trim().startsWith("<")&&($.content+=ee,ve.delete($.id),G.delete($.id),$.rawContent=void 0,d($))}}if(C.isComplete){let Ee=(Et=(Yn=C.result)==null?void 0:Yn.response)!=null?Et:$.content;if(Ee){let ct=ve.get($.id),Rt=ct!=null?ct:q(Ee);$.rawContent=Rt;let Mt=G.get($.id),Nt=null,Ht=!1;if(Mt&&(Nt=Mt.getExtractedText(),Nt===null&&(Nt=Wo(Rt)),Nt===null)){let dt=Mt.processChunk(Rt);dt instanceof Promise?(Ht=!0,dt.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===$.id&&(Ot.content=It,Ot.streaming=!1,G.delete(Ot.id),ve.delete(Ot.id),d(Ot))}})):Nt=typeof dt=="string"?dt:(wn=dt==null?void 0:dt.text)!=null?wn:null}if(!Ht){Nt!==null&&Nt.trim()!==""?$.content=Nt:ve.has($.id)||($.content=q(Ee));let dt=G.get($.id);if(dt){let ut=(Br=dt.close)==null?void 0:Br.call(dt);ut instanceof Promise&&ut.catch(()=>{}),G.delete($.id)}ve.delete($.id),$.streaming=!1,d($)}}}}else if(Fe==="step_complete"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=(On=C.result)==null?void 0:On.response,ee=O();if($!=null){let Ee=G.get(ee.id),ct=!1,Rt=!1;if(Ee){let Mt=Ee.getExtractedText(),Nt=ve.get(ee.id),Ht=Nt!=null?Nt:q($);if(ee.rawContent=Ht,Mt!==null&&Mt.trim()!=="")ee.content=Mt,ct=!0;else{let dt=Wo(Ht);if(dt!==null)ee.content=dt,ct=!0;else{let ut=Ee.processChunk(Ht);if(ut instanceof Promise)Rt=!0,ut.then(It=>{var Ot;let gt=typeof It=="string"?It:(Ot=It==null?void 0:It.text)!=null?Ot:null;if(gt!==null&&gt.trim()!==""){let en=f;en&&en.id===ee.id&&(en.content=gt,en.streaming=!1,G.delete(en.id),ve.delete(en.id),d(en))}else{let en=Ee.getExtractedText(),dn=f;dn&&dn.id===ee.id&&(en!==null&&en.trim()!==""?dn.content=en:ve.has(dn.id)||(dn.content=q($)),dn.streaming=!1,G.delete(dn.id),ve.delete(dn.id),d(dn))}});else{let It=typeof ut=="string"?ut:(Sn=ut==null?void 0:ut.text)!=null?Sn:null;if(It!==null&&It.trim()!=="")ee.content=It,ct=!0;else{let gt=Ee.getExtractedText();gt!==null&&gt.trim()!==""&&(ee.content=gt,ct=!0)}}}}}if(!Rt){if(!ee.rawContent){let Mt=ve.get(ee.id);ee.rawContent=Mt!=null?Mt:q($)}if(!ct&&!ve.has(ee.id)&&(ee.content=q($)),Ee){let Mt=(H=Ee.close)==null?void 0:H.call(Ee);Mt instanceof Promise&&Mt.catch(()=>{})}G.delete(ee.id),ve.delete(ee.id),ee.streaming=!1,d(ee)}}else G.delete(ee.id),ve.delete(ee.id),ee.streaming=!1,d(ee)}else if(Fe==="flow_complete"){let B=($n=C.result)==null?void 0:$n.response;if(B!=null){let w=O(),$=ve.get(w.id),ee=$!=null?$:q(B);w.rawContent=ee;let Ee=q(B),ct=G.get(w.id);if(ct){let Nt=Wo(ee);if(Nt!==null)Ee=Nt;else{let Ht=ct.processChunk(ee);Ht instanceof Promise&&Ht.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===w.id&&(Ot.content=It,Ot.streaming=!1,d(Ot))}});let dt=ct.getExtractedText();dt!==null&&(Ee=dt)}}G.delete(w.id),ve.delete(w.id);let Rt=Ee!==w.content,Mt=w.streaming!==!1;Rt&&(w.content=Ee),w.streaming=!1,(Rt||Mt)&&d(w)}else if(f!==null){let w=f;G.delete(w.id),ve.delete(w.id),w.streaming!==!1&&(w.streaming=!1,d(w))}t({type:"status",status:"idle"})}else if(Fe==="agent_start")xe={executionId:C.executionId,agentId:(Fn=C.agentId)!=null?Fn:"virtual",agentName:(Dr=C.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(Ln=C.maxTurns)!=null?Ln:1,startedAt:ce(C.startedAt)};else if(Fe==="agent_iteration_start"){if(xe&&(xe.currentIteration=C.iteration),Xe==="separate"&&C.iteration>1){let B=f;B&&(B.streaming=!1,d(B),Ke.set(C.iteration-1,B),f=null)}}else if(Fe!=="agent_turn_start"){if(Fe==="agent_turn_delta"){if(C.contentType==="text"){let B=O();B.content+=(Xn=C.delta)!=null?Xn:"",B.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:xe==null?void 0:xe.agentName},d(B)}else if(C.contentType==="thinking"){let B=(Nr=C.turnId)!=null?Nr:`agent-think-${C.iteration}`,w=ge(B);w.reasoning=(In=w.reasoning)!=null?In:{id:B,status:"streaming",chunks:[]},w.reasoning.chunks.push((Pn=C.delta)!=null?Pn:""),w.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},d(w)}else if(C.contentType==="tool_input"){let B=(pr=C.toolCallId)!=null?pr:M.lastId;if(B){let w=b.get(B);w!=null&&w.toolCall&&(w.toolCall.chunks=(ur=w.toolCall.chunks)!=null?ur:[],w.toolCall.chunks.push((uo=C.delta)!=null?uo:""),d(w))}}}else if(Fe==="agent_turn_complete"){let B=C.turnId;if(B){let w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce(C.completedAt);let $=(go=w.reasoning.startedAt)!=null?go:Date.now();w.reasoning.durationMs=Math.max(0,((mo=w.reasoning.completedAt)!=null?mo:Date.now())-$),w.streaming=!1,d(w)}}}else if(Fe==="agent_tool_start"){let B=(Or=C.toolCallId)!=null?Or:`agent-tool-${c()}`;ie(I(C),B);let w=Y(B),$=(gr=w.toolCall)!=null?gr:{id:B,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};$.name=($r=(Ve=C.toolName)!=null?Ve:C.name)!=null?$r:$.name,$.status="running",C.parameters!==void 0&&($.args=C.parameters),$.startedAt=ce((cn=C.startedAt)!=null?cn:C.timestamp),w.toolCall=$,w.streaming=!0,w.agentMetadata={executionId:C.executionId,iteration:C.iteration},d(w)}else if(Fe==="agent_tool_delta"){let B=(Qt=C.toolCallId)!=null?Qt:M.lastId;if(B){let w=(fo=b.get(B))!=null?fo:Y(B);w.toolCall&&(w.toolCall.chunks=(ho=w.toolCall.chunks)!=null?ho:[],w.toolCall.chunks.push((Fr=C.delta)!=null?Fr:""),w.toolCall.status="running",w.streaming=!0,d(w))}}else if(Fe==="agent_tool_complete"){let B=(Zn=C.toolCallId)!=null?Zn:M.lastId;if(B){let w=(Wn=b.get(B))!=null?Wn:Y(B);if(w.toolCall){w.toolCall.status="complete",C.result!==void 0&&(w.toolCall.result=C.result),typeof C.executionTime=="number"&&(w.toolCall.durationMs=C.executionTime),w.toolCall.completedAt=ce((yo=C.completedAt)!=null?yo:C.timestamp),w.streaming=!1,d(w);let $=I(C);$&&M.byCall.delete($)}}}else if(Fe!=="agent_iteration_complete"){if(Fe==="agent_reflection"||Fe==="agent_reflect"){let B=`agent-reflection-${C.executionId}-${C.iteration}`,w={id:B,role:"assistant",content:(bo=C.reflection)!=null?bo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(xo=C.reflection)!=null?xo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};d(w)}else if(Fe==="agent_complete"){xe&&(xe.status=C.success?"complete":"error",xe.completedAt=ce(C.completedAt),xe.stopReason=C.stopReason);let B=f;B&&(B.streaming=!1,d(B)),t({type:"status",status:"idle"})}else if(Fe==="agent_error"){let B=typeof C.error=="string"?C.error:(Qn=(rs=C.error)==null?void 0:rs.message)!=null?Qn:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):t({type:"error",error:new Error(B)})}else if(Fe!=="agent_ping")if(Fe==="agent_approval_start"){let B=(er=C.approvalId)!=null?er:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(bt=xe==null?void 0:xe.agentId)!=null?bt:"virtual",executionId:(fr=(mr=C.executionId)!=null?mr:xe==null?void 0:xe.executionId)!=null?fr:"",toolName:(_r=C.toolName)!=null?_r:"",toolType:C.toolType,description:(zr=C.description)!=null?zr:`Execute ${(jr=C.toolName)!=null?jr:"tool"}`,parameters:C.parameters}};d(w)}else if(Fe==="step_await"&&C.awaitReason==="approval_required"){let B=(qr=C.approvalId)!=null?qr:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Yt=xe==null?void 0:xe.agentId)!=null?Yt:"virtual",executionId:(Rn=(on=C.executionId)!=null?on:xe==null?void 0:xe.executionId)!=null?Rn:"",toolName:($e=C.toolName)!=null?$e:"",toolType:C.toolType,description:(tr=C.description)!=null?tr:`Execute ${(Ur=C.toolName)!=null?Ur:"tool"}`,parameters:C.parameters}};d(w)}else if(Fe==="agent_approval_complete"){let B=C.approvalId;if(B){let $={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(gn=C.decision)!=null?gn:"approved",agentId:(vo=xe==null?void 0:xe.agentId)!=null?vo:"virtual",executionId:(yr=(hr=C.executionId)!=null?hr:xe==null?void 0:xe.executionId)!=null?yr:"",toolName:(nr=C.toolName)!=null?nr:"",description:(_n=C.description)!=null?_n:"",resolvedAt:Date.now()}};d($)}}else if(Fe==="artifact_start"||Fe==="artifact_delta"||Fe==="artifact_update"||Fe==="artifact_complete"){if(Fe==="artifact_start"){let B=C.artifactType,w=String(C.id),$=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:w,artifactType:B,title:$,component:typeof C.component=="string"?C.component:void 0}),le.set(w,{markdown:"",title:$}),!Te.has(w)){Te.add(w);let ee={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:$,artifactType:B,status:"streaming"}})};ne.set(w,ee),d(ee)}}else if(Fe==="artifact_delta"){let B=String(C.id),w=typeof C.delta=="string"?C.delta:String((Co=C.delta)!=null?Co:"");t({type:"artifact_delta",id:B,artDelta:w});let $=le.get(B);$&&($.markdown+=w)}else if(Fe==="artifact_update"){let B=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:B,component:typeof C.component=="string"?C.component:void 0})}else if(Fe==="artifact_complete"){let B=String(C.id);t({type:"artifact_complete",id:B});let w=ne.get(B);if(w){w.streaming=!1;try{let $=JSON.parse((wo=w.rawContent)!=null?wo:"{}");if($.props){$.props.status="complete";let ee=le.get(B);ee!=null&&ee.markdown&&($.props.markdown=ee.markdown)}w.rawContent=JSON.stringify($)}catch{}le.delete(B),d(w),ne.delete(B)}}}else if(Fe==="transcript_insert"){let B=C.message;if(!B||typeof B!="object")continue;let w=String((mn=B.id)!=null?mn:`msg-${c()}`),$=B.role,Ee={id:w,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof B.content=="string"?B.content:"",rawContent:typeof B.rawContent=="string"?B.rawContent:void 0,createdAt:typeof B.createdAt=="string"?B.createdAt:new Date().toISOString(),streaming:B.streaming===!0,...typeof B.variant=="string"?{variant:B.variant}:{},sequence:c()};if(d(Ee),Ee.rawContent)try{let ct=JSON.parse(Ee.rawContent),Rt=(rr=ct==null?void 0:ct.props)==null?void 0:rr.artifactId;typeof Rt=="string"&&Te.add(Rt)}catch{}f=null,m.current=null,G.delete(w),ve.delete(w)}else Fe==="error"&&C.error&&t({type:"error",error:C.error instanceof Error?C.error:new Error(String(C.error))})}}}}}};function rd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Qr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Cr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ro="[Image]";function od(e){return typeof e=="string"?[{type:"text",text:e}]:e}function sd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function ad(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function id(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function ld(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function cd(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function dd(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var yl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],pd=["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=[...yl,...pd];function ud(e){return yl.includes(e)||e.startsWith("image/")}function Ho(e){return ud(e.type)}async function bl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ho(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 xl(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 gd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function vl(e,r){let t=gd(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 Bo=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 p=new Uint8Array(this.remainder.length+r.length);p.set(this.remainder),p.set(r,this.remainder.length),t=p,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 p=this.activeSources.indexOf(a);p!==-1&&this.activeSources.splice(p,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 Do=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 p=Math.sqrt(i/a.length);(n==="silence"?p<s.threshold:p>=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 eo=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 Do;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,p=(n=this.config)==null?void 0:n.clientToken;if(!i||!p)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=${p}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,A=x=>{v||(v=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>A("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+u+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!v){let M=x.code!==1006?` (code ${x.code})`:"";A("WebSocket connection failed"+M+"."+d)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Bo(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,p=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:p,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",d=new Blob(this.audioChunks,{type:u});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),p=new Audio(i);this.currentAudio=p,this.currentAudioUrl=i,p.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===p&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await p.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 ar=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(p=>p[0]).map(p=>p.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(p=>p({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 wr(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new eo(e.runtype);case"browser":if(!ar.isSupported())throw new Error("Browser speech recognition not supported");return new ar(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ms(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return wr({type:"runtype",runtype:e.runtype});if(ar.isSupported())return wr({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function No(e){try{return ms(e),!0}catch{return!1}}var to=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,p;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"),(p=(i=this.callbacks).onError)==null||p.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 vr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return No((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=wr(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",p=(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,d,f,m,v,A;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}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(A=this.pendingVoiceAssistantMessageId)!=null?A:(v=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:v.id;b&&this.ttsSpokenMessageIds.add(b)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(u=this.callbacks).onVoiceStatusChanged)==null||d.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,p,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:(p=r.runtype)==null?void 0:p.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 vr(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:p,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Qr():t==="assistant"?Cr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:p!=null?p: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:p,createdAt:c,sequence:u,streaming:d=!1}=n,m={id:p!=null?p:s==="user"?Qr():s==="assistant"?Cr():`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:d,...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,d,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=Qr(),o=Cr(),a={id:s,role:"user",content:n||Ro,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 p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!A){let b={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(v instanceof Error?(d=(u=this.callbacks).onError)==null||d.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,p;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Cr();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):(p=(i=this.callbacks).onError)==null||p.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 p,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 d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let m=await d.json().catch(()=>null);throw new Error((p=m==null?void 0:m.error)!=null?p:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(u=(c=this.callbacks).onError)==null||u.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var p,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=(p=t.sequence)!=null?p: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},En=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as md from"lucide";var fe=(e,r=24,t="currentColor",n=2)=>{try{let s=e.split("-").map(a=>a.charAt(0).toUpperCase()+a.slice(1)).join(""),o=md[s];return o?fd(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 fd(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 p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&p.setAttribute(c,String(u))}),s.appendChild(p)}}}),s}var Oo={allowedTypes:Hn,maxFileSize:10*1024*1024,maxFiles:4};function hd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yd(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 Sr=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Oo.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Oo.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Oo.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:Oo.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,p;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=xl(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let d=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await bl(c),f=Ho(c)?URL.createObjectURL(c):null,m={id:hd(),file:c,previewUrl:f,contentPart:d};this.attachments.push(m),this.renderPreview(m)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(p=(i=this.config).onAttachmentsChange)==null||p.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(p=>p.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=Ho(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=yd(r.file.type),p=fe(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let c=h("span");c.textContent=vl(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=fe("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 Cl={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"}},wl={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"}},Sl={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 no(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."))?no(e,n):n}function fs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let p=no(e,a);p!==void 0&&(r[i]={path:i,value:p,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 Al(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 El(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]=El(o,s):t[n]=s}return t}function bd(e,r){return r?El(e,r):e}function ro(e,r={}){var s,o,a,i,p,c,u,d,f,m,v,A,b;let t={palette:Cl,semantic:wl,components:Sl},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,...(p=e==null?void 0:e.palette)==null?void 0:p.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=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(A=e==null?void 0:e.semantic)==null?void 0:A.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:bd(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Al(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function hs(e){var v,A,b,x,M,F,S,I,O,k,V,ge,ie,_,ne,Te,le,ke,de,Y,ce,q,G,ve,xe,Ke,Xe,mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae,re,ye,Ce,Qe,he,Pe,Ne,ot,At,Oe,Jn,xn,Kn,Dn,cr,Nn,Mn,et;let r=fs(e),t={};for(let[X,an]of Object.entries(r)){let rn=X.replace(/\./g,"-");t[`--persona-${rn}`]=an.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(A=t["--persona-semantic-colors-secondary"])!=null?A:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(S=t["--persona-semantic-colors-text"])!=null?S:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(I=t["--persona-semantic-colors-text-muted"])!=null?I:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(k=t["--persona-semantic-colors-border"])!=null?k:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(V=t["--persona-semantic-colors-divider"])!=null?V:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(ge=t["--persona-components-voice-recording-indicator"])!=null?ge:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ie=t["--persona-components-voice-recording-background"])!=null?ie:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(_=t["--persona-components-voice-processing-icon"])!=null?_:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Te=t["--persona-components-approval-requested-background"])!=null?Te:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(le=t["--persona-components-approval-requested-border"])!=null?le:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(ke=t["--persona-components-approval-requested-text"])!=null?ke:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(de=t["--persona-components-approval-approve-background"])!=null?de:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Y=t["--persona-components-approval-deny-background"])!=null?Y:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ce=t["--persona-components-attachment-image-background"])!=null?ce:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(q=t["--persona-components-attachment-image-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(G=t["--persona-semantic-typography-fontFamily"])!=null?G:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ve=t["--persona-semantic-typography-fontSize"])!=null?ve:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(xe=t["--persona-semantic-typography-fontWeight"])!=null?xe:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ke=t["--persona-semantic-typography-lineHeight"])!=null?Ke: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"]=(Xe=t["--persona-palette-radius-sm"])!=null?Xe:"0.125rem",t["--persona-radius-md"]=(mt=t["--persona-palette-radius-md"])!=null?mt:"0.375rem",t["--persona-radius-lg"]=(Be=t["--persona-palette-radius-lg"])!=null?Be:"0.5rem",t["--persona-radius-xl"]=(rt=t["--persona-palette-radius-xl"])!=null?rt:"0.75rem",t["--persona-launcher-radius"]=(D=(Me=t["--persona-components-launcher-borderRadius"])!=null?Me:t["--persona-palette-radius-full"])!=null?D:"9999px",t["--persona-button-radius"]=(te=(se=t["--persona-components-button-primary-borderRadius"])!=null?se:t["--persona-palette-radius-full"])!=null?te:"9999px",t["--persona-panel-radius"]=(oe=(z=t["--persona-components-panel-borderRadius"])!=null?z:t["--persona-radius-xl"])!=null?oe:"0.75rem",t["--persona-panel-border"]=(Le=t["--persona-components-panel-border"])!=null?Le:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(J=(Z=t["--persona-components-panel-shadow"])!=null?Z:t["--persona-palette-shadows-xl"])!=null?J:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Ue=(ze=t["--persona-components-input-borderRadius"])!=null?ze:t["--persona-radius-lg"])!=null?Ue:"0.5rem",t["--persona-message-user-radius"]=(qt=(St=t["--persona-components-message-user-borderRadius"])!=null?St:t["--persona-radius-lg"])!=null?qt:"0.5rem",t["--persona-message-assistant-radius"]=(K=(Ut=t["--persona-components-message-assistant-borderRadius"])!=null?Ut:t["--persona-radius-lg"])!=null?K:"0.5rem",t["--persona-header-bg"]=(Ie=t["--persona-components-header-background"])!=null?Ie:t["--persona-surface"],t["--persona-header-border"]=(ft=t["--persona-components-header-border"])!=null?ft:t["--persona-divider"],t["--persona-header-icon-bg"]=(yt=t["--persona-components-header-iconBackground"])!=null?yt:t["--persona-primary"],t["--persona-header-icon-fg"]=(Ze=t["--persona-components-header-iconForeground"])!=null?Ze:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(it=t["--persona-components-header-titleForeground"])!=null?it:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Wt=t["--persona-components-header-subtitleForeground"])!=null?Wt:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(Vt=t["--persona-components-header-actionIconForeground"])!=null?Vt:t["--persona-muted"];let n=(ue=e.components)==null?void 0:ue.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=t["--persona-components-message-user-background"])!=null?T:t["--persona-accent"],t["--persona-message-user-text"]=(Ae=t["--persona-components-message-user-text"])!=null?Ae:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(re=t["--persona-components-message-user-shadow"])!=null?re:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(ye=t["--persona-components-message-assistant-background"])!=null?ye:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ce=t["--persona-components-message-assistant-text"])!=null?Ce:t["--persona-text"],t["--persona-message-assistant-border"]=(Qe=t["--persona-components-message-assistant-border"])!=null?Qe:t["--persona-border"],t["--persona-message-assistant-shadow"]=(he=t["--persona-components-message-assistant-shadow"])!=null?he:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Pe=t["--persona-components-toolBubble-shadow"])!=null?Pe:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(Ne=t["--persona-components-reasoningBubble-shadow"])!=null?Ne:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(ot=t["--persona-components-composer-shadow"])!=null?ot:"none",t["--persona-md-inline-code-bg"]=(At=t["--persona-components-markdown-inlineCode-background"])!=null?At:t["--persona-container"],t["--persona-md-inline-code-color"]=(Oe=t["--persona-components-markdown-inlineCode-foreground"])!=null?Oe:t["--persona-text"],t["--persona-md-link-color"]=(xn=(Jn=t["--persona-components-markdown-link-foreground"])!=null?Jn:t["--persona-accent"])!=null?xn:"#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 p=t["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(t["--persona-md-prose-font-family"]=p);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 d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let X=m.toolbar;X.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=X.iconHoverColor),X.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=X.iconHoverBackground),X.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=X.iconPadding),X.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=X.iconBorderRadius),X.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=X.iconBorder),X.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=X.toggleGroupGap),X.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=X.toggleBorderRadius),X.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=X.copyBackground),X.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=X.copyBorder),X.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=X.copyColor),X.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=X.copyBorderRadius),X.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=X.copyPadding),X.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=X.copyMenuBackground,t["--persona-dropdown-bg"]=(Kn=t["--persona-dropdown-bg"])!=null?Kn:X.copyMenuBackground),X.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=X.copyMenuBorder,t["--persona-dropdown-border"]=(Dn=t["--persona-dropdown-border"])!=null?Dn:X.copyMenuBorder),X.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=X.copyMenuShadow,t["--persona-dropdown-shadow"]=(cr=t["--persona-dropdown-shadow"])!=null?cr:X.copyMenuShadow),X.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=X.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Nn=t["--persona-dropdown-radius"])!=null?Nn:X.copyMenuBorderRadius),X.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=X.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Mn=t["--persona-dropdown-item-hover-bg"])!=null?Mn:X.copyMenuItemHoverBackground),X.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=X.iconBackground),X.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=X.toolbarBorder)}if(m!=null&&m.tab){let X=m.tab;X.background&&(t["--persona-artifact-tab-bg"]=X.background),X.activeBackground&&(t["--persona-artifact-tab-active-bg"]=X.activeBackground),X.activeBorder&&(t["--persona-artifact-tab-active-border"]=X.activeBorder),X.borderRadius&&(t["--persona-artifact-tab-radius"]=X.borderRadius),X.textColor&&(t["--persona-artifact-tab-color"]=X.textColor),X.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=X.hoverBackground),X.listBackground&&(t["--persona-artifact-tab-list-bg"]=X.listBackground),X.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=X.listBorderColor),X.listPadding&&(t["--persona-artifact-tab-list-padding"]=X.listPadding)}if(m!=null&&m.pane){let X=m.pane;if(X.toolbarBackground){let an=(et=no(e,X.toolbarBackground))!=null?et:X.toolbarBackground;t["--persona-artifact-toolbar-bg"]=an}}return t}var xd={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 Tl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function oo(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];Tl(o)&&Tl(s)?t[n]=oo(o,s):t[n]=s}return t}var vd={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"}}},Ml=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$o=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Cd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":$o()},kl=e=>Cd(e),wd=e=>ro(e),Sd=e=>{var t;let r=ro(void 0,{validate:!1});return ro({...e,palette:{...r.palette,colors:{...vd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Fo=e=>{let r=kl(e),t=Ml(e==null?void 0:e.theme),n=Ml(e==null?void 0:e.darkTheme);return r==="dark"?Sd(oo(t!=null?t:{},n!=null?n:{})):wd(t)},Ad=e=>hs(e),ir=(e,r)=>{var o;let t=Fo(r),n=Ad(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)},ys=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e($o())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e($o());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as Ed}from"idiomorph";var Ll=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Ed.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 Il(e,r){var t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,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:"",(p=(i=e.rawContent)==null?void 0:i.length)!=null?p:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(x=(b=(A=e.reasoning)==null?void 0:A.chunks)==null?void 0:b.length)!=null?x:0,(F=(M=e.contentParts)==null?void 0:M.length)!=null?F:0,r].join("\0")}function Pl(){return new Map}function Wl(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Rl(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Hl(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Gt={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 so=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
6
+ `);a=(We=ot.pop())!=null?We:"";for(let $e of ot){let qe=$e.split(`
7
+ `),Lt="message",Tt="";for(let B of qe)B.startsWith("event:")?Lt=B.replace("event:","").trim():B.startsWith("data:")&&(Tt+=B.replace("data:","").trim());if(!Tt)continue;let C;try{C=JSON.parse(Tt)}catch(B){t({type:"error",error:B instanceof Error?B:new Error("Failed to parse chat stream payload")});continue}let Ne=Lt!=="message"?Lt:(nt=C.type)!=null?nt:"message";if((ke=this.onSSEEvent)==null||ke.call(this,Ne,C),this.parseSSEEvent){m.current=f;let B=await this.handleCustomSSEEvent(C,t,m,d,c,v);if(m.current&&m.current!==f&&(f=m.current),B)continue}if(Ne==="reason_start"){let B=(D=U(C,!0))!=null?D:`reason-${c()}`,w=ue(B);w.reasoning=(se=w.reasoning)!=null?se:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(z=w.reasoning.startedAt)!=null?z:ce((te=C.startedAt)!=null?te:C.timestamp),w.reasoning.completedAt=void 0,w.reasoning.durationMs=void 0,w.streaming=!0,w.reasoning.status="streaming",d(w)}else if(Ne==="reason_delta"||Ne==="reason_chunk"){let B=(Ie=(oe=U(C,!1))!=null?oe:U(C,!0))!=null?Ie:`reason-${c()}`,w=ue(B);w.reasoning=(Z=w.reasoning)!=null?Z:{id:B,status:"streaming",chunks:[]},w.reasoning.startedAt=(je=w.reasoning.startedAt)!=null?je:ce((G=C.startedAt)!=null?G:C.timestamp);let $=(jt=(St=(Ue=C.reasoningText)!=null?Ue:C.text)!=null?St:C.delta)!=null?jt:"";if($&&C.hidden!==!0&&w.reasoning.chunks.push(String($)),w.reasoning.status=C.done?"complete":"streaming",C.done){w.reasoning.completedAt=ce((zt=C.completedAt)!=null?zt:C.timestamp);let ee=(J=w.reasoning.startedAt)!=null?J:Date.now();w.reasoning.durationMs=Math.max(0,((Pe=w.reasoning.completedAt)!=null?Pe:Date.now())-ee)}w.streaming=w.reasoning.status!=="complete",d(w)}else if(Ne==="reason_complete"){let B=(yt=(ht=U(C,!1))!=null?ht:U(C,!0))!=null?yt:`reason-${c()}`,w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce((Qe=C.completedAt)!=null?Qe:C.timestamp);let ee=(it=w.reasoning.startedAt)!=null?it:Date.now();w.reasoning.durationMs=Math.max(0,((Wt=w.reasoning.completedAt)!=null?Wt:Date.now())-ee),w.streaming=!1,d(w)}let $=S(C);$&&x.byStep.delete($)}else if(Ne==="tool_start"){let B=(qt=de(C,!0))!=null?qt:`tool-${c()}`,w=(pe=C.toolName)!=null?pe:C.name;if(Le(w)){_.add(B);continue}let $=Y(B),ee=(T=$.toolCall)!=null?T:{id:B,status:"pending"};ee.name=w!=null?w:ee.name,ee.status="running",C.args!==void 0?ee.args=C.args:C.parameters!==void 0&&(ee.args=C.parameters),ee.startedAt=(re=ee.startedAt)!=null?re:ce((Ee=C.startedAt)!=null?Ee:C.timestamp),ee.completedAt=void 0,ee.durationMs=void 0,$.toolCall=ee,$.streaming=!0;let Te=C.agentContext;(Te||C.executionId)&&($.agentMetadata={executionId:(be=Te==null?void 0:Te.executionId)!=null?be:C.executionId,iteration:(we=Te==null?void 0:Te.iteration)!=null?we:C.iteration}),d($)}else if(Ne==="tool_chunk"||Ne==="tool_delta"){let B=(fe=(ze=de(C,!1))!=null?ze:de(C,!0))!=null?fe:`tool-${c()}`;if(_.has(B))continue;let w=Y(B),$=(Re=w.toolCall)!=null?Re:{id:B,status:"running"};$.startedAt=(rt=$.startedAt)!=null?rt:ce((Be=C.startedAt)!=null?Be:C.timestamp);let ee=(Yn=(_e=(At=C.text)!=null?At:C.delta)!=null?_e:C.message)!=null?Yn:"";ee&&($.chunks=(Sn=$.chunks)!=null?Sn:[],$.chunks.push(String(ee))),$.status="running",w.toolCall=$,w.streaming=!0;let Te=C.agentContext;(Te||C.executionId)&&(w.agentMetadata=(ur=w.agentMetadata)!=null?ur:{executionId:(Xn=Te==null?void 0:Te.executionId)!=null?Xn:C.executionId,iteration:(An=Te==null?void 0:Te.iteration)!=null?An:C.iteration}),d(w)}else if(Ne==="tool_complete"){let B=(Pn=(On=de(C,!1))!=null?On:de(C,!0))!=null?Pn:`tool-${c()}`;if(_.has(B)){_.delete(B);continue}let w=Y(B),$=(et=w.toolCall)!=null?et:{id:B,status:"running"};$.status="complete",C.result!==void 0&&($.result=C.result),typeof C.duration=="number"&&($.duration=C.duration),$.completedAt=ce((an=C.completedAt)!=null?an:C.timestamp);let ee=(fn=C.duration)!=null?fn:C.executionTime;if(typeof ee=="number")$.durationMs=ee;else{let Rt=(en=$.startedAt)!=null?en:Date.now();$.durationMs=Math.max(0,(($n=$.completedAt)!=null?$n:Date.now())-Rt)}w.toolCall=$,w.streaming=!1;let Te=C.agentContext;(Te||C.executionId)&&(w.agentMetadata=(Yt=w.agentMetadata)!=null?Yt:{executionId:(ln=Te==null?void 0:Te.executionId)!=null?ln:C.executionId,iteration:(dt=Te==null?void 0:Te.iteration)!=null?dt:C.iteration}),d(w);let lt=I(C);lt&&M.byCall.delete(lt)}else if(Ne==="step_chunk"||Ne==="step_delta"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=O(),ee=(Hr=(Fn=(Wn=(X=C.text)!=null?X:C.delta)!=null?Wn:C.content)!=null?Fn:C.chunk)!=null?Hr:"";if(ee){let lt=((Zn=Ce.get($.id))!=null?Zn:"")+ee;$.rawContent=lt,K.has($.id)||K.set($.id,this.createStreamParser());let Rt=K.get($.id),Mt=lt.trim().startsWith("{")||lt.trim().startsWith("[");if(Mt&&Ce.set($.id,lt),Rt.__isPlainTextParser===!0){$.content+=ee,Ce.delete($.id),K.delete($.id),$.rawContent=void 0,d($);continue}let Ht=Rt.processChunk(lt);if(Ht instanceof Promise)Ht.then(ct=>{var It;let ut=typeof ct=="string"?ct:(It=ct==null?void 0:ct.text)!=null?It:null;if(ut!==null&&ut.trim()!==""){let gt=f;gt&&gt.id===$.id&&(gt.content=ut,d(gt))}else if(!Mt&&!lt.trim().startsWith("<")){let gt=f;gt&&gt.id===$.id&&(gt.content+=ee,Ce.delete(gt.id),K.delete(gt.id),gt.rawContent=void 0,d(gt))}}).catch(()=>{$.content+=ee,Ce.delete($.id),K.delete($.id),$.rawContent=void 0,d($)});else{let ct=typeof Ht=="string"?Ht:(En=Ht==null?void 0:Ht.text)!=null?En:null;ct!==null&&ct.trim()!==""?($.content=ct,d($)):!Mt&&!lt.trim().startsWith("<")&&($.content+=ee,Ce.delete($.id),K.delete($.id),$.rawContent=void 0,d($))}}if(C.isComplete){let Te=(Et=(Qn=C.result)==null?void 0:Qn.response)!=null?Et:$.content;if(Te){let lt=Ce.get($.id),Rt=lt!=null?lt:q(Te);$.rawContent=Rt;let Mt=K.get($.id),Nt=null,Ht=!1;if(Mt&&(Nt=Mt.getExtractedText(),Nt===null&&(Nt=Wo(Rt)),Nt===null)){let ct=Mt.processChunk(Rt);ct instanceof Promise?(Ht=!0,ct.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===$.id&&(Ot.content=It,Ot.streaming=!1,K.delete(Ot.id),Ce.delete(Ot.id),d(Ot))}})):Nt=typeof ct=="string"?ct:(Tn=ct==null?void 0:ct.text)!=null?Tn:null}if(!Ht){Nt!==null&&Nt.trim()!==""?$.content=Nt:Ce.has($.id)||($.content=q(Te));let ct=K.get($.id);if(ct){let ut=(Br=ct.close)==null?void 0:Br.call(ct);ut instanceof Promise&&ut.catch(()=>{}),K.delete($.id)}Ce.delete($.id),$.streaming=!1,d($)}}}}else if(Ne==="step_complete"){let B=C.stepType,w=C.executionType;if(B==="tool"||w==="context")continue;let $=(_n=C.result)==null?void 0:_n.response,ee=O();if($!=null){let Te=K.get(ee.id),lt=!1,Rt=!1;if(Te){let Mt=Te.getExtractedText(),Nt=Ce.get(ee.id),Ht=Nt!=null?Nt:q($);if(ee.rawContent=Ht,Mt!==null&&Mt.trim()!=="")ee.content=Mt,lt=!0;else{let ct=Wo(Ht);if(ct!==null)ee.content=ct,lt=!0;else{let ut=Te.processChunk(Ht);if(ut instanceof Promise)Rt=!0,ut.then(It=>{var Ot;let gt=typeof It=="string"?It:(Ot=It==null?void 0:It.text)!=null?Ot:null;if(gt!==null&&gt.trim()!==""){let nn=f;nn&&nn.id===ee.id&&(nn.content=gt,nn.streaming=!1,K.delete(nn.id),Ce.delete(nn.id),d(nn))}else{let nn=Te.getExtractedText(),un=f;un&&un.id===ee.id&&(nn!==null&&nn.trim()!==""?un.content=nn:Ce.has(un.id)||(un.content=q($)),un.streaming=!1,K.delete(un.id),Ce.delete(un.id),d(un))}});else{let It=typeof ut=="string"?ut:(Mn=ut==null?void 0:ut.text)!=null?Mn:null;if(It!==null&&It.trim()!=="")ee.content=It,lt=!0;else{let gt=Te.getExtractedText();gt!==null&&gt.trim()!==""&&(ee.content=gt,lt=!0)}}}}}if(!Rt){if(!ee.rawContent){let Mt=Ce.get(ee.id);ee.rawContent=Mt!=null?Mt:q($)}if(!lt&&!Ce.has(ee.id)&&(ee.content=q($)),Te){let Mt=(H=Te.close)==null?void 0:H.call(Te);Mt instanceof Promise&&Mt.catch(()=>{})}K.delete(ee.id),Ce.delete(ee.id),ee.streaming=!1,d(ee)}}else K.delete(ee.id),Ce.delete(ee.id),ee.streaming=!1,d(ee)}else if(Ne==="flow_complete"){let B=(jn=C.result)==null?void 0:jn.response;if(B!=null){let w=O(),$=Ce.get(w.id),ee=$!=null?$:q(B);w.rawContent=ee;let Te=q(B),lt=K.get(w.id);if(lt){let Nt=Wo(ee);if(Nt!==null)Te=Nt;else{let Ht=lt.processChunk(ee);Ht instanceof Promise&&Ht.then(ut=>{var gt;let It=typeof ut=="string"?ut:(gt=ut==null?void 0:ut.text)!=null?gt:null;if(It!==null){let Ot=f;Ot&&Ot.id===w.id&&(Ot.content=It,Ot.streaming=!1,d(Ot))}});let ct=lt.getExtractedText();ct!==null&&(Te=ct)}}K.delete(w.id),Ce.delete(w.id);let Rt=Te!==w.content,Mt=w.streaming!==!1;Rt&&(w.content=Te),w.streaming=!1,(Rt||Mt)&&d(w)}else if(f!==null){let w=f;K.delete(w.id),Ce.delete(w.id),w.streaming!==!1&&(w.streaming=!1,d(w))}t({type:"status",status:"idle"})}else if(Ne==="agent_start")ve={executionId:C.executionId,agentId:(zn=C.agentId)!=null?zn:"virtual",agentName:(Dr=C.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(hn=C.maxTurns)!=null?hn:1,startedAt:ce(C.startedAt)};else if(Ne==="agent_iteration_start"){if(ve&&(ve.currentIteration=C.iteration),Ze==="separate"&&C.iteration>1){let B=f;B&&(B.streaming=!1,d(B),Ge.set(C.iteration-1,B),f=null)}}else if(Ne!=="agent_turn_start"){if(Ne==="agent_turn_delta"){if(C.contentType==="text"){let B=O();B.content+=(er=C.delta)!=null?er:"",B.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:ve==null?void 0:ve.agentName},d(B)}else if(C.contentType==="thinking"){let B=(Nr=C.turnId)!=null?Nr:`agent-think-${C.iteration}`,w=ue(B);w.reasoning=(Rn=w.reasoning)!=null?Rn:{id:B,status:"streaming",chunks:[]},w.reasoning.chunks.push((yn=C.delta)!=null?yn:""),w.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},d(w)}else if(C.contentType==="tool_input"){let B=(gr=C.toolCallId)!=null?gr:M.lastId;if(B){let w=b.get(B);w!=null&&w.toolCall&&(w.toolCall.chunks=(mr=w.toolCall.chunks)!=null?mr:[],w.toolCall.chunks.push((uo=C.delta)!=null?uo:""),d(w))}}}else if(Ne==="agent_turn_complete"){let B=C.turnId;if(B){let w=A.get(B);if(w!=null&&w.reasoning){w.reasoning.status="complete",w.reasoning.completedAt=ce(C.completedAt);let $=(go=w.reasoning.startedAt)!=null?go:Date.now();w.reasoning.durationMs=Math.max(0,((mo=w.reasoning.completedAt)!=null?mo:Date.now())-$),w.streaming=!1,d(w)}}}else if(Ne==="agent_tool_start"){let B=(Or=C.toolCallId)!=null?Or:`agent-tool-${c()}`;ie(I(C),B);let w=Y(B),$=(fr=w.toolCall)!=null?fr:{id:B,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};$.name=($r=(Je=C.toolName)!=null?Je:C.name)!=null?$r:$.name,$.status="running",C.parameters!==void 0&&($.args=C.parameters),$.startedAt=ce((pn=C.startedAt)!=null?pn:C.timestamp),w.toolCall=$,w.streaming=!0,w.agentMetadata={executionId:C.executionId,iteration:C.iteration},d(w)}else if(Ne==="agent_tool_delta"){let B=(tn=C.toolCallId)!=null?tn:M.lastId;if(B){let w=(fo=b.get(B))!=null?fo:Y(B);w.toolCall&&(w.toolCall.chunks=(ho=w.toolCall.chunks)!=null?ho:[],w.toolCall.chunks.push((Fr=C.delta)!=null?Fr:""),w.toolCall.status="running",w.streaming=!0,d(w))}}else if(Ne==="agent_tool_complete"){let B=(tr=C.toolCallId)!=null?tr:M.lastId;if(B){let w=(Hn=b.get(B))!=null?Hn:Y(B);if(w.toolCall){w.toolCall.status="complete",C.result!==void 0&&(w.toolCall.result=C.result),typeof C.executionTime=="number"&&(w.toolCall.durationMs=C.executionTime),w.toolCall.completedAt=ce((yo=C.completedAt)!=null?yo:C.timestamp),w.streaming=!1,d(w);let $=I(C);$&&M.byCall.delete($)}}}else if(Ne!=="agent_iteration_complete"){if(Ne==="agent_reflection"||Ne==="agent_reflect"){let B=`agent-reflection-${C.executionId}-${C.iteration}`,w={id:B,role:"assistant",content:(bo=C.reflection)!=null?bo:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:c(),reasoning:{id:B,status:"complete",chunks:[(xo=C.reflection)!=null?xo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};d(w)}else if(Ne==="agent_complete"){ve&&(ve.status=C.success?"complete":"error",ve.completedAt=ce(C.completedAt),ve.stopReason=C.stopReason);let B=f;B&&(B.streaming=!1,d(B)),t({type:"status",status:"idle"})}else if(Ne==="agent_error"){let B=typeof C.error=="string"?C.error:(nr=(rs=C.error)==null?void 0:rs.message)!=null?nr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",B):t({type:"error",error:new Error(B)})}else if(Ne!=="agent_ping")if(Ne==="agent_approval_start"){let B=(rr=C.approvalId)!=null?rr:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(bt=ve==null?void 0:ve.agentId)!=null?bt:"virtual",executionId:(yr=(hr=C.executionId)!=null?hr:ve==null?void 0:ve.executionId)!=null?yr:"",toolName:(_r=C.toolName)!=null?_r:"",toolType:C.toolType,description:(zr=C.description)!=null?zr:`Execute ${(jr=C.toolName)!=null?jr:"tool"}`,parameters:C.parameters}};d(w)}else if(Ne==="step_await"&&C.awaitReason==="approval_required"){let B=(qr=C.approvalId)!=null?qr:`approval-${c()}`,w={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:"pending",agentId:(Xt=ve==null?void 0:ve.agentId)!=null?Xt:"virtual",executionId:(Bn=(cn=C.executionId)!=null?cn:ve==null?void 0:ve.executionId)!=null?Bn:"",toolName:(De=C.toolName)!=null?De:"",toolType:C.toolType,description:(or=C.description)!=null?or:`Execute ${(Vr=C.toolName)!=null?Vr:"tool"}`,parameters:C.parameters}};d(w)}else if(Ne==="agent_approval_complete"){let B=C.approvalId;if(B){let $={id:`approval-${B}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:c(),approval:{id:B,status:(bn=C.decision)!=null?bn:"approved",agentId:(vo=ve==null?void 0:ve.agentId)!=null?vo:"virtual",executionId:(xr=(br=C.executionId)!=null?br:ve==null?void 0:ve.executionId)!=null?xr:"",toolName:(sr=C.toolName)!=null?sr:"",description:(qn=C.description)!=null?qn:"",resolvedAt:Date.now()}};d($)}}else if(Ne==="artifact_start"||Ne==="artifact_delta"||Ne==="artifact_update"||Ne==="artifact_complete"){if(Ne==="artifact_start"){let B=C.artifactType,w=String(C.id),$=typeof C.title=="string"?C.title:void 0;if(t({type:"artifact_start",id:w,artifactType:B,title:$,component:typeof C.component=="string"?C.component:void 0}),le.set(w,{markdown:"",title:$}),!Me.has(w)){Me.add(w);let ee={id:`artifact-ref-${w}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:c(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:w,title:$,artifactType:B,status:"streaming"}})};ne.set(w,ee),d(ee)}}else if(Ne==="artifact_delta"){let B=String(C.id),w=typeof C.delta=="string"?C.delta:String((Co=C.delta)!=null?Co:"");t({type:"artifact_delta",id:B,artDelta:w});let $=le.get(B);$&&($.markdown+=w)}else if(Ne==="artifact_update"){let B=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};t({type:"artifact_update",id:String(C.id),props:B,component:typeof C.component=="string"?C.component:void 0})}else if(Ne==="artifact_complete"){let B=String(C.id);t({type:"artifact_complete",id:B});let w=ne.get(B);if(w){w.streaming=!1;try{let $=JSON.parse((wo=w.rawContent)!=null?wo:"{}");if($.props){$.props.status="complete";let ee=le.get(B);ee!=null&&ee.markdown&&($.props.markdown=ee.markdown)}w.rawContent=JSON.stringify($)}catch{}le.delete(B),d(w),ne.delete(B)}}}else if(Ne==="transcript_insert"){let B=C.message;if(!B||typeof B!="object")continue;let w=String((xn=B.id)!=null?xn:`msg-${c()}`),$=B.role,Te={id:w,role:$==="user"?"user":$==="system"?"system":"assistant",content:typeof B.content=="string"?B.content:"",rawContent:typeof B.rawContent=="string"?B.rawContent:void 0,createdAt:typeof B.createdAt=="string"?B.createdAt:new Date().toISOString(),streaming:B.streaming===!0,...typeof B.variant=="string"?{variant:B.variant}:{},sequence:c()};if(d(Te),Te.rawContent)try{let lt=JSON.parse(Te.rawContent),Rt=(ar=lt==null?void 0:lt.props)==null?void 0:ar.artifactId;typeof Rt=="string"&&Me.add(Rt)}catch{}f=null,m.current=null,K.delete(w),Ce.delete(w)}else Ne==="error"&&C.error&&t({type:"error",error:C.error instanceof Error?C.error:new Error(String(C.error))})}}}}}};function rd(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`msg_${e}_${r}`}function Qr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`usr_${e}_${r}`}function Sr(){let e=Date.now().toString(36),r=Math.random().toString(36).substring(2,10);return`ast_${e}_${r}`}var Ro="[Image]";function od(e){return typeof e=="string"?[{type:"text",text:e}]:e}function sd(e){return typeof e=="string"?e:e.filter(r=>r.type==="text").map(r=>r.text).join("")}function ad(e){return typeof e=="string"?!1:e.some(r=>r.type==="image")}function id(e){return typeof e=="string"?[]:e.filter(r=>r.type==="image")}function gs(e){return{type:"text",text:e}}function ld(e,r){return{type:"image",image:e,...(r==null?void 0:r.mimeType)&&{mimeType:r.mimeType},...(r==null?void 0:r.alt)&&{alt:r.alt}}}async function cd(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;r({type:"image",image:s,mimeType:e.type,alt:e.name})},n.onerror=()=>t(new Error("Failed to read file")),n.readAsDataURL(e)})}function dd(e,r=["image/png","image/jpeg","image/gif","image/webp"],t=10*1024*1024){return r.includes(e.type)?e.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${r.join(", ")}`}}var yl=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],pd=["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"],Dn=[...yl,...pd];function ud(e){return yl.includes(e)||e.startsWith("image/")}function Ho(e){return ud(e.type)}async function bl(e){return new Promise((r,t)=>{let n=new FileReader;n.onload=()=>{let s=n.result;Ho(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 xl(e,r=Dn,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 gd(e){let r=e.split(".");return r.length>1?r.pop().toLowerCase():""}function vl(e,r){let t=gd(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 Bo=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 p=new Uint8Array(this.remainder.length+r.length);p.set(this.remainder),p.set(r,this.remainder.length),t=p,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 p=this.activeSources.indexOf(a);p!==-1&&this.activeSources.splice(p,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 Do=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 p=Math.sqrt(i/a.length);(n==="silence"?p<s.threshold:p>=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 eo=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 Do;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,p=(n=this.config)==null?void 0:n.clientToken;if(!i||!p)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=${p}`;this.ws=new WebSocket(c),this.setupWebSocketHandlers();let u=`${o}//${a}/ws/agents/${i}/voice?token=...`,d=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,m)=>{if(!this.ws)return m(new Error("WebSocket not created"));let v=!1,A=x=>{v||(v=!0,clearTimeout(b),m(new Error(x)))},b=setTimeout(()=>A("WebSocket connection timed out."+d),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(b),f())},{once:!0}),this.ws.addEventListener("error",()=>{A("WebSocket connection failed to "+u+"."+d)},{once:!0}),this.ws.addEventListener("close",x=>{if(!x.wasClean&&!v){let M=x.code!==1006?` (code ${x.code})`:"";A("WebSocket connection failed"+M+"."+d)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(r=>r("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(r=>r("disconnected"))},this.ws.onerror=r=>{this.errorCallbacks.forEach(t=>t(new Error("WebSocket error"))),this.statusCallbacks.forEach(t=>t("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=r=>{if(r.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(r.data));return}try{let t=JSON.parse(r.data);this.handleWebSocketMessage(t)}catch{this.errorCallbacks.forEach(n=>n(new Error("Message parsing failed")))}})}handleWebSocketMessage(r){var t,n;switch(r.type){case"session_config":r.interruptionMode&&(this.interruptionMode=r.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:r.response.agentResponseText||r.response.transcript,transcript:r.response.transcript,audio:r.response.audio,confidence:.95,provider:"runtype"})),(t=r.response.audio)!=null&&t.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(r.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(n=r.response.audio)!=null&&n.base64;break;case"audio_end":if(r.requestId&&r.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(r.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(r){r.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Bo(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,p=(s=(n=this.config)==null?void 0:n.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:p,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",d=new Blob(this.audioChunks,{type:u});await this.sendAudio(d),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(c=>c("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(r=>r.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(r=>r.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(r=>r("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let r=this.w;if(!this.mediaStream&&r&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&r&&(this.audioContext=new(r.AudioContext||r.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let t=this.audioContext,n=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(t,this.mediaStream,"speech",{threshold:n,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(r=>{this.errorCallbacks.forEach(t=>t(r instanceof Error?r:new Error(String(r))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(r){var t;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(n=>n(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(n=>n("error"));return}try{let n=await this.blobToBase64(r),s=this.getFormatFromMimeType(r.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:n,format:s,sampleRate:16e3,voiceId:(t=this.config)==null?void 0:t.voiceId,requestId:o}))}catch(n){this.errorCallbacks.forEach(s=>s(n)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(r){return r.includes("wav")?"wav":r.includes("mpeg")||r.includes("mp3")?"mp3":"webm"}blobToBase64(r){return new Promise((t,n)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];t(a)},s.onerror=n,s.readAsDataURL(r)})}async playAudio(r){if(!r.base64)return;let t=atob(r.base64),n=new Uint8Array(t.length);for(let c=0;c<t.length;c++)n[c]=t.charCodeAt(c);let s=r.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([n],{type:o}),i=URL.createObjectURL(a),p=new Audio(i);this.currentAudio=p,this.currentAudioUrl=i,p.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===p&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(c=>c("idle")))},await p.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 cr=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(p=>p[0]).map(p=>p.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(p=>p({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 Ar(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new eo(e.runtype);case"browser":if(!cr.isSupported())throw new Error("Browser speech recognition not supported");return new cr(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function ms(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Ar({type:"runtype",runtype:e.runtype});if(cr.isSupported())return Ar({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function No(e){try{return ms(e),!0}catch{return!1}}var to=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,p;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"),(p=(i=this.callbacks).onError)==null||p.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 wr(r),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.callbacks.onStatusChanged(this.status)}setSSEEventCallback(r){this.client.setSSEEventCallback(r)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var r;return((r=this.agentExecution)==null?void 0:r.status)==="running"}isVoiceSupported(){var r;return No((r=this.config.voiceRecognition)==null?void 0:r.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var r;return(r=this.voiceProvider)!=null&&r.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var r;(r=this.voiceProvider)!=null&&r.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var r,t,n;return(n=(t=(r=this.voiceProvider)==null?void 0:r.isBargeInActive)==null?void 0:t.call(r))!=null?n:!1}async deactivateBargeIn(){var r;(r=this.voiceProvider)!=null&&r.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}setupVoice(r){var t,n,s;try{let o=r||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Ar(o);let a=(t=this.config.voiceRecognition)!=null?t:{},i=(n=a.processingText)!=null?n:"\u{1F3A4} Processing voice...",p=(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,d,f,m,v,A;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}):(d=c.transcript)!=null&&d.trim()&&this.injectUserMessage({content:c.transcript.trim()}),this.pendingVoiceAssistantMessageId&&((f=c.text)!=null&&f.trim())?this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c.text.trim(),createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}):(m=c.text)!=null&&m.trim()&&this.injectAssistantMessage({content:c.text.trim()});{let b=(A=this.pendingVoiceAssistantMessageId)!=null?A:(v=[...this.messages].reverse().find(x=>x.role==="assistant"))==null?void 0:v.id;b&&this.ttsSpokenMessageIds.add(b)}this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null}}),this.voiceProvider.onError(c=>{console.error("Voice error:",c),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:p,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(c=>{var u,d;this.voiceStatus=c,this.voiceActive=c==="listening",(d=(u=this.callbacks).onVoiceStatusChanged)==null||d.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,p,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:(p=r.runtype)==null?void 0:p.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 wr(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:p,streaming:c=!1,voiceProcessing:u}=r,f={id:a!=null?a:t==="user"?Qr():t==="assistant"?Sr():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:n,createdAt:i!=null?i:new Date().toISOString(),sequence:p!=null?p: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:p,createdAt:c,sequence:u,streaming:d=!1}=n,m={id:p!=null?p:s==="user"?Qr():s==="assistant"?Sr():`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:d,...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,d,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=Qr(),o=Sr(),a={id:s,role:"user",content:n||Ro,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 p=[...this.messages];try{await this.client.dispatch({messages:p,signal:i.signal,assistantMessageId:o},this.handleEvent)}catch(v){let A=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!A){let b={id:o,role:"assistant",createdAt:new Date().toISOString(),content:"It looks like the proxy isn't returning a real response yet. Here's a sample message so you can continue testing locally.",sequence:this.nextSequence()};this.appendMessage(b)}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,A||(v instanceof Error?(d=(u=this.callbacks).onError)==null||d.call(u,v):(m=(f=this.callbacks).onError)==null||m.call(f,new Error(String(v))))}}async continueConversation(){var s,o,a,i,p;if(this.streaming)return;(s=this.abortController)==null||s.abort();let r=Sr();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):(p=(i=this.callbacks).onError)==null||p.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 p,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 d;if(i?d=await i({approvalId:r.id,executionId:r.executionId,agentId:r.agentId,toolName:r.toolName},t):d=await this.client.resolveApproval({agentId:r.agentId,executionId:r.executionId,approvalId:r.id},t),d){let f=null;if(d instanceof Response){if(!d.ok){let m=await d.json().catch(()=>null);throw new Error((p=m==null?void 0:m.error)!=null?p:`Approval request failed: ${d.status}`)}f=d.body}else d instanceof ReadableStream&&(f=d);f?await this.connectStream(f):t==="denied"&&this.appendMessage({id:`denial-${r.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}}catch(d){(u=(c=this.callbacks).onError)==null||u.call(c,d instanceof Error?d:new Error(String(d)))}}cancel(){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var r;this.stopSpeaking(),(r=this.abortController)==null||r.abort(),this.abortController=null,this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(r){return this.artifacts.get(r)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(r){this.selectedArtifactId=r,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(r){var s;let t=r.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(r.artifactType==="markdown"){let o={id:t,artifactType:"markdown",title:r.title,status:"complete",markdown:r.content};return this.artifacts.set(t,o),this.selectedArtifactId=t,this.emitArtifactsState(),o}let n={id:t,artifactType:"component",title:r.title,status:"complete",component:r.component,props:(s=r.props)!=null?s:{}};return this.artifacts.set(t,n),this.selectedArtifactId=t,this.emitArtifactsState(),n}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var r,t;(t=(r=this.callbacks).onArtifactsState)==null||t.call(r,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(r){var t,n;switch(r.type){case"artifact_start":{r.artifactType==="markdown"?this.artifacts.set(r.id,{id:r.id,artifactType:"markdown",title:r.title,status:"streaming",markdown:""}):this.artifacts.set(r.id,{id:r.id,artifactType:"component",title:r.title,status:"streaming",component:(t=r.component)!=null?t:"",props:{}}),this.selectedArtifactId=r.id;break}case"artifact_delta":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="markdown"&&(s.markdown=((n=s.markdown)!=null?n:"")+r.artDelta);break}case"artifact_update":{let s=this.artifacts.get(r.id);(s==null?void 0:s.artifactType)==="component"&&(s.props={...s.props,...r.props},r.component&&(s.component=r.component));break}case"artifact_complete":{let s=this.artifacts.get(r.id);s&&(s.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(r){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.messages=this.sortMessages(r.map(n=>{var s;return{...n,streaming:!1,sequence:(s=n.sequence)!=null?s:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}setStatus(r){this.status!==r&&(this.status=r,this.callbacks.onStatusChanged(r))}setStreaming(r){if(this.streaming===r)return;let t=this.streaming;this.streaming=r,this.callbacks.onStreamingChanged(r),t&&!r&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let r=this.config.textToSpeech;if(!(r!=null&&r.enabled)||!(!r.provider||r.provider==="browser"||r.provider==="runtype"&&r.browserFallback))return;let n=[...this.messages].reverse().find(o=>o.role==="assistant"&&o.content&&!o.voiceProcessing);if(!n)return;if(this.ttsSpokenMessageIds.has(n.id)){this.ttsSpokenMessageIds.delete(n.id);return}let s=n.content;s.trim()&&this.speak(s,r)}speak(r,t){if(typeof window=="undefined"||!("speechSynthesis"in window))return;let n=window.speechSynthesis;n.cancel();let s=new SpeechSynthesisUtterance(r),o=n.getVoices();if(t.voice){let a=o.find(i=>i.name===t.voice);a&&(s.voice=a)}else o.length>0&&(s.voice=t.pickVoice?t.pickVoice(o):e.pickBestVoice(o));t.rate!==void 0&&(s.rate=t.rate),t.pitch!==void 0&&(s.pitch=t.pitch),setTimeout(()=>n.speak(s),50)}static pickBestVoice(r){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let s of t){let o=r.find(a=>a.name===s);if(o)return o}return(n=r.find(s=>s.lang.startsWith("en")))!=null?n:r[0]}stopSpeaking(){typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(r){let t=this.ensureSequence(r);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(r){let t=this.ensureSequence(r),n=this.messages.findIndex(s=>s.id===t.id);if(n===-1){this.appendMessage(t);return}this.messages=this.messages.map((s,o)=>o===n?{...s,...t}:s),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(r){return r.sequence!==void 0?{...r}:{...r,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(r){return[...r].sort((t,n)=>{var p,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=(p=t.sequence)!=null?p: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},Ln=(e,r,t)=>{let n=e.createElement(r);return t&&(n.className=t),n};import*as md 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=md[s];return o?fd(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 fd(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 p=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,u])=>{c!=="stroke"&&p.setAttribute(c,String(u))}),s.appendChild(p)}}}),s}var Oo={allowedTypes:Dn,maxFileSize:10*1024*1024,maxFiles:4};function hd(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function yd(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 Er=class e{constructor(r={}){this.attachments=[];this.previewsContainer=null;var t,n,s;this.config={allowedTypes:(t=r.allowedTypes)!=null?t:Oo.allowedTypes,maxFileSize:(n=r.maxFileSize)!=null?n:Oo.maxFileSize,maxFiles:(s=r.maxFiles)!=null?s:Oo.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:Oo.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,p;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=xl(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let d=(s=u.error)!=null&&s.includes("type")?"type":"size";(a=(o=this.config).onFileRejected)==null||a.call(o,c,d);continue}try{let d=await bl(c),f=Ho(c)?URL.createObjectURL(c):null,m={id:hd(),file:c,previewUrl:f,contentPart:d};this.attachments.push(m),this.renderPreview(m)}catch(d){console.error("[AttachmentManager] Failed to process file:",d)}}this.updatePreviewsVisibility(),(p=(i=this.config).onAttachmentsChange)==null||p.call(i,this.getAttachments())}}removeAttachment(r){var o,a,i;let t=this.attachments.findIndex(p=>p.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=Ho(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=yd(r.file.type),p=me(i,20,"var(--persona-muted, #6b7280)",1.5);p&&a.appendChild(p);let c=h("span");c.textContent=vl(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 Cl={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"},info:{50:"#eff6ff",100:"#dbeafe",200:"#bfdbfe",300:"#93c5fd",400:"#60a5fa",500:"#3b82f6",600:"#2563eb",700:"#1d4ed8",800:"#1e40af",900:"#1e3a8a",950:"#172554"}},spacing:{0:"0px",1:"0.25rem",2:"0.5rem",3:"0.75rem",4:"1rem",5:"1.25rem",6:"1.5rem",8:"2rem",10:"2.5rem",12:"3rem",16:"4rem",20:"5rem",24:"6rem",32:"8rem",40:"10rem",48:"12rem",56:"14rem",64:"16rem"},typography:{fontFamily:{sans:'system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif',serif:'Georgia, Cambria, "Times New Roman", Times, serif',mono:"ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace"},fontSize:{xs:"0.75rem",sm:"0.875rem",base:"1rem",lg:"1.125rem",xl:"1.25rem","2xl":"1.5rem","3xl":"1.875rem","4xl":"2.25rem"},fontWeight:{normal:"400",medium:"500",semibold:"600",bold:"700"},lineHeight:{tight:"1.25",normal:"1.5",relaxed:"1.625"}},shadows:{none:"none",sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)"},borders:{none:"none",sm:"1px solid",md:"2px solid",lg:"4px solid"},radius:{none:"0px",sm:"0.125rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem",full:"9999px"}},wl={colors:{primary:"palette.colors.primary.500",secondary:"palette.colors.secondary.500",accent:"palette.colors.primary.600",surface:"palette.colors.gray.50",background:"palette.colors.gray.50",container:"palette.colors.gray.50",text:"palette.colors.gray.900",textMuted:"palette.colors.gray.500",textInverse:"palette.colors.gray.50",border:"palette.colors.gray.200",divider:"palette.colors.gray.200",interactive:{default:"palette.colors.primary.600",hover:"palette.colors.primary.700",focus:"palette.colors.primary.600",active:"palette.colors.primary.600",disabled:"palette.colors.gray.300"},feedback:{success:"palette.colors.success.500",warning:"palette.colors.warning.500",error:"palette.colors.error.500",info:"palette.colors.info.500"}},spacing:{xs:"palette.spacing.1",sm:"palette.spacing.2",md:"palette.spacing.4",lg:"palette.spacing.6",xl:"palette.spacing.8","2xl":"palette.spacing.10"},typography:{fontFamily:"palette.typography.fontFamily.sans",fontSize:"palette.typography.fontSize.base",fontWeight:"palette.typography.fontWeight.normal",lineHeight:"palette.typography.lineHeight.normal"}},Sl={button:{primary:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},secondary:{background:"semantic.colors.surface",foreground:"semantic.colors.secondary",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md"},ghost:{background:"transparent",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},input:{background:"palette.colors.gray.50",placeholder:"palette.colors.gray.400",borderRadius:"palette.radius.lg",padding:"semantic.spacing.md",focus:{border:"palette.colors.gray.400",ring:"palette.colors.gray.400"}},launcher:{background:"palette.colors.primary.500",foreground:"palette.colors.primary.50",border:"palette.colors.gray.200",size:"60px",iconSize:"28px",borderRadius:"palette.radius.full",shadow:"palette.shadows.lg"},panel:{width:"min(400px, calc(100vw - 24px))",maxWidth:"400px",height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"}},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"}},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 no(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."))?no(e,n):n}function fs(e){let r={};function t(n,s){for(let[o,a]of Object.entries(n)){let i=`${s}.${o}`;if(typeof a=="string"){let p=no(e,a);p!==void 0&&(r[i]={path:i,value:p,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 Al(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 El(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]=El(o,s):t[n]=s}return t}function bd(e,r){return r?El(e,r):e}function ro(e,r={}){var s,o,a,i,p,c,u,d,f,m,v,A,b;let t={palette:Cl,semantic:wl,components:Sl},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,...(p=e==null?void 0:e.palette)==null?void 0:p.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=(d=e==null?void 0:e.semantic)==null?void 0:d.colors)==null?void 0:f.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(A=e==null?void 0:e.semantic)==null?void 0:A.spacing},typography:{...t.semantic.typography,...(b=e==null?void 0:e.semantic)==null?void 0:b.typography}},components:bd(t.components,e==null?void 0:e.components)};if(r.validate!==!1){let x=Al(n);if(!x.valid)throw new Error(`Theme validation failed: ${x.errors.map(M=>M.message).join(", ")}`)}if(r.plugins)for(let x of r.plugins)n=x.transform(n);return n}function hs(e){var v,A,b,x,M,F,S,I,O,k,U,ue,ie,_,ne,Me,le,Le,de,Y,ce,q,K,Ce,ve,Ge,Ze,ft,We,nt,ke,D,se,te,z,oe,Ie,Z,G,je,Ue,St,jt,zt,J,Pe,ht,yt,Qe,it,Wt,qt,pe,T,Ee,re,be,we,ze,fe,Re,Be,rt,At,_e,Yn,Sn,Xn,An,ur,On,Pn,et,an,fn,en,$n,ln,dt,Yt;let r=fs(e),t={};for(let[X,Wn]of Object.entries(r)){let Fn=X.replace(/\./g,"-");t[`--persona-${Fn}`]=Wn.value}t["--persona-primary"]=(v=t["--persona-semantic-colors-primary"])!=null?v:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(A=t["--persona-semantic-colors-secondary"])!=null?A:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(b=t["--persona-semantic-colors-accent"])!=null?b:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(x=t["--persona-semantic-colors-surface"])!=null?x:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(M=t["--persona-semantic-colors-background"])!=null?M:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(F=t["--persona-semantic-colors-container"])!=null?F:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(S=t["--persona-semantic-colors-text"])!=null?S:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(I=t["--persona-semantic-colors-text-muted"])!=null?I:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(O=t["--persona-semantic-colors-text-inverse"])!=null?O:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(k=t["--persona-semantic-colors-border"])!=null?k: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"]=(ue=t["--persona-components-voice-recording-indicator"])!=null?ue:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(ie=t["--persona-components-voice-recording-background"])!=null?ie:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(_=t["--persona-components-voice-processing-icon"])!=null?_:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(ne=t["--persona-components-voice-speaking-icon"])!=null?ne:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Me=t["--persona-components-approval-requested-background"])!=null?Me:t["--persona-palette-colors-warning-50"],t["--persona-approval-border"]=(le=t["--persona-components-approval-requested-border"])!=null?le:t["--persona-palette-colors-warning-200"],t["--persona-approval-text"]=(Le=t["--persona-components-approval-requested-text"])!=null?Le:t["--persona-palette-colors-gray-900"],t["--persona-approval-approve-bg"]=(de=t["--persona-components-approval-approve-background"])!=null?de:t["--persona-palette-colors-success-500"],t["--persona-approval-deny-bg"]=(Y=t["--persona-components-approval-deny-background"])!=null?Y:t["--persona-palette-colors-error-500"],t["--persona-attachment-image-bg"]=(ce=t["--persona-components-attachment-image-background"])!=null?ce:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(q=t["--persona-components-attachment-image-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(K=t["--persona-semantic-typography-fontFamily"])!=null?K:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(Ce=t["--persona-semantic-typography-fontSize"])!=null?Ce:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(ve=t["--persona-semantic-typography-fontWeight"])!=null?ve:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(Ge=t["--persona-semantic-typography-lineHeight"])!=null?Ge: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"]=(Ze=t["--persona-palette-radius-sm"])!=null?Ze:"0.125rem",t["--persona-radius-md"]=(ft=t["--persona-palette-radius-md"])!=null?ft:"0.375rem",t["--persona-radius-lg"]=(We=t["--persona-palette-radius-lg"])!=null?We:"0.5rem",t["--persona-radius-xl"]=(nt=t["--persona-palette-radius-xl"])!=null?nt:"0.75rem",t["--persona-launcher-radius"]=(D=(ke=t["--persona-components-launcher-borderRadius"])!=null?ke:t["--persona-palette-radius-full"])!=null?D:"9999px",t["--persona-launcher-bg"]=(se=t["--persona-components-launcher-background"])!=null?se:t["--persona-primary"],t["--persona-launcher-fg"]=(te=t["--persona-components-launcher-foreground"])!=null?te:t["--persona-text-inverse"],t["--persona-launcher-border"]=(z=t["--persona-components-launcher-border"])!=null?z:t["--persona-border"],t["--persona-button-primary-bg"]=(oe=t["--persona-components-button-primary-background"])!=null?oe:t["--persona-primary"],t["--persona-button-primary-fg"]=(Ie=t["--persona-components-button-primary-foreground"])!=null?Ie:t["--persona-text-inverse"],t["--persona-button-radius"]=(G=(Z=t["--persona-components-button-primary-borderRadius"])!=null?Z:t["--persona-palette-radius-full"])!=null?G:"9999px",t["--persona-panel-radius"]=(Ue=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?Ue:"0.75rem",t["--persona-panel-border"]=(St=t["--persona-components-panel-border"])!=null?St:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(zt=(jt=t["--persona-components-panel-shadow"])!=null?jt:t["--persona-palette-shadows-xl"])!=null?zt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-input-radius"]=(Pe=(J=t["--persona-components-input-borderRadius"])!=null?J:t["--persona-radius-lg"])!=null?Pe:"0.5rem",t["--persona-message-user-radius"]=(yt=(ht=t["--persona-components-message-user-borderRadius"])!=null?ht:t["--persona-radius-lg"])!=null?yt:"0.5rem",t["--persona-message-assistant-radius"]=(it=(Qe=t["--persona-components-message-assistant-borderRadius"])!=null?Qe:t["--persona-radius-lg"])!=null?it:"0.5rem",t["--persona-header-bg"]=(Wt=t["--persona-components-header-background"])!=null?Wt:t["--persona-surface"],t["--persona-header-border"]=(qt=t["--persona-components-header-border"])!=null?qt:t["--persona-divider"],t["--persona-header-icon-bg"]=(pe=t["--persona-components-header-iconBackground"])!=null?pe:t["--persona-primary"],t["--persona-header-icon-fg"]=(T=t["--persona-components-header-iconForeground"])!=null?T:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Ee=t["--persona-components-header-titleForeground"])!=null?Ee:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(re=t["--persona-components-header-subtitleForeground"])!=null?re:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(be=t["--persona-components-header-actionIconForeground"])!=null?be:t["--persona-muted"];let n=(we=e.components)==null?void 0:we.header;n!=null&&n.shadow&&(t["--persona-header-shadow"]=n.shadow),n!=null&&n.borderBottom&&(t["--persona-header-border-bottom"]=n.borderBottom),t["--persona-input-background"]=(ze=t["--persona-components-input-background"])!=null?ze:t["--persona-surface"],t["--persona-input-placeholder"]=(fe=t["--persona-components-input-placeholder"])!=null?fe:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Re=t["--persona-components-message-user-background"])!=null?Re: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"]=(rt=t["--persona-components-message-user-shadow"])!=null?rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(At=t["--persona-components-message-assistant-background"])!=null?At:t["--persona-surface"],t["--persona-message-assistant-text"]=(_e=t["--persona-components-message-assistant-text"])!=null?_e:t["--persona-text"],t["--persona-message-assistant-border"]=(Yn=t["--persona-components-message-assistant-border"])!=null?Yn:t["--persona-border"],t["--persona-message-assistant-shadow"]=(Sn=t["--persona-components-message-assistant-shadow"])!=null?Sn:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-tool-bubble-shadow"]=(Xn=t["--persona-components-toolBubble-shadow"])!=null?Xn:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(An=t["--persona-components-reasoningBubble-shadow"])!=null?An:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(ur=t["--persona-components-composer-shadow"])!=null?ur:"none",t["--persona-md-inline-code-bg"]=(On=t["--persona-components-markdown-inlineCode-background"])!=null?On:t["--persona-container"],t["--persona-md-inline-code-color"]=(Pn=t["--persona-components-markdown-inlineCode-foreground"])!=null?Pn:t["--persona-text"],t["--persona-md-link-color"]=(an=(et=t["--persona-components-markdown-link-foreground"])!=null?et:t["--persona-accent"])!=null?an:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let o=t["--persona-components-markdown-heading-h1-fontWeight"];o&&(t["--persona-md-h1-weight"]=o);let a=t["--persona-components-markdown-heading-h2-fontSize"];a&&(t["--persona-md-h2-size"]=a);let i=t["--persona-components-markdown-heading-h2-fontWeight"];i&&(t["--persona-md-h2-weight"]=i);let p=t["--persona-components-markdown-prose-fontFamily"];p&&p!=="inherit"&&(t["--persona-md-prose-font-family"]=p);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 d=c==null?void 0:c.labelButton;d&&(d.background&&(t["--persona-label-btn-bg"]=d.background),d.border&&(t["--persona-label-btn-border"]=d.border),d.color&&(t["--persona-label-btn-color"]=d.color),d.padding&&(t["--persona-label-btn-padding"]=d.padding),d.borderRadius&&(t["--persona-label-btn-radius"]=d.borderRadius),d.hoverBackground&&(t["--persona-label-btn-hover-bg"]=d.hoverBackground),d.fontSize&&(t["--persona-label-btn-font-size"]=d.fontSize),d.gap&&(t["--persona-label-btn-gap"]=d.gap));let f=c==null?void 0:c.toggleGroup;f&&(f.gap&&(t["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(t["--persona-toggle-group-radius"]=f.borderRadius));let m=c==null?void 0:c.artifact;if(m!=null&&m.toolbar){let X=m.toolbar;X.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=X.iconHoverColor),X.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=X.iconHoverBackground),X.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=X.iconPadding),X.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=X.iconBorderRadius),X.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=X.iconBorder),X.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=X.toggleGroupGap),X.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=X.toggleBorderRadius),X.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=X.copyBackground),X.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=X.copyBorder),X.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=X.copyColor),X.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=X.copyBorderRadius),X.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=X.copyPadding),X.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=X.copyMenuBackground,t["--persona-dropdown-bg"]=(fn=t["--persona-dropdown-bg"])!=null?fn:X.copyMenuBackground),X.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=X.copyMenuBorder,t["--persona-dropdown-border"]=(en=t["--persona-dropdown-border"])!=null?en:X.copyMenuBorder),X.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=X.copyMenuShadow,t["--persona-dropdown-shadow"]=($n=t["--persona-dropdown-shadow"])!=null?$n:X.copyMenuShadow),X.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=X.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(ln=t["--persona-dropdown-radius"])!=null?ln:X.copyMenuBorderRadius),X.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=X.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(dt=t["--persona-dropdown-item-hover-bg"])!=null?dt:X.copyMenuItemHoverBackground),X.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=X.iconBackground),X.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=X.toolbarBorder)}if(m!=null&&m.tab){let X=m.tab;X.background&&(t["--persona-artifact-tab-bg"]=X.background),X.activeBackground&&(t["--persona-artifact-tab-active-bg"]=X.activeBackground),X.activeBorder&&(t["--persona-artifact-tab-active-border"]=X.activeBorder),X.borderRadius&&(t["--persona-artifact-tab-radius"]=X.borderRadius),X.textColor&&(t["--persona-artifact-tab-color"]=X.textColor),X.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=X.hoverBackground),X.listBackground&&(t["--persona-artifact-tab-list-bg"]=X.listBackground),X.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=X.listBorderColor),X.listPadding&&(t["--persona-artifact-tab-list-padding"]=X.listPadding)}if(m!=null&&m.pane){let X=m.pane;if(X.toolbarBackground){let Wn=(Yt=no(e,X.toolbarBackground))!=null?Yt:X.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Wn}}return t}var xd={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 Tl=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function oo(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];Tl(o)&&Tl(s)?t[n]=oo(o,s):t[n]=s}return t}var vd={colors:{primary:{50:"#ffffff",100:"#f5f5f5",200:"#d4d4d4",300:"#a3a3a3",400:"#737373",500:"#171717",600:"#0f0f0f",700:"#0a0a0a",800:"#050505",900:"#030303",950:"#000000"},secondary:{50:"#f5f3ff",100:"#ede9fe",200:"#ddd6fe",300:"#c4b5fd",400:"#a78bfa",500:"#8b5cf6",600:"#7c3aed",700:"#6d28d9",800:"#5b21b6",900:"#4c1d95",950:"#2e1065"},accent:{50:"#ecfeff",100:"#cffafe",200:"#a5f3fc",300:"#67e8f9",400:"#22d3ee",500:"#06b6d4",600:"#0891b2",700:"#0e7490",800:"#155e75",900:"#164e63",950:"#083344"},gray:{50:"#f9fafb",100:"#f3f4f6",200:"#e5e7eb",300:"#d1d5db",400:"#9ca3af",500:"#6b7280",600:"#4b5563",700:"#374151",800:"#1f2937",900:"#111827",950:"#030712"},success:{50:"#f0fdf4",100:"#dcfce7",200:"#bbf7d0",300:"#86efac",400:"#4ade80",500:"#22c55e",600:"#16a34a",700:"#15803d",800:"#166534",900:"#14532d"},warning:{50:"#fefce8",100:"#fef9c3",200:"#fef08a",300:"#fde047",400:"#facc15",500:"#eab308",600:"#ca8a04",700:"#a16207",800:"#854d0e",900:"#713f12"},error:{50:"#fef2f2",100:"#fee2e2",200:"#fecaca",300:"#fca5a5",400:"#f87171",500:"#ef4444",600:"#dc2626",700:"#b91c1c",800:"#991b1b",900:"#7f1d1d"}}},Ml=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},$o=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Cd=e=>{var t;let r=(t=e==null?void 0:e.colorScheme)!=null?t:"light";return r==="light"?"light":r==="dark"?"dark":$o()},kl=e=>Cd(e),wd=e=>ro(e),Sd=e=>{var t;let r=ro(void 0,{validate:!1});return ro({...e,palette:{...r.palette,colors:{...vd.colors,...(t=e==null?void 0:e.palette)==null?void 0:t.colors}}},{validate:!1})},Fo=e=>{let r=kl(e),t=Ml(e==null?void 0:e.theme),n=Ml(e==null?void 0:e.darkTheme);return r==="dark"?Sd(oo(t!=null?t:{},n!=null?n:{})):wd(t)},Ad=e=>hs(e),dr=(e,r)=>{var o;let t=Fo(r),n=Ad(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)},ys=e=>{let r=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{e($o())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),r.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),n=()=>e($o());t.addEventListener?(t.addEventListener("change",n),r.push(()=>t.removeEventListener("change",n))):t.addListener&&(t.addListener(n),r.push(()=>t.removeListener(n)))}return()=>{r.forEach(t=>t())}};import{Idiomorph as Ed}from"idiomorph";var Ll=(e,r,t={})=>{let{preserveTypingAnimation:n=!0}=t;Ed.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 Il(e,r){var t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,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:"",(p=(i=e.rawContent)==null?void 0:i.length)!=null?p:0,(u=(c=e.llmContent)==null?void 0:c.length)!=null?u:0,(f=(d=e.approval)==null?void 0:d.status)!=null?f:"",(v=(m=e.toolCall)==null?void 0:m.status)!=null?v:"",(x=(b=(A=e.reasoning)==null?void 0:A.chunks)==null?void 0:b.length)!=null?x:0,(F=(M=e.contentParts)==null?void 0:M.length)!=null?F:0,r].join("\0")}function Pl(){return new Map}function Wl(e,r,t){let n=e.get(r);return n&&n.fingerprint===t?n.wrapper:null}function Rl(e,r,t,n){e.set(r,{fingerprint:t,wrapper:n})}function Hl(e,r){for(let t of e.keys())r.has(t)||e.delete(t)}var Gt={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"};var _o={side:"right",width:"420px",animate:!0,reveal:"resize"},_t=e=>{var r,t;return((t=(r=e==null?void 0:e.launcher)==null?void 0:r.mountMode)!=null?t:"floating")==="docked"},Cn=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 wn={"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 so=(e,r)=>{let t=h("button");t.type="button",t.innerHTML=`
8
8
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
9
9
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
10
10
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -12,12 +12,12 @@ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=
12
12
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
13
13
  </span>
14
14
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
15
- `,t.addEventListener("click",r);let n=o=>{var F,S,I,O,k,V,ge,ie,_,ne,Te,le,ke;let a=(F=o.launcher)!=null?F:{},i=zt(o),p=t.querySelector("[data-role='launcher-title']");if(p){let de=(S=a.title)!=null?S:"Chat Assistant";p.textContent=de,p.setAttribute("title",de)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let de=(I=a.subtitle)!=null?I:"Get answers fast";c.textContent=de,c.setAttribute("title",de)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let de=(O=a.agentIconSize)!=null?O:"40px";if(d.style.height=de,d.style.width=de,d.innerHTML="",a.agentIconName){let Y=parseFloat(de)||24,ce=fe(a.agentIconName,Y*.6,"var(--persona-text-inverse, #ffffff)",2);ce?(d.appendChild(ce),d.style.display=""):(d.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(V=a.agentIconText)!=null?V:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let de=(ge=a.agentIconSize)!=null?ge:"40px";f.style.height=de,f.style.width=de,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 de=(ie=a.callToActionIconSize)!=null?ie:"32px";m.style.height=de,m.style.width=de,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 Y=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Y=(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 ce=parseFloat(de)||24,q=Math.max(ce-Y,8),G=fe(a.callToActionIconName,q,"currentColor",2);G?m.appendChild(G):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&yn[a.position]?yn[a.position]:yn["bottom-right"],A="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",b="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?b:`${A} ${v}`;let x="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Te=a.border)!=null?Te:x,t.style.boxShadow=(le=a.shadow)!=null?le:M,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(ke=a.collapsedMaxWidth)!=null?ke:"",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))"},qn=e=>{var ie,_,ne,Te,le,ke,de,Y,ce,q,G,ve,xe,Ke,Xe,mt,Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut;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=(ie=r==null?void 0:r.launcher)!=null?ie:{},o=(_=s.headerIconSize)!=null?_:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Te=s.closeButtonPlacement)!=null?Te:"inline",p=(le=s.headerIconHidden)!=null?le:!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))",!p)if(c){let K=parseFloat(o)||24,Ie=fe(c,K*.6,"currentColor",1);Ie?u.replaceChildren(Ie):u.textContent=(de=(ke=r==null?void 0:r.launcher)==null?void 0:ke.agentIconText)!=null?de:"\u{1F4AC}"}else if((Y=r==null?void 0:r.launcher)!=null&&Y.iconUrl){let K=h("img");K.src=r.launcher.iconUrl,K.alt="",K.className="persona-rounded-xl persona-object-cover",K.style.height=o,K.style.width=o,u.replaceChildren(K)}else u.textContent=(q=(ce=r==null?void 0:r.launcher)==null?void 0:ce.agentIconText)!=null?q:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=bn.titleColor,f.textContent=(ve=(G=r==null?void 0:r.launcher)==null?void 0:G.title)!=null?ve:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=bn.subtitleColor,m.textContent=(Ke=(xe=r==null?void 0:r.launcher)==null?void 0:xe.subtitle)!=null?Ke:"Here to help you get answers fast",d.append(f,m),p?n.append(d):n.append(u,d);let v=(Xe=s.clearChat)!=null?Xe:{},A=(mt=v.enabled)!=null?mt:!0,b=(Be=v.placement)!=null?Be:"inline",x=null,M=null;if(A){let K=(rt=v.size)!=null?rt:"32px",Ie=(Me=v.iconName)!=null?Me:"refresh-cw",ft=(D=v.iconColor)!=null?D:"",yt=(se=v.backgroundColor)!=null?se:"",Ze=(te=v.borderWidth)!=null?te:"",it=(z=v.borderColor)!=null?z:"",Wt=(oe=v.borderRadius)!=null?oe:"",Vt=(Le=v.paddingX)!=null?Le:"",ue=(Z=v.paddingY)!=null?Z:"",T=(J=v.tooltipText)!=null?J:"Clear chat",Ae=(ze=v.showTooltip)!=null?ze:!0;M=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(M.style.right="48px"),x=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"),x.style.height=K,x.style.width=K,x.type="button",x.setAttribute("aria-label",T),x.style.color=ft||bn.actionIconColor;let re=fe(Ie,"20px","currentColor",1);if(re&&x.appendChild(re),yt&&(x.style.backgroundColor=yt,x.classList.remove("hover:persona-bg-gray-100")),Ze||it){let ye=Ze||"0px",Ce=it||"transparent";x.style.border=`${ye} solid ${Ce}`,x.classList.remove("persona-border-none")}if(Wt&&(x.style.borderRadius=Wt,x.classList.remove("persona-rounded-full")),Vt?(x.style.paddingLeft=Vt,x.style.paddingRight=Vt):(x.style.paddingLeft="",x.style.paddingRight=""),ue?(x.style.paddingTop=ue,x.style.paddingBottom=ue):(x.style.paddingTop="",x.style.paddingBottom=""),M.appendChild(x),Ae&&T&&x&&M){let ye=null,Ce=()=>{if(ye||!x)return;let he=x.ownerDocument,Pe=he.body;if(!Pe)return;ye=En(he,"div","persona-clear-chat-tooltip"),ye.textContent=T;let Ne=En(he,"div");Ne.className="persona-clear-chat-tooltip-arrow",ye.appendChild(Ne);let ot=x.getBoundingClientRect();ye.style.position="fixed",ye.style.left=`${ot.left+ot.width/2}px`,ye.style.top=`${ot.top-8}px`,ye.style.transform="translate(-50%, -100%)",Pe.appendChild(ye)},Qe=()=>{ye&&ye.parentNode&&(ye.parentNode.removeChild(ye),ye=null)};M.addEventListener("mouseenter",Ce),M.addEventListener("mouseleave",Qe),x.addEventListener("focus",Ce),x.addEventListener("blur",Qe),M._cleanupTooltip=()=>{Qe(),M&&(M.removeEventListener("mouseenter",Ce),M.removeEventListener("mouseleave",Qe)),x&&(x.removeEventListener("focus",Ce),x.removeEventListener("blur",Qe))}}b==="inline"&&n.appendChild(M)}let F=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":A&&b==="inline"?"":"persona-ml-auto"),S=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");S.style.height=a,S.style.width=a,S.type="button";let I=(Ue=s.closeButtonTooltipText)!=null?Ue:"Close chat",O=(St=s.closeButtonShowTooltip)!=null?St:!0;S.setAttribute("aria-label",I),S.style.display=t?"":"none";let k=(qt=s.closeButtonIconName)!=null?qt:"x",V=(Ut=s.closeButtonIconText)!=null?Ut:"\xD7";S.style.color=s.closeButtonColor||bn.actionIconColor;let ge=fe(k,"20px","currentColor",1);if(ge?S.appendChild(ge):S.textContent=V,s.closeButtonBackgroundColor?(S.style.backgroundColor=s.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let K=s.closeButtonBorderWidth||"0px",Ie=s.closeButtonBorderColor||"transparent";S.style.border=`${K} solid ${Ie}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(S.style.borderRadius=s.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(S.style.paddingLeft=s.closeButtonPaddingX,S.style.paddingRight=s.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),s.closeButtonPaddingY?(S.style.paddingTop=s.closeButtonPaddingY,S.style.paddingBottom=s.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),F.appendChild(S),O&&I){let K=null,Ie=()=>{if(K)return;let yt=S.ownerDocument,Ze=yt.body;if(!Ze)return;K=En(yt,"div","persona-clear-chat-tooltip"),K.textContent=I;let it=En(yt,"div");it.className="persona-clear-chat-tooltip-arrow",K.appendChild(it);let Wt=S.getBoundingClientRect();K.style.position="fixed",K.style.left=`${Wt.left+Wt.width/2}px`,K.style.top=`${Wt.top-8}px`,K.style.transform="translate(-50%, -100%)",Ze.appendChild(K)},ft=()=>{K&&K.parentNode&&(K.parentNode.removeChild(K),K=null)};F.addEventListener("mouseenter",Ie),F.addEventListener("mouseleave",ft),S.addEventListener("focus",Ie),S.addEventListener("blur",ft),F._cleanupTooltip=()=>{ft(),F.removeEventListener("mouseenter",Ie),F.removeEventListener("mouseleave",ft),S.removeEventListener("focus",Ie),S.removeEventListener("blur",ft)}}return i!=="top-right"&&n.appendChild(F),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:S,closeButtonWrapper:F,clearChatButton:x,clearChatButtonWrapper:M}},Ar=(e,r,t)=>{var a,i,p,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(p=n.clearChat)==null?void 0:p.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 lr(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 b=document.createElement("hr");a.appendChild(b)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=fe(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let A=document.createElement("span");A.textContent=m.label,v.appendChild(A),v.addEventListener("click",b=>{b.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function p(){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(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.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 d(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:d,destroy:f}}function vt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,p=h("button","persona-icon-btn"+(o?" "+o:""));p.type="button",p.setAttribute("aria-label",t),p.title=t;let c=fe(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&p.appendChild(c),a&&p.addEventListener("click",a),i)for(let[u,d]of Object.entries(i))p.setAttribute(u,d);return p}function jo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:p}=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=fe(r,o!=null?o:14,"currentColor",2);f&&u.appendChild(f)}let d=h("span");if(d.textContent=t,u.appendChild(d),i&&u.addEventListener("click",i),p)for(let[f,m]of Object.entries(p))u.setAttribute(f,m);return u}function zo(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 p(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let d;u.icon?d=vt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,p(),n(u.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",u.label),d.title=u.label,d.textContent=u.label,d.addEventListener("click",()=>{a=u.id,p(),n(u.id)})),d.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:d}),o.appendChild(d)}function c(u){a=u,p()}return{element:o,setSelected:c}}function bs(e){var m,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:p}=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 d=fe(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),p&&(c.style.borderRadius=(m=p.borderRadius)!=null?m:"10px",c.style.padding=(v=p.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var A,b;c.style.backgroundColor=(A=p.background)!=null?A:"",c.style.borderColor=(b=p.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=lr({items:n,onSelect:A=>{c.setAttribute("aria-expanded","false"),s(A)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",A=>{A.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),c.click())}),{element:c,setLabel:A=>{u.textContent=A,c.setAttribute("aria-label",A)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let A=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Bl=e=>{var n;let r=qn({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 Td(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 p=fe(a.icon,14,"currentColor",2);p&&i.appendChild(p)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let p=h("div","persona-relative");p.appendChild(i);let c=lr({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:p,position:"bottom-left"});p.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(p)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Dl=e=>{var M,F,S,I,O,k,V,ge,ie;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s==null?void 0:s.titleMenu,c,u;if(p)c=bs({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=bn.titleColor,u=(S=c.querySelector(".persona-combo-btn-label"))!=null?S: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=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),Td(c,s==null?void 0:s.trailingActions,(O=s==null?void 0:s.onAction)!=null?O:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Te=>{Te.target.closest("button")||ne()}),c.addEventListener("keydown",Te=>{(Te.key==="Enter"||Te.key===" ")&&(Te.preventDefault(),ne())})}let _=s==null?void 0:s.titleRowHover;_&&(c.style.borderRadius=(k=_.borderRadius)!=null?k:"10px",c.style.padding=(V=_.padding)!=null?V:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var ne,Te;c.style.backgroundColor=(ne=_.background)!=null?ne:"",c.style.borderColor=(Te=_.border)!=null?Te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(ge=a.closeButtonSize)!=null?ge:"32px",f=h("div",""),m=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=d,m.style.width=d,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||bn.actionIconColor;let v=(ie=a.closeButtonIconName)!=null?ie:"x",A=fe(v,"20px","currentColor",2);A?m.appendChild(A):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},xs={default:Bl,minimal:Dl},Nl=e=>{var r;return(r=xs[e])!=null?r:xs.default},ao=(e,r,t)=>{var a,i,p;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 d=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:d,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Nl(n)({config:e,showClose:(p=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?p:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var io=e=>{var Be,rt,Me,D,se,te,z,oe,Le,Z,J,ze,Ue,St,qt,Ut,K,Ie,ft,yt,Ze,it,Wt,Vt,ue,T,Ae;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=(rt=(Be=r==null?void 0:r.copy)==null?void 0:Be.inputPlaceholder)!=null?rt:"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 p=3*20;o.style.maxHeight=`${p}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let re=Math.min(o.scrollHeight,p);o.style.height=`${re}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=(Me=r==null?void 0:r.sendButton)!=null?Me:{},d=(D=u.useIcon)!=null?D:!1,f=(se=u.iconText)!=null?se:"\u2191",m=u.iconName,v=(te=u.tooltipText)!=null?te:"Send message",A=(z=u.showTooltip)!=null?z:!1,b=(oe=u.size)!=null?oe:"40px",x=u.backgroundColor,M=u.textColor,F=h("div","persona-send-button-wrapper"),S=h("button",d?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(S.type="submit",S.setAttribute("data-persona-composer-submit",""),d){if(S.style.width=b,S.style.height=b,S.style.minWidth=b,S.style.minHeight=b,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",m){let re=parseFloat(b)||24,ye=M&&typeof M=="string"&&M.trim()?M.trim():"currentColor",Ce=fe(m,re,ye,2);Ce?(S.appendChild(Ce),S.style.color=ye):(S.textContent=f,M?S.style.color=M:S.classList.add("persona-text-white"))}else S.textContent=f,M?S.style.color=M:S.classList.add("persona-text-white");x?S.style.backgroundColor=x:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Z=(Le=r==null?void 0:r.copy)==null?void 0:Le.sendButtonLabel)!=null?Z:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(u.borderWidth&&(S.style.borderWidth=u.borderWidth,S.style.borderStyle="solid"),u.borderColor&&(S.style.borderColor=u.borderColor),u.paddingX?(S.style.paddingLeft=u.paddingX,S.style.paddingRight=u.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),u.paddingY?(S.style.paddingTop=u.paddingY,S.style.paddingBottom=u.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),A&&v){let re=h("div","persona-send-button-tooltip");re.textContent=v,F.appendChild(re)}F.appendChild(S);let I=(J=r==null?void 0:r.voiceRecognition)!=null?J:{},O=I.enabled===!0,k=null,V=null,ge=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ie=((ze=I.provider)==null?void 0:ze.type)==="runtype";if(O&&(ge||ie)){V=h("div","persona-send-button-wrapper"),k=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),k.type="button",k.setAttribute("data-persona-composer-mic",""),k.setAttribute("aria-label","Start voice recognition");let re=(Ue=I.iconName)!=null?Ue:"mic",ye=(St=I.iconSize)!=null?St:b,Ce=parseFloat(ye)||24,Qe=(qt=I.backgroundColor)!=null?qt:x,he=(Ut=I.iconColor)!=null?Ut:M;k.style.width=ye,k.style.height=ye,k.style.minWidth=ye,k.style.minHeight=ye,k.style.fontSize="18px",k.style.lineHeight="1";let Pe=he||"currentColor",Ne=fe(re,Ce,Pe,1.5);Ne?(k.appendChild(Ne),k.style.color=Pe):(k.textContent="\u{1F3A4}",k.style.color=Pe),Qe?k.style.backgroundColor=Qe:k.classList.add("persona-bg-persona-primary"),he?k.style.color=he:!he&&!M&&k.classList.add("persona-text-white"),I.borderWidth&&(k.style.borderWidth=I.borderWidth,k.style.borderStyle="solid"),I.borderColor&&(k.style.borderColor=I.borderColor),I.paddingX&&(k.style.paddingLeft=I.paddingX,k.style.paddingRight=I.paddingX),I.paddingY&&(k.style.paddingTop=I.paddingY,k.style.paddingBottom=I.paddingY),V.appendChild(k);let ot=(K=I.tooltipText)!=null?K:"Start voice recognition";if(((Ie=I.showTooltip)!=null?Ie:!1)&&ot){let Oe=h("div","persona-send-button-tooltip");Oe.textContent=ot,V.appendChild(Oe)}}let ne=(ft=r==null?void 0:r.attachments)!=null?ft:{},Te=ne.enabled===!0,le=null,ke=null,de=null,Y=null;if(Te){Y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Y.style.display="none",de=h("input"),de.type="file",de.accept=((yt=ne.allowedTypes)!=null?yt:Hn).join(","),de.multiple=((Ze=ne.maxFiles)!=null?Ze:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),ke=h("div","persona-send-button-wrapper"),le=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(it=ne.buttonTooltipText)!=null?it:"Attach file");let re=(Wt=ne.buttonIconName)!=null?Wt:"paperclip",ye=b,Ce=parseFloat(ye)||40,Qe=Math.round(Ce*.6);le.style.width=ye,le.style.height=ye,le.style.minWidth=ye,le.style.minHeight=ye,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let he=fe(re,Qe,"currentColor",1.5);he?le.appendChild(he):le.textContent="\u{1F4CE}",le.addEventListener("click",ot=>{ot.preventDefault(),de==null||de.click()}),ke.appendChild(le);let Pe=(Vt=ne.buttonTooltipText)!=null?Vt:"Attach file",Ne=h("div","persona-send-button-tooltip");Ne.textContent=Pe,ke.appendChild(Ne)}s.addEventListener("click",re=>{re.target!==S&&re.target!==F&&re.target!==k&&re.target!==V&&re.target!==le&&re.target!==ke&&o.focus()}),Y&&(Y.style.gap="8px",s.append(Y)),de&&s.append(de),s.append(o);let ce=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),q=h("div","persona-flex persona-items-center persona-gap-2");ke&&q.append(ke);let G=h("div","persona-flex persona-items-center persona-gap-1");V&&G.append(V),G.append(F),ce.append(q,G),s.append(ce);let ve=(ue=r==null?void 0:r.statusIndicator)!=null?ue:{},xe=ve.align==="left"?"persona-text-left":ve.align==="center"?"persona-text-center":"persona-text-right",Ke=h("div",`persona-mt-2 ${xe} persona-text-xs persona-text-persona-muted`);Ke.setAttribute("data-persona-composer-status","");let Xe=(T=ve.visible)!=null?T:!0;Ke.style.display=Xe?"":"none";let mt=(Ae=ve.idleText)!=null?Ae:"Online";if(ve.idleLink){let re=h("a");re.href=ve.idleLink,re.target="_blank",re.rel="noopener noreferrer",re.textContent=mt,re.style.color="inherit",re.style.textDecoration="none",Ke.appendChild(re)}else Ke.textContent=mt;return t.append(n,s,Ke),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:S,sendButtonWrapper:F,micButton:k,micButtonWrapper:V,statusText:Ke,attachmentButton:le,attachmentButtonWrapper:ke,attachmentInput:de,attachmentPreviewsContainer:Y,actionsRow:ce,leftActions:q,rightActions:G}};var Ol=e=>{var c,u,d,f,m,v,A;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(zt(e)){let b=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 b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=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"),M=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return b.style.width=M,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}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=(A=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?A:e==null?void 0:e.launcherWidth,p=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=p,a.style.maxWidth=p,o.appendChild(a),{wrapper:o,panel:a}},$l=(e,r=!0)=>{var b,x,M,F,S,I,O,k,V;let t=h("div","persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-bg-persona-surface persona-text-persona-primary persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border");t.setAttribute("data-persona-theme-zone","container");let n=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?ao(e,n,{showClose:r}):qn({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",p=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(F=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?F:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(I=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",p.append(c,u);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),p.setAttribute("data-persona-intro-card",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(p.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(p,d);let v=io({config:e}),A=((V=e==null?void 0:e.layout)==null?void 0:V.showFooter)!==!1;return s?Ar(t,o,e):(o.header.style.display="none",Ar(t,o,e)),t.append(a),A||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle: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:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var Md=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},kd=320,Ld=320,Id=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Pd=(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,p)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${kd}px`,c.style.maxHeight=`${Ld}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}),Md(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}},Er=()=>{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},_l=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Er};if(r){let s=r(n);if(s!==null)return s}return Er()},Wd=(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},Fl=(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},Rd=(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},jl=(e,r,t)=>{var m,v,A,b,x,M;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(A=r.showDownvote)!=null?A:!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=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",p=(M=r.layout)!=null?M:"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"}[p],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(F,S,I)=>{let O=vt({icon:F,label:S,size:14,className:"persona-message-action-btn"});return O.setAttribute("data-action",I),O};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},lo=(e,r,t,n,s,o)=>{var ie,_,ne,Te,le,ke,de;let a=t!=null?t:{},i=(ie=a.layout)!=null?ie:"bubble",p=a.avatar,c=a.timestamp,u=(_=p==null?void 0:p.show)!=null?_:!1,d=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Te=p==null?void 0:p.position)!=null?Te:"left",m=(le=c==null?void 0:c.position)!=null?le:"below",v=Rd(e.role,i),A=h("div",v.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Id(e),x=(de=(ke=e.content)==null?void 0:ke.trim())!=null?de:"",F=b.length>0&&x===Ro,S=document.createElement("div");S.classList.add("persona-message-content");let I=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=null;if(F?(O=document.createElement("div"),O.innerHTML=I,O.style.display="none",S.appendChild(O)):S.innerHTML=I,d&&m==="inline"&&e.createdAt){let Y=Fl(e,c);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(b.length>0){let Y=Pd(b,!F&&!!x,()=>{F&&O&&(O.style.display="")});Y?A.appendChild(Y):F&&O&&(O.style.display="")}if(A.appendChild(S),d&&m==="below"&&e.createdAt){let Y=Fl(e,c);Y.classList.add("persona-mt-1"),A.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=_l("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Y&&A.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Y=jl(e,n,s);A.appendChild(Y)}if(!u||e.role==="system")return A;let V=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ge=Wd(p,e.role);return f==="right"||f==="left"&&e.role==="user"?V.append(A,ge):V.append(ge,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),V},Hd=(e,r,t,n,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):lo(e,r,t,n,s,o)};var Tr=new Set,zl=(e,r)=>{let t=Tr.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 p=fe(t?"chevron-up":"chevron-down",16,"currentColor",2);p?a.appendChild(p):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},vs=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=Tr.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=fl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let p=h("div","persona-flex persona-items-center"),u=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);u?p.appendChild(u):p.textContent=n?"Hide":"Show";let d=h("div","persona-flex persona-items-center persona-ml-auto");d.append(p),s.append(o,d);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),p.innerHTML="";let x=fe(n?"chevron-up":"chevron-down",16,"currentColor",2);x?p.appendChild(x):p.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Mr=new Set,ql=(e,r,t)=>{var c;let n=Mr.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"),p=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",d=fe(n?"chevron-up":"chevron-down",16,u,2);d?p.appendChild(d):p.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},Cs=(e,r)=>{var A;let t=e.toolCall,n=(A=r==null?void 0:r.toolCall)!=null?A:{},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=Mr.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"),p=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(p.style.color=n.headerTextColor),p.textContent=hl(t),i.appendChild(p);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",d=fe(o?"chevron-up":"chevron-down",16,u,2);d?c.appendChild(d):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Zr(t.args),b.append(x,M),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=t.chunks.join(`
16
- `),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Zr(t.result),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",x=fe(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var ws=(e,r)=>{var A,b,x,M,F,S,I,O,k,V,ge,ie;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=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=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=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=fe(p,20,c,2);u&&i.appendChild(u);let d=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=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(m),!s){let _=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",t.status),t.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):t.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):t.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),f.appendChild(_)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let _=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(_.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(_.style.color=n.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=Zr(t.parameters),d.appendChild(_)}if(s){let _=h("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let ne=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ne.type="button",ne.style.backgroundColor=(F=n==null?void 0:n.approveButtonColor)!=null?F:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(S=n==null?void 0:n.approveButtonTextColor)!=null?S:"#ffffff",ne.setAttribute("data-approval-action","approve");let Te=fe("shield-check",14,(I=n==null?void 0:n.approveButtonTextColor)!=null?I:"#ffffff",2);Te&&(Te.style.marginRight="4px",ne.appendChild(Te));let le=document.createTextNode((O=n==null?void 0:n.approveLabel)!=null?O:"Approve");ne.appendChild(le);let ke=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");ke.type="button",ke.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",ke.style.color=(V=n==null?void 0:n.denyButtonTextColor)!=null?V:"var(--persona-feedback-error, #dc2626)",ke.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,ke.setAttribute("data-approval-action","deny");let de=fe("shield-x",14,(ge=n==null?void 0:n.denyButtonTextColor)!=null?ge:"var(--persona-feedback-error, #dc2626)",2);de&&(de.style.marginRight="4px",ke.appendChild(de));let Y=document.createTextNode((ie=n==null?void 0:n.denyLabel)!=null?ie:"Deny");ke.appendChild(Y),_.append(ne,ke),d.appendChild(_)}return a.append(i,d),o.appendChild(a),o};var Ul=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(),d=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-muted hover:persona-opacity-90 persona-cursor-pointer persona-border persona-border-gray-200");v.type="button",v.textContent=m,v.disabled=d,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),r.push(v)}),e.appendChild(u)}}};var co=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 po=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 kr(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Bd={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)"}},Dd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Nd=["flowName","stepName","reasoningText","text","name","tool","toolName"],Od=100;function $d(e,r){let t={...Bd,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Dd}function Fd(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function _d(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 jd(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 zd(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 qd(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 Ud(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]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=n,i.appendChild(p),i}}function Ss(e,r,t,n,s,o,a,i){var f;let p=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");kr(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:()=>d(),isExpanded:p,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(d()),c;function d(){var ne,Te;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let A=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=fe(p?"chevron-down":"chevron-right","14px","currentColor",2);b&&A.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";x.textContent=M==="relative"?Fd(e.timestamp,t):_d(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 S=$d(e.type,n.badgeColors),I=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");I.style.backgroundColor=S.bg,I.style.color=S.text,I.style.borderColor=S.text+"50",I.textContent=e.type;let O=(Te=n.descriptionFields)!=null?Te:Nd,k=jd(e.payload,O),V=null;k&&(V=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),V.textContent=k);let ge=h("div","persona-flex-1 persona-min-w-0"),ie=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"),_=fe("clipboard","12px","currentColor",1.5);return _&&ie.appendChild(_),ie.addEventListener("click",async le=>{le.stopPropagation(),await zd(qd(e)),ie.innerHTML="";let ke=fe("check","12px","currentColor",1.5);ke&&ie.appendChild(ke),setTimeout(()=>{ie.innerHTML="";let de=fe("clipboard","12px","currentColor",1.5);de&&ie.appendChild(de)},1500)}),v.appendChild(A),v.appendChild(x),F&&v.appendChild(F),v.appendChild(I),V&&v.appendChild(V),v.appendChild(ge),v.appendChild(ie),m.appendChild(v),p&&m.appendChild(Ud(e,a,i)),m}}function Vl(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(d=>d.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let d=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>p().element,onClose:n});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return p();function p(){let d=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");kr(f,d==null?void 0:d.panel);let m=[],v="",A="",b=null,x=[],M={},F=0,S=!1,I=0,O=0,k=!1,V=null,ge=!1,ie=0,_=new Set,ne=new Map,Te="",le="",ke=null,de,Y,ce,q,G;function ve(){let ue=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),T=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");kr(T,d==null?void 0:d.headerBar);let Ae=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ae.textContent="Events",de=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"),de.textContent="0";let re=h("div","persona-flex-1");Y=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 ye=h("option","");ye.value="",ye.textContent="All events",Y.appendChild(ye),ce=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"),ce.type="button",ce.title="Copy All";let Qe=fe("clipboard-copy","12px","currentColor",1.5);Qe&&ce.appendChild(Qe);let he=h("span","persona-text-xs");he.textContent="Copy All",ce.appendChild(he),T.appendChild(Ae),T.appendChild(de),T.appendChild(re),T.appendChild(Y),T.appendChild(ce);let Pe=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");kr(Pe,d==null?void 0:d.searchBar);let Ne=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),ot=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");Ne&&ot.appendChild(Ne),q=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"),kr(q,d==null?void 0:d.searchInput),q.type="text",q.placeholder="Search event payloads...",G=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"),G.type="button",G.style.display="none";let At=fe("x","12px","currentColor",2);return At&&G.appendChild(At),Pe.appendChild(ot),Pe.appendChild(q),Pe.appendChild(G),ue.appendChild(T),ue.appendChild(Pe),ue}let xe,Ke=o.find(ue=>ue.renderEventStreamToolbar);if(Ke!=null&&Ke.renderEventStreamToolbar&&s){let ue=Ke.renderEventStreamToolbar({config:s,defaultRenderer:()=>ve(),eventCount:r.getSize(),filteredCount:0,onFilterChange:T=>{v=T,Le(),ze()},onSearchChange:T=>{A=T,Le(),ze()}});xe=ue!=null?ue:ve()}else xe=ve();let Xe=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");Xe.style.display="none";let mt=h("div","persona-flex-1 persona-min-h-0 persona-relative"),Be=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");Be.style.height="100%";let rt=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");kr(rt,d==null?void 0:d.scrollIndicator),rt.style.display="none";let Me=fe("arrow-down","12px","currentColor",2);Me&&rt.appendChild(Me);let D=h("span","");rt.appendChild(D);let se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");se.style.display="none",mt.appendChild(Be),mt.appendChild(se),mt.appendChild(rt),f.setAttribute("tabindex","0"),f.appendChild(xe),f.appendChild(Xe),f.appendChild(mt);function te(){let ue=r.getAll(),T={};for(let he of ue)T[he.type]=(T[he.type]||0)+1;let Ae=Object.keys(T).sort(),re=Ae.length!==x.length||!Ae.every((he,Pe)=>he===x[Pe]),ye=!re&&Ae.some(he=>T[he]!==M[he]),Ce=ue.length!==Object.values(M).reduce((he,Pe)=>he+Pe,0);if(!re&&!ye&&!Ce||(x=Ae,M=T,!Y))return;let Qe=Y.value;if(Y.options[0].textContent="All events",re){for(;Y.options.length>1;)Y.remove(1);for(let he of Ae){let Pe=h("option","");Pe.value=he,Pe.textContent=`${he} (${T[he]||0})`,Y.appendChild(Pe)}Qe&&Ae.includes(Qe)?Y.value=Qe:Qe&&(Y.value="",v="")}else for(let he=1;he<Y.options.length;he++){let Pe=Y.options[he];Pe.textContent=`${Pe.value} (${T[Pe.value]||0})`}}function z(){let ue=r.getAll();if(v&&(ue=ue.filter(T=>T.type===v)),A){let T=A.toLowerCase();ue=ue.filter(Ae=>Ae.type.toLowerCase().includes(T)||Ae.payload.toLowerCase().includes(T))}return ue}function oe(){return v!==""||A!==""}function Le(){F=0,I=0,S=!1,rt.style.display="none"}function Z(ue){_.has(ue)?_.delete(ue):_.add(ue),ke=ue;let T=Be.scrollTop,Ae=S;ge=!0,S=!0,ze(),Be.scrollTop=T,S=Ae,ge=!1}function J(){return Be.scrollHeight-Be.scrollTop-Be.clientHeight<=50}function ze(){O=Date.now(),k=!1,te();let ue=r.getEvictedCount();ue>0?(Xe.textContent=`${ue.toLocaleString()} older events truncated`,Xe.style.display=""):Xe.style.display="none",m=z();let T=m.length,Ae=r.getSize()>0;de&&(de.textContent=String(r.getSize())),T===0&&Ae&&oe()?(se.textContent=A?`No events matching '${A}'`:"No events matching filter",se.style.display="",Be.style.display="none"):(se.style.display="none",Be.style.display=""),ce&&(ce.title=oe()?`Copy Filtered (${T})`:"Copy All"),S&&T>F&&(I+=T-F,D.textContent=`${I} new event${I===1?"":"s"}`,rt.style.display=""),F=T;let re=r.getAll(),ye=re.length>0?re[0].timestamp:0,Ce=new Set(m.map(Pe=>Pe.id));for(let Pe of _)Ce.has(Pe)||_.delete(Pe);let Qe=v!==Te||A!==le,he=ne.size===0&&m.length>0;if(Qe||he||m.length===0){Be.innerHTML="",ne.clear();let Pe=document.createDocumentFragment();for(let Ne=0;Ne<m.length;Ne++){let ot=Ss(m[Ne],Ne,ye,a,_,Z,o,s);ne.set(m[Ne].id,ot),Pe.appendChild(ot)}Be.appendChild(Pe),Te=v,le=A,ke=null}else{if(ke!==null){let Ne=ne.get(ke);if(Ne&&Ne.parentNode===Be){let ot=m.findIndex(At=>At.id===ke);if(ot>=0){let At=Ss(m[ot],ot,ye,a,_,Z,o,s);Be.insertBefore(At,Ne),Ne.remove(),ne.set(ke,At)}}ke=null}let Pe=new Set(m.map(Ne=>Ne.id));for(let[Ne,ot]of ne)Pe.has(Ne)||(ot.remove(),ne.delete(Ne));for(let Ne=0;Ne<m.length;Ne++){let ot=m[Ne];if(!ne.has(ot.id)){let At=Ss(ot,Ne,ye,a,_,Z,o,s);ne.set(ot.id,At),Be.appendChild(At)}}}S||(Be.scrollTop=Be.scrollHeight)}function Ue(){if(Date.now()-O>=Od){V!==null&&(cancelAnimationFrame(V),V=null),ze();return}k||(k=!0,V=requestAnimationFrame(()=>{V=null,ze()}))}let St=(ue,T)=>{if(!ce)return;ce.innerHTML="";let Ae=fe(ue,"12px","currentColor",1.5);Ae&&ce.appendChild(Ae);let re=h("span","persona-text-xs");re.textContent="Copy All",ce.appendChild(re),setTimeout(()=>{ce.innerHTML="";let ye=fe("clipboard-copy","12px","currentColor",1.5);ye&&ce.appendChild(ye);let Ce=h("span","persona-text-xs");Ce.textContent="Copy All",ce.appendChild(Ce),ce.disabled=!1},T)},qt=async()=>{if(ce){ce.disabled=!0;try{let ue;oe()?ue=m:t?(ue=await t(),ue.length===0&&(ue=r.getAll())):ue=r.getAll();let T=ue.map(Ae=>{try{return JSON.parse(Ae.payload)}catch{return Ae.payload}});await navigator.clipboard.writeText(JSON.stringify(T,null,2)),St("check",1500)}catch{St("x",1500)}}},Ut=()=>{Y&&(v=Y.value,Le(),ze())},K=()=>{!q||!G||(G.style.display=q.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{A=q.value,Le(),ze()},150))},Ie=()=>{!q||!G||(q.value="",A="",G.style.display="none",b&&clearTimeout(b),Le(),ze())},ft=()=>{if(ge)return;let ue=Be.scrollTop,T=ue>ie;ie=ue,J()&&T?(S=!1,I=0,rt.style.display="none"):J()||(S=!0)},yt=ue=>{ue.deltaY<0&&(S=!0)},Ze=()=>{Be.scrollTop=Be.scrollHeight,S=!1,I=0,rt.style.display="none"},it=ue=>{let T=ue.target;if(!T||T.closest("button"))return;let Ae=T.closest("[data-event-id]");if(!Ae)return;let re=Ae.getAttribute("data-event-id");re&&Z(re)},Wt=ue=>{if((ue.metaKey||ue.ctrlKey)&&ue.key==="f"){ue.preventDefault(),q==null||q.focus(),q==null||q.select();return}ue.key==="Escape"&&(q&&document.activeElement===q?(Ie(),q.blur(),f.focus()):n&&n())};ce&&ce.addEventListener("click",qt),Y&&Y.addEventListener("change",Ut),q&&q.addEventListener("input",K),G&&G.addEventListener("click",Ie),Be.addEventListener("scroll",ft),Be.addEventListener("wheel",yt,{passive:!0}),Be.addEventListener("click",it),rt.addEventListener("click",Ze),f.addEventListener("keydown",Wt);function Vt(){b&&clearTimeout(b),V!==null&&(cancelAnimationFrame(V),V=null),k=!1,ne.clear(),ce&&ce.removeEventListener("click",qt),Y&&Y.removeEventListener("change",Ut),q&&q.removeEventListener("input",K),G&&G.removeEventListener("click",Ie),Be.removeEventListener("scroll",ft),Be.removeEventListener("wheel",yt),Be.removeEventListener("click",it),rt.removeEventListener("click",Ze),f.removeEventListener("keydown",Wt)}return{element:f,update:Ue,destroy:Vt}}}function Jl(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 p=document.createElement("div");p.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-muted, #9ca3af)",p.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #3b82f6)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",d.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(m)}else d.textContent=a;if(c.append(u,d),i.append(p,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 Kl=(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:"",p=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:p},config:r.config,defaultRenderer:()=>Jl(e,r)});if(u)return u}return Jl(e,r)};var As=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)})}},Un=new As;Un.register("PersonaArtifactCard",Kl);function Vd(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 Gl(e,r){var mt,Be,rt,Me;let t=(Be=(mt=e.features)==null?void 0:mt.artifacts)==null?void 0:Be.layout,s=((rt=t==null?void 0:t.toolbarPreset)!=null?rt:"default")==="document",o=(Me=t==null?void 0:t.panePadding)==null?void 0:Me.trim(),a=e.markdown?xr(e.markdown):null,i=Xr(e.sanitize),p=D=>{let se=a?a(D):Yr(D);return i?i(se):se},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"),d.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};c&&c.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let d=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let A="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vt({icon:"eye",label:"Rendered view"}),M=s?vt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vt({icon:"code-2",label:"Source"}),F=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),S=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,I=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,O=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(I&&O&&O.length>0),V=null,ge,ie=null,_=null;if(s&&(S||I)&&!k){if(ge=S?jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let D=fe("chevron-down",14,"currentColor",2);D&&ge.appendChild(D)}}else s&&k?(V=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ge=S?jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ie=vt({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"}}),V.append(ge,ie)):s?ge=vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ge=vt({icon:"copy",label:"Copy"});let ne=s?vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vt({icon:"refresh-cw",label:"Refresh"}),Te=s?vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vt({icon:"x",label:"Close"}),le=()=>{var oe,Le,Z;let D=(oe=G.find(J=>J.id===ve))!=null?oe:G[G.length-1],se=(Le=D==null?void 0:D.id)!=null?Le:null,te=(D==null?void 0:D.artifactType)==="markdown"&&(Z=D.markdown)!=null?Z:"",z=D?JSON.stringify({component:D.component,props:D.props},null,2):"";return{markdown:te,jsonPayload:z,id:se}},ke=async()=>{var oe;let{markdown:D,jsonPayload:se}=le(),te=(oe=G.find(Le=>Le.id===ve))!=null?oe:G[G.length-1],z=(te==null?void 0:te.artifactType)==="markdown"?D:te?se:"";try{await navigator.clipboard.writeText(z)}catch{}};if(ge.addEventListener("click",async()=>{let D=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(D&&k){let{markdown:se,jsonPayload:te,id:z}=le();try{await D({actionId:"primary",artifactId:z,markdown:se,jsonPayload:te})}catch{}return}await ke()}),ie&&(O!=null&&O.length)){let D=()=>{var te;return(te=d.closest("[data-persona-root]"))!=null?te:document.body},se=()=>{_=lr({items:O.map(te=>({id:te.id,label:te.label})),onSelect:async te=>{let{markdown:z,jsonPayload:oe,id:Le}=le(),Z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Z?await Z({actionId:te,artifactId:Le,markdown:z,jsonPayload:oe}):te==="markdown"||te==="md"?await navigator.clipboard.writeText(z):te==="json"||te==="source"?await navigator.clipboard.writeText(oe):await navigator.clipboard.writeText(z||oe)}catch{}},anchor:V!=null?V:ie,position:"bottom-right",portal:D()})};d.isConnected?se():requestAnimationFrame(se),ie.addEventListener("click",te=>{te.stopPropagation(),_==null||_.toggle()})}ne.addEventListener("click",async()=>{var D;try{await((D=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:D.call(t))}catch{}Ke()}),Te.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let de=()=>{s&&(x.setAttribute("aria-pressed",A==="rendered"?"true":"false"),M.setAttribute("aria-pressed",A==="source"?"true":"false"))};x.addEventListener("click",()=>{A="rendered",de(),Ke()}),M.addEventListener("click",()=>{A="source",de(),Ke()});let Y=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),b.append(x,M),V?F.append(V,ne,Te):F.append(ge,ne,Te),f.append(b,Y,F),de()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ce=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"),q=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ce.style.paddingLeft=o,ce.style.paddingRight=o,q.style.padding=o),d.appendChild(f),d.appendChild(ce),d.appendChild(q);let G=[],ve=null,xe=!1,Ke=()=>{var z,oe,Le,Z;let D=s&&G.length<=1;ce.classList.toggle("persona-hidden",D),ce.replaceChildren();for(let J of G){let ze=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");ze.type="button",ze.textContent=J.title||J.id.slice(0,8),J.id===ve&&ze.classList.add("persona-bg-persona-container","persona-border-persona-border"),ze.addEventListener("click",()=>r.onSelect(J.id)),ce.appendChild(ze)}q.replaceChildren();let se=ve&&G.find(J=>J.id===ve)||G[G.length-1];if(!se)return;if(s){let J=se.artifactType==="markdown"?"MD":(z=se.component)!=null?z:"Component",Ue=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Y.textContent=`${Ue} \xB7 ${J}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(s&&A==="source"){let ze=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");ze.textContent=(oe=se.markdown)!=null?oe:"",q.appendChild(ze);return}let J=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");J.innerHTML=p((Le=se.markdown)!=null?Le:""),q.appendChild(J);return}let te=se.component?Un.get(se.component):void 0;if(te){let ze={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Ue=te((Z=se.props)!=null?Z:{},ze);if(Ue){q.appendChild(Ue);return}}catch{}}q.appendChild(Vd(se))},Xe=()=>{var se;let D=G.length>0;if(d.classList.toggle("persona-hidden",!D),c){let te=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,oe=((se=te==null?void 0:te.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;D&&oe&&xe?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(D){var se,te,z;G=D.artifacts,ve=(z=(te=D.selectedId)!=null?te:(se=D.artifacts[D.artifacts.length-1])==null?void 0:se.id)!=null?z:null,G.length>0&&(xe=!0),Ke(),Xe()},setMobileOpen(D){xe=D,!D&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):Xe()}}}function un(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 Yl(e,r){var o,a,i,p;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"),!un(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=(p=t==null?void 0:t.paneBorderLeft)==null?void 0:p.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 Jd(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 qo(e,r){var p,c,u,d,f,m,v,A,b,x;if(!un(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"),Jd(e),Yl(e,r);return}let t=(c=(p=r.features)==null?void 0:p.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",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(A=t==null?void 0:t.documentToolbarIconColor)==null?void 0:A.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(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"),Yl(e,r)}var Xl=["panel","seamless"];function Uo(e,r){var i,p,c,u,d,f;for(let m of Xl)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"),!un(r))return;let t=(p=(i=r.features)==null?void 0:i.artifacts)==null?void 0:p.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Xl.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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Zl(e,r){var t,n,s;return!r||!un(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Kd(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 Gd(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 Yd(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Xd(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Ql(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 ec(e,r,t,n,s,o){let a=Kd(s,200),i=Xd(r,t,n,200);i=Math.max(a,i);let p=Gd(o);return p!==null&&(i=Math.min(i,p)),Yd(e,a,i)}var tc={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"}},Es=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,A,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(A=tc[a])!=null?A:tc.init;o.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,p.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,p.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var O,k;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${x.name}`;let F=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=x.label,M.appendChild(F);let S=(O=x.type)!=null?O:"text",I;S==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=S),I.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",I.id=`${r.id}-${a}-${x.name}`,I.name=x.name,I.placeholder=(k=x.placeholder)!=null?k:"",x.required&&(I.required=!0),M.appendChild(I),u.appendChild(M)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(b=i.submitLabel)!=null?b:"Submit",d.appendChild(f),d.appendChild(m),u.appendChild(d),o.replaceChildren(p,u),u.addEventListener("submit",async x=>{var I,O;x.preventDefault();let M=(I=t.formEndpoint)!=null?I:"/form",F=new FormData(u),S={};F.forEach((k,V)=>{S[V]=k}),S.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let V=await k.json();f.textContent=(O=V.message)!=null?O:"Thanks! We'll be in touch soon.",V.success&&V.nextPrompt&&await n.sendMessage(String(V.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ts=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,p;return((i=a.priority)!=null?i:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Vo=new Ts;var Ct={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 nc(e,r){if(!(!e&&!r))return e?r?oo(e,r):e:r}function Ms(e){var r,t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,F,S,I;return e?{...Ct,...e,theme:nc(Ct.theme,e.theme),darkTheme:nc(Ct.darkTheme,e.darkTheme),launcher:{...Ct.launcher,...e.launcher,dock:{...(r=Ct.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Ct.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ct.copy,...e.copy},sendButton:{...Ct.sendButton,...e.sendButton},statusIndicator:{...Ct.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ct.voiceRecognition,...e.voiceRecognition},features:(()=>{var ge,ie;let O=(ge=Ct.features)==null?void 0:ge.artifacts,k=(ie=e.features)==null?void 0:ie.artifacts,V=O===void 0&&k===void 0?void 0:{...O,...k,layout:{...O==null?void 0:O.layout,...k==null?void 0:k.layout}};return{...Ct.features,...e.features,...V!==void 0?{artifacts:V}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ct.suggestionChips,suggestionChipsConfig:{...Ct.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ct.layout,...e.layout,header:{...(a=Ct.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(p=Ct.layout)==null?void 0:p.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(u=Ct.layout)==null?void 0:u.messages)==null?void 0:d.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(A=(v=Ct.layout)==null?void 0:v.messages)==null?void 0:A.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(M=Ct.layout)==null?void 0:M.slots,...(F=e.layout)==null?void 0:F.slots}},markdown:{...Ct.markdown,...e.markdown,options:{...(S=Ct.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Ct.messageActions,...e.messageActions}}:Ct}var rc=()=>{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(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var Zd=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Qd=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},Jo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Zd(e),t=Qd(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}},ks=e=>typeof e=="string"?e:e==null?"":String(e),Lr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ks(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ks(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:ks(t.text)}}},oc=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ko=e=>{let r=new Set(oc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(oc(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 p={action:i,message:o.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",p)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var ep=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}},tp=e=>e.map(r=>({...r,streaming:!1})),Ls=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?ep(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?tp(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 np,STR as rp,OBJ as op}from"partial-json";function sp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function ap(e,r){if(!sp(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 Is(){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=np(t,rp|op),o=ap(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function ip(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ps(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Un.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 lp(){let e=Is();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ws(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 Rs(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 cp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hs(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:p=!0,ratingLabels:c=cp}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,m.appendChild(A),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let O=1;O<=5;O++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${c[O-1]}`),k.title=c[O-1],k.dataset.rating=String(O),k.innerHTML=`
15
+ `,t.addEventListener("click",r);let n=o=>{var F,S,I,O,k,U,ue,ie,_,ne,Me,le,Le;let a=(F=o.launcher)!=null?F:{},i=_t(o),p=t.querySelector("[data-role='launcher-title']");if(p){let de=(S=a.title)!=null?S:"Chat Assistant";p.textContent=de,p.setAttribute("title",de)}let c=t.querySelector("[data-role='launcher-subtitle']");if(c){let de=(I=a.subtitle)!=null?I:"Get answers fast";c.textContent=de,c.setAttribute("title",de)}let u=t.querySelector(".persona-flex-col");u&&(a.textHidden||i?u.style.display="none":u.style.display="");let d=t.querySelector("[data-role='launcher-icon']");if(d)if(a.agentIconHidden)d.style.display="none";else{let de=(O=a.agentIconSize)!=null?O:"40px";if(d.style.height=de,d.style.width=de,d.innerHTML="",a.agentIconName){let Y=parseFloat(de)||24,ce=me(a.agentIconName,Y*.6,"var(--persona-text-inverse, #ffffff)",2);ce?(d.appendChild(ce),d.style.display=""):(d.textContent=(k=a.agentIconText)!=null?k:"\u{1F4AC}",d.style.display="")}else a.iconUrl?d.style.display="none":(d.textContent=(U=a.agentIconText)!=null?U:"\u{1F4AC}",d.style.display="")}let f=t.querySelector("[data-role='launcher-image']");if(f){let de=(ue=a.agentIconSize)!=null?ue:"40px";f.style.height=de,f.style.width=de,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 de=(ie=a.callToActionIconSize)!=null?ie:"32px";m.style.height=de,m.style.width=de,a.callToActionIconBackgroundColor?(m.style.backgroundColor=a.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(m.style.color=a.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Y=0;if(a.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=a.callToActionIconPadding,Y=(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 ce=parseFloat(de)||24,q=Math.max(ce-Y,8),K=me(a.callToActionIconName,q,"currentColor",2);K?m.appendChild(K):m.textContent=(_=a.callToActionIconText)!=null?_:"\u2197"}else m.textContent=(ne=a.callToActionIconText)!=null?ne:"\u2197"}let v=a.position&&wn[a.position]?wn[a.position]:wn["bottom-right"],A="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",b="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";t.className=i?b:`${A} ${v}`;let x="1px solid var(--persona-border, #e5e7eb)",M="var(--persona-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";t.style.border=(Me=a.border)!=null?Me:x,t.style.boxShadow=(le=a.shadow)!=null?le:M,i?(t.style.width="0",t.style.minWidth="0",t.style.maxWidth="0",t.style.padding="0",t.style.overflow="hidden",t.style.border="none",t.style.boxShadow="none"):(t.style.width="",t.style.minWidth="",t.style.maxWidth=(Le=a.collapsedMaxWidth)!=null?Le:"",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 sn={titleColor:"var(--persona-header-title-fg, var(--persona-primary, #0f0f0f))",subtitleColor:"var(--persona-header-subtitle-fg, var(--persona-text-muted, var(--persona-muted, #9ca3af)))",actionIconColor:"var(--persona-header-action-icon-fg, var(--persona-muted, #9ca3af))"},Jn=e=>{var ie,_,ne,Me,le,Le,de,Y,ce,q,K,Ce,ve,Ge,Ze,ft,We,nt,ke,D,se,te,z,oe,Ie,Z,G,je,Ue,St,jt,zt;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=(ie=r==null?void 0:r.launcher)!=null?ie:{},o=(_=s.headerIconSize)!=null?_:"48px",a=(ne=s.closeButtonSize)!=null?ne:"32px",i=(Me=s.closeButtonPlacement)!=null?Me:"inline",p=(le=s.headerIconHidden)!=null?le:!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, #0f0f0f))",u.style.color="var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))",!p)if(c){let J=parseFloat(o)||24,Pe=me(c,J*.6,"currentColor",1);Pe?u.replaceChildren(Pe):u.textContent=(de=(Le=r==null?void 0:r.launcher)==null?void 0:Le.agentIconText)!=null?de:"\u{1F4AC}"}else if((Y=r==null?void 0:r.launcher)!=null&&Y.iconUrl){let J=h("img");J.src=r.launcher.iconUrl,J.alt="",J.className="persona-rounded-xl persona-object-cover",J.style.height=o,J.style.width=o,u.replaceChildren(J)}else u.textContent=(q=(ce=r==null?void 0:r.launcher)==null?void 0:ce.agentIconText)!=null?q:"\u{1F4AC}";let d=h("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=h("span","persona-text-base persona-font-semibold");f.style.color=sn.titleColor,f.textContent=(Ce=(K=r==null?void 0:r.launcher)==null?void 0:K.title)!=null?Ce:"Chat Assistant";let m=h("span","persona-text-xs");m.style.color=sn.subtitleColor,m.textContent=(Ge=(ve=r==null?void 0:r.launcher)==null?void 0:ve.subtitle)!=null?Ge:"Here to help you get answers fast",d.append(f,m),p?n.append(d):n.append(u,d);let v=(Ze=s.clearChat)!=null?Ze:{},A=(ft=v.enabled)!=null?ft:!0,b=(We=v.placement)!=null?We:"inline",x=null,M=null;if(A){let J=(nt=v.size)!=null?nt:"32px",Pe=(ke=v.iconName)!=null?ke:"refresh-cw",ht=(D=v.iconColor)!=null?D:"",yt=(se=v.backgroundColor)!=null?se:"",Qe=(te=v.borderWidth)!=null?te:"",it=(z=v.borderColor)!=null?z:"",Wt=(oe=v.borderRadius)!=null?oe:"",qt=(Ie=v.paddingX)!=null?Ie:"",pe=(Z=v.paddingY)!=null?Z:"",T=(G=v.tooltipText)!=null?G:"Clear chat",Ee=(je=v.showTooltip)!=null?je:!0;M=h("div",b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"),b==="top-right"&&(M.style.right="48px"),x=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"),x.style.height=J,x.style.width=J,x.type="button",x.setAttribute("aria-label",T),x.style.color=ht||sn.actionIconColor;let re=me(Pe,"20px","currentColor",1);if(re&&x.appendChild(re),yt&&(x.style.backgroundColor=yt,x.classList.remove("hover:persona-bg-gray-100")),Qe||it){let be=Qe||"0px",we=it||"transparent";x.style.border=`${be} solid ${we}`,x.classList.remove("persona-border-none")}if(Wt&&(x.style.borderRadius=Wt,x.classList.remove("persona-rounded-full")),qt?(x.style.paddingLeft=qt,x.style.paddingRight=qt):(x.style.paddingLeft="",x.style.paddingRight=""),pe?(x.style.paddingTop=pe,x.style.paddingBottom=pe):(x.style.paddingTop="",x.style.paddingBottom=""),M.appendChild(x),Ee&&T&&x&&M){let be=null,we=()=>{if(be||!x)return;let fe=x.ownerDocument,Re=fe.body;if(!Re)return;be=Ln(fe,"div","persona-clear-chat-tooltip"),be.textContent=T;let Be=Ln(fe,"div");Be.className="persona-clear-chat-tooltip-arrow",be.appendChild(Be);let rt=x.getBoundingClientRect();be.style.position="fixed",be.style.left=`${rt.left+rt.width/2}px`,be.style.top=`${rt.top-8}px`,be.style.transform="translate(-50%, -100%)",Re.appendChild(be)},ze=()=>{be&&be.parentNode&&(be.parentNode.removeChild(be),be=null)};M.addEventListener("mouseenter",we),M.addEventListener("mouseleave",ze),x.addEventListener("focus",we),x.addEventListener("blur",ze),M._cleanupTooltip=()=>{ze(),M&&(M.removeEventListener("mouseenter",we),M.removeEventListener("mouseleave",ze)),x&&(x.removeEventListener("focus",we),x.removeEventListener("blur",ze))}}b==="inline"&&n.appendChild(M)}let F=h("div",i==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":A&&b==="inline"?"":"persona-ml-auto"),S=h("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");S.style.height=a,S.style.width=a,S.type="button";let I=(Ue=s.closeButtonTooltipText)!=null?Ue:"Close chat",O=(St=s.closeButtonShowTooltip)!=null?St:!0;S.setAttribute("aria-label",I),S.style.display=t?"":"none";let k=(jt=s.closeButtonIconName)!=null?jt:"x",U=(zt=s.closeButtonIconText)!=null?zt:"\xD7";S.style.color=s.closeButtonColor||sn.actionIconColor;let ue=me(k,"20px","currentColor",1);if(ue?S.appendChild(ue):S.textContent=U,s.closeButtonBackgroundColor?(S.style.backgroundColor=s.closeButtonBackgroundColor,S.classList.remove("hover:persona-bg-gray-100")):(S.style.backgroundColor="",S.classList.add("hover:persona-bg-gray-100")),s.closeButtonBorderWidth||s.closeButtonBorderColor){let J=s.closeButtonBorderWidth||"0px",Pe=s.closeButtonBorderColor||"transparent";S.style.border=`${J} solid ${Pe}`,S.classList.remove("persona-border-none")}else S.style.border="",S.classList.add("persona-border-none");if(s.closeButtonBorderRadius?(S.style.borderRadius=s.closeButtonBorderRadius,S.classList.remove("persona-rounded-full")):(S.style.borderRadius="",S.classList.add("persona-rounded-full")),s.closeButtonPaddingX?(S.style.paddingLeft=s.closeButtonPaddingX,S.style.paddingRight=s.closeButtonPaddingX):(S.style.paddingLeft="",S.style.paddingRight=""),s.closeButtonPaddingY?(S.style.paddingTop=s.closeButtonPaddingY,S.style.paddingBottom=s.closeButtonPaddingY):(S.style.paddingTop="",S.style.paddingBottom=""),F.appendChild(S),O&&I){let J=null,Pe=()=>{if(J)return;let yt=S.ownerDocument,Qe=yt.body;if(!Qe)return;J=Ln(yt,"div","persona-clear-chat-tooltip"),J.textContent=I;let it=Ln(yt,"div");it.className="persona-clear-chat-tooltip-arrow",J.appendChild(it);let Wt=S.getBoundingClientRect();J.style.position="fixed",J.style.left=`${Wt.left+Wt.width/2}px`,J.style.top=`${Wt.top-8}px`,J.style.transform="translate(-50%, -100%)",Qe.appendChild(J)},ht=()=>{J&&J.parentNode&&(J.parentNode.removeChild(J),J=null)};F.addEventListener("mouseenter",Pe),F.addEventListener("mouseleave",ht),S.addEventListener("focus",Pe),S.addEventListener("blur",ht),F._cleanupTooltip=()=>{ht(),F.removeEventListener("mouseenter",Pe),F.removeEventListener("mouseleave",ht),S.removeEventListener("focus",Pe),S.removeEventListener("blur",ht)}}return i!=="top-right"&&n.appendChild(F),{header:n,iconHolder:u,headerTitle:f,headerSubtitle:m,closeButton:S,closeButtonWrapper:F,clearChatButton:x,clearChatButtonWrapper:M}},Tr=(e,r,t)=>{var a,i,p,c;let n=(a=t==null?void 0:t.launcher)!=null?a:{},s=(i=n.closeButtonPlacement)!=null?i:"inline",o=(c=(p=n.clearChat)==null?void 0:p.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 pr(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 b=document.createElement("hr");a.appendChild(b)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let b=me(m.icon,16,"currentColor",1.5);b&&v.appendChild(b)}let A=document.createElement("span");A.textContent=m.label,v.appendChild(A),v.addEventListener("click",b=>{b.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function p(){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(){p(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!n.contains(v.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 d(){a.classList.contains("persona-hidden")?c():u()}function f(){u(),a.remove()}return o&&o.appendChild(a),{element:a,show:c,hide:u,toggle:d,destroy:f}}function vt(e){let{icon:r,label:t,size:n,strokeWidth:s,className:o,onClick:a,aria:i}=e,p=h("button","persona-icon-btn"+(o?" "+o:""));p.type="button",p.setAttribute("aria-label",t),p.title=t;let c=me(r,n!=null?n:16,"currentColor",s!=null?s:2);if(c&&p.appendChild(c),a&&p.addEventListener("click",a),i)for(let[u,d]of Object.entries(i))p.setAttribute(u,d);return p}function jo(e){let{icon:r,label:t,variant:n="default",size:s="sm",iconSize:o,className:a,onClick:i,aria:p}=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 d=h("span");if(d.textContent=t,u.appendChild(d),i&&u.addEventListener("click",i),p)for(let[f,m]of Object.entries(p))u.setAttribute(f,m);return u}function zo(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 p(){for(let u of i)u.btn.setAttribute("aria-pressed",u.id===a?"true":"false")}for(let u of r){let d;u.icon?d=vt({icon:u.icon,label:u.label,onClick:()=>{a=u.id,p(),n(u.id)}}):(d=h("button","persona-icon-btn"),d.type="button",d.setAttribute("aria-label",u.label),d.title=u.label,d.textContent=u.label,d.addEventListener("click",()=>{a=u.id,p(),n(u.id)})),d.setAttribute("aria-pressed",u.id===a?"true":"false"),i.push({id:u.id,btn:d}),o.appendChild(d)}function c(u){a=u,p()}return{element:o,setSelected:c}}function bs(e){var m,v;let{label:r,icon:t="chevron-down",menuItems:n,onSelect:s,position:o="bottom-left",portal:a,className:i,hover:p}=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 d=me(t,14,"currentColor",2);d&&(d.style.marginLeft="4px",d.style.opacity="0.6",c.appendChild(d)),p&&(c.style.borderRadius=(m=p.borderRadius)!=null?m:"10px",c.style.padding=(v=p.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var A,b;c.style.backgroundColor=(A=p.background)!=null?A:"",c.style.borderColor=(b=p.border)!=null?b:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=pr({items:n,onSelect:A=>{c.setAttribute("aria-expanded","false"),s(A)},anchor:c,position:o,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",A=>{A.stopPropagation();let b=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",b?"false":"true"),f.toggle()}),c.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),c.click())}),{element:c,setLabel:A=>{u.textContent=A,c.setAttribute("aria-label",A)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let A=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",A?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Bl=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 Td(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 p=me(a.icon,14,"currentColor",2);p&&i.appendChild(p)}else a.label&&(i.textContent=a.label);if((o=a.menuItems)!=null&&o.length){let p=h("div","persona-relative");p.appendChild(i);let c=pr({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:p,position:"bottom-left"});p.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),e.appendChild(p)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),e.appendChild(i)}}var Dl=e=>{var M,F,S,I,O,k,U,ue,ie;let{config:r,showClose:t=!0,onClose:n,layoutHeaderConfig:s,onHeaderAction:o}=e,a=(M=r==null?void 0:r.launcher)!=null?M:{},i=h("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let p=s==null?void 0:s.titleMenu,c,u;if(p)c=bs({label:(F=a.title)!=null?F:"Chat Assistant",menuItems:p.menuItems,onSelect:p.onSelect,hover:p.hover,className:""}).element,c.style.color=sn.titleColor,u=(S=c.querySelector(".persona-combo-btn-label"))!=null?S: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=sn.titleColor,u.textContent=(I=a.title)!=null?I:"Chat Assistant",c.appendChild(u),Td(c,s==null?void 0:s.trailingActions,(O=s==null?void 0:s.onAction)!=null?O:o),s!=null&&s.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let ne=s.onTitleClick;c.addEventListener("click",Me=>{Me.target.closest("button")||ne()}),c.addEventListener("keydown",Me=>{(Me.key==="Enter"||Me.key===" ")&&(Me.preventDefault(),ne())})}let _=s==null?void 0:s.titleRowHover;_&&(c.style.borderRadius=(k=_.borderRadius)!=null?k:"10px",c.style.padding=(U=_.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 ne,Me;c.style.backgroundColor=(ne=_.background)!=null?ne:"",c.style.borderColor=(Me=_.border)!=null?Me:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let d=(ue=a.closeButtonSize)!=null?ue:"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=d,m.style.width=d,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||sn.actionIconColor;let v=(ie=a.closeButtonIconName)!=null?ie:"x",A=me(v,"20px","currentColor",2);A?m.appendChild(A):m.textContent="\xD7",n&&m.addEventListener("click",n),f.appendChild(m),i.appendChild(f);let b=h("div");b.style.display="none";let x=h("span");return x.style.display="none",{header:i,iconHolder:b,headerTitle:u,headerSubtitle:x,closeButton:m,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},xs={default:Bl,minimal:Dl},Nl=e=>{var r;return(r=xs[e])!=null?r:xs.default},ao=(e,r,t)=>{var a,i,p;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 d=h("span"),f=h("span"),m=h("button");m.style.display="none";let v=h("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:d,headerSubtitle:f,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let n=(a=r==null?void 0:r.layout)!=null?a:"default",o=Nl(n)({config:e,showClose:(p=(i=r==null?void 0:r.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?p:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:r,onHeaderAction:r==null?void 0:r.onAction});return r&&(r.showIcon===!1&&(o.iconHolder.style.display="none"),r.showTitle===!1&&(o.headerTitle.style.display="none"),r.showSubtitle===!1&&(o.headerSubtitle.style.display="none"),r.showCloseButton===!1&&(o.closeButton.style.display="none"),r.showClearChat===!1&&o.clearChatButtonWrapper&&(o.clearChatButtonWrapper.style.display="none")),o};var io=e=>{var We,nt,ke,D,se,te,z,oe,Ie,Z,G,je,Ue,St,jt,zt,J,Pe,ht,yt,Qe,it,Wt,qt,pe,T,Ee;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=(nt=(We=r==null?void 0:r.copy)==null?void 0:We.inputPlaceholder)!=null?nt:"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 p=3*20;o.style.maxHeight=`${p}px`,o.style.overflowY="auto";let c=()=>{o.style.height="auto";let re=Math.min(o.scrollHeight,p);o.style.height=`${re}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=(ke=r==null?void 0:r.sendButton)!=null?ke:{},d=(D=u.useIcon)!=null?D:!1,f=(se=u.iconText)!=null?se:"\u2191",m=u.iconName,v=(te=u.tooltipText)!=null?te:"Send message",A=(z=u.showTooltip)!=null?z:!1,b=(oe=u.size)!=null?oe:"40px",x=u.backgroundColor,M=u.textColor,F=h("div","persona-send-button-wrapper"),S=h("button",d?"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer":"persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold disabled:persona-opacity-50 persona-cursor-pointer");if(S.type="submit",S.setAttribute("data-persona-composer-submit",""),d){if(S.style.width=b,S.style.height=b,S.style.minWidth=b,S.style.minHeight=b,S.style.fontSize="18px",S.style.lineHeight="1",S.innerHTML="",M?S.style.color=M:S.style.color="var(--persona-button-primary-fg, #ffffff)",m){let re=parseFloat(b)||24,be=(M==null?void 0:M.trim())||"currentColor",we=me(m,re,be,2);we?S.appendChild(we):S.textContent=f}else S.textContent=f;x?S.style.backgroundColor=x:S.classList.add("persona-bg-persona-primary")}else S.textContent=(Z=(Ie=r==null?void 0:r.copy)==null?void 0:Ie.sendButtonLabel)!=null?Z:"Send",M?S.style.color=M:S.classList.add("persona-text-white");if(u.borderWidth&&(S.style.borderWidth=u.borderWidth,S.style.borderStyle="solid"),u.borderColor&&(S.style.borderColor=u.borderColor),u.paddingX?(S.style.paddingLeft=u.paddingX,S.style.paddingRight=u.paddingX):(S.style.paddingLeft="",S.style.paddingRight=""),u.paddingY?(S.style.paddingTop=u.paddingY,S.style.paddingBottom=u.paddingY):(S.style.paddingTop="",S.style.paddingBottom=""),A&&v){let re=h("div","persona-send-button-tooltip");re.textContent=v,F.appendChild(re)}F.appendChild(S);let I=(G=r==null?void 0:r.voiceRecognition)!=null?G:{},O=I.enabled===!0,k=null,U=null,ue=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),ie=((je=I.provider)==null?void 0:je.type)==="runtype";if(O&&(ue||ie)){U=h("div","persona-send-button-wrapper"),k=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer"),k.type="button",k.setAttribute("data-persona-composer-mic",""),k.setAttribute("aria-label","Start voice recognition");let re=(Ue=I.iconName)!=null?Ue:"mic",be=(St=I.iconSize)!=null?St:b,we=parseFloat(be)||24,ze=(jt=I.backgroundColor)!=null?jt:x,fe=(zt=I.iconColor)!=null?zt:M;k.style.width=be,k.style.height=be,k.style.minWidth=be,k.style.minHeight=be,k.style.fontSize="18px",k.style.lineHeight="1",fe?k.style.color=fe:k.style.color="var(--persona-text, #111827)";let Be=me(re,we,fe||"currentColor",1.5);Be?k.appendChild(Be):k.textContent="\u{1F3A4}",ze&&(k.style.backgroundColor=ze),I.borderWidth&&(k.style.borderWidth=I.borderWidth,k.style.borderStyle="solid"),I.borderColor&&(k.style.borderColor=I.borderColor),I.paddingX&&(k.style.paddingLeft=I.paddingX,k.style.paddingRight=I.paddingX),I.paddingY&&(k.style.paddingTop=I.paddingY,k.style.paddingBottom=I.paddingY),U.appendChild(k);let rt=(J=I.tooltipText)!=null?J:"Start voice recognition";if(((Pe=I.showTooltip)!=null?Pe:!1)&&rt){let _e=h("div","persona-send-button-tooltip");_e.textContent=rt,U.appendChild(_e)}}let ne=(ht=r==null?void 0:r.attachments)!=null?ht:{},Me=ne.enabled===!0,le=null,Le=null,de=null,Y=null;if(Me){Y=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Y.style.display="none",de=h("input"),de.type="file",de.accept=((yt=ne.allowedTypes)!=null?yt:Dn).join(","),de.multiple=((Qe=ne.maxFiles)!=null?Qe:4)>1,de.style.display="none",de.setAttribute("aria-label","Attach files"),Le=h("div","persona-send-button-wrapper"),le=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),le.type="button",le.setAttribute("aria-label",(it=ne.buttonTooltipText)!=null?it:"Attach file");let re=(Wt=ne.buttonIconName)!=null?Wt:"paperclip",be=b,we=parseFloat(be)||40,ze=Math.round(we*.6);le.style.width=be,le.style.height=be,le.style.minWidth=be,le.style.minHeight=be,le.style.fontSize="18px",le.style.lineHeight="1",le.style.backgroundColor="transparent",le.style.color="var(--persona-primary, #111827)",le.style.border="none",le.style.borderRadius="6px",le.style.transition="background-color 0.15s ease",le.addEventListener("mouseenter",()=>{le.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),le.addEventListener("mouseleave",()=>{le.style.backgroundColor="transparent"});let fe=me(re,ze,"currentColor",1.5);fe?le.appendChild(fe):le.textContent="\u{1F4CE}",le.addEventListener("click",rt=>{rt.preventDefault(),de==null||de.click()}),Le.appendChild(le);let Re=(qt=ne.buttonTooltipText)!=null?qt:"Attach file",Be=h("div","persona-send-button-tooltip");Be.textContent=Re,Le.appendChild(Be)}s.addEventListener("click",re=>{re.target!==S&&re.target!==F&&re.target!==k&&re.target!==U&&re.target!==le&&re.target!==Le&&o.focus()}),Y&&(Y.style.gap="8px",s.append(Y)),de&&s.append(de),s.append(o);let ce=h("div","persona-flex persona-items-center persona-justify-between persona-w-full"),q=h("div","persona-flex persona-items-center persona-gap-2");Le&&q.append(Le);let K=h("div","persona-flex persona-items-center persona-gap-1");U&&K.append(U),K.append(F),ce.append(q,K),s.append(ce);let Ce=(pe=r==null?void 0:r.statusIndicator)!=null?pe:{},ve=Ce.align==="left"?"persona-text-left":Ce.align==="center"?"persona-text-center":"persona-text-right",Ge=h("div",`persona-mt-2 ${ve} persona-text-xs persona-text-persona-muted`);Ge.setAttribute("data-persona-composer-status","");let Ze=(T=Ce.visible)!=null?T:!0;Ge.style.display=Ze?"":"none";let ft=(Ee=Ce.idleText)!=null?Ee:"Online";if(Ce.idleLink){let re=h("a");re.href=Ce.idleLink,re.target="_blank",re.rel="noopener noreferrer",re.textContent=ft,re.style.color="inherit",re.style.textDecoration="none",Ge.appendChild(re)}else Ge.textContent=ft;return t.append(n,s,Ge),{footer:t,suggestions:n,composerForm:s,textarea:o,sendButton:S,sendButtonWrapper:F,micButton:k,micButtonWrapper:U,statusText:Ge,attachmentButton:le,attachmentButtonWrapper:Le,attachmentInput:de,attachmentPreviewsContainer:Y,actionsRow:ce,leftActions:q,rightActions:K}};var Ol=e=>{var c,u,d,f,m,v,A;let r=(u=(c=e==null?void 0:e.launcher)==null?void 0:c.enabled)!=null?u:!0;if(_t(e)){let b=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 b.appendChild(x),{wrapper:b,panel:x}}if(!r){let b=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"),M=(f=(d=e==null?void 0:e.launcher)==null?void 0:d.width)!=null?f:"100%";return b.style.width=M,x.style.width="100%",b.appendChild(x),{wrapper:b,panel:x}}let n=(m=e==null?void 0:e.launcher)!=null?m:{},s=n.position&&wn[n.position]?wn[n.position]:wn["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=(A=(v=e==null?void 0:e.launcher)==null?void 0:v.width)!=null?A:e==null?void 0:e.launcherWidth,p=i!=null?i:"min(400px, calc(100vw - 24px))";return a.style.width=p,a.style.maxWidth=p,o.appendChild(a),{wrapper:o,panel:a}},$l=(e,r=!0)=>{var b,x,M,F,S,I,O,k,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=(b=e==null?void 0:e.layout)==null?void 0:b.header,s=((x=e==null?void 0:e.layout)==null?void 0:x.showHeader)!==!1,o=n?ao(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=_t(e)?"persona-rounded-2xl persona-bg-persona-surface persona-p-6":"persona-rounded-2xl persona-bg-persona-surface persona-p-6 persona-shadow-sm",p=h("div",i),c=h("h2","persona-text-lg persona-font-semibold persona-text-persona-primary");c.textContent=(F=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?F:"Hello \u{1F44B}";let u=h("p","persona-mt-2 persona-text-sm persona-text-persona-muted");u.textContent=(I=(S=e==null?void 0:e.copy)==null?void 0:S.welcomeSubtitle)!=null?I:"Ask anything about your account or products.",p.append(c,u);let d=h("div","persona-flex persona-flex-col persona-gap-3"),f=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;f&&(d.style.maxWidth=f,d.style.marginLeft="auto",d.style.marginRight="auto",d.style.width="100%"),p.setAttribute("data-persona-intro-card",""),((k=e==null?void 0:e.copy)==null?void 0:k.showWelcomeCard)!==!1||(p.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(p,d);let v=io({config:e}),A=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;return s?Tr(t,o,e):(o.header.style.display="none",Tr(t,o,e)),t.append(a),A||(v.footer.style.display="none"),t.append(v.footer),{container:t,body:a,messagesWrapper:d,suggestions:v.suggestions,textarea:v.textarea,sendButton:v.sendButton,sendButtonWrapper:v.sendButtonWrapper,micButton:v.micButton,micButtonWrapper:v.micButtonWrapper,composerForm:v.composerForm,statusText:v.statusText,introTitle:c,introSubtitle: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:v.footer,attachmentButton:v.attachmentButton,attachmentButtonWrapper:v.attachmentButtonWrapper,attachmentInput:v.attachmentInput,attachmentPreviewsContainer:v.attachmentPreviewsContainer,actionsRow:v.actionsRow,leftActions:v.leftActions,rightActions:v.rightActions}};var Md=e=>{let r=e.toLowerCase();return r.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||r.startsWith("data:image/")||!e.includes(":"))},kd=320,Ld=320,Id=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(r=>r.type==="image"&&typeof r.image=="string"&&r.image.trim().length>0),Pd=(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,p)=>{var d;let c=h("img");c.alt=((d=i.alt)==null?void 0:d.trim())||`Attached image ${p+1}`,c.loading="lazy",c.decoding="async",c.referrerPolicy="no-referrer",c.style.display="block",c.style.width="100%",c.style.maxWidth=`${kd}px`,c.style.maxHeight=`${Ld}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}),Md(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}},Mr=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="0ms";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="250ms";let n=document.createElement("div");n.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",n.style.backgroundColor="currentColor",n.style.opacity="0.4",n.style.animationDelay="500ms";let s=document.createElement("span");return s.className="persona-sr-only",s.textContent="Loading",e.appendChild(r),e.appendChild(t),e.appendChild(n),e.appendChild(s),e},_l=(e,r,t)=>{let n={config:t!=null?t:{},streaming:!0,location:e,defaultRenderer:Mr};if(r){let s=r(n);if(s!==null)return s}return Mr()},Wd=(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},Fl=(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},Rd=(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},jl=(e,r,t)=>{var m,v,A,b,x,M;let n=(m=r.showCopy)!=null?m:!0,s=(v=r.showUpvote)!=null?v:!0,o=(A=r.showDownvote)!=null?A:!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=(b=r.visibility)!=null?b:"hover",i=(x=r.align)!=null?x:"right",p=(M=r.layout)!=null?M:"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"}[p],d=h("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${c} ${u} ${a==="hover"?"persona-message-actions-hover":""}`);d.id=`actions-${e.id}`,d.setAttribute("data-actions-for",e.id);let f=(F,S,I)=>{let O=vt({icon:F,label:S,size:14,className:"persona-message-action-btn"});return O.setAttribute("data-action",I),O};return n&&d.appendChild(f("copy","Copy message","copy")),s&&d.appendChild(f("thumbs-up","Upvote","upvote")),o&&d.appendChild(f("thumbs-down","Downvote","downvote")),d},lo=(e,r,t,n,s,o)=>{var ie,_,ne,Me,le,Le,de;let a=t!=null?t:{},i=(ie=a.layout)!=null?ie:"bubble",p=a.avatar,c=a.timestamp,u=(_=p==null?void 0:p.show)!=null?_:!1,d=(ne=c==null?void 0:c.show)!=null?ne:!1,f=(Me=p==null?void 0:p.position)!=null?Me:"left",m=(le=c==null?void 0:c.position)!=null?le:"below",v=Rd(e.role,i),A=h("div",v.join(" "));A.id=`bubble-${e.id}`,A.setAttribute("data-message-id",e.id),A.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(A.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",A.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(A.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",A.style.color="var(--persona-message-assistant-text, var(--persona-text))");let b=Id(e),x=(de=(Le=e.content)==null?void 0:Le.trim())!=null?de:"",F=b.length>0&&x===Ro,S=document.createElement("div");S.classList.add("persona-message-content");let I=r({text:e.content,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=null;if(F?(O=document.createElement("div"),O.innerHTML=I,O.style.display="none",S.appendChild(O)):S.innerHTML=I,d&&m==="inline"&&e.createdAt){let Y=Fl(e,c);Y.classList.add("persona-ml-2","persona-inline"),S.appendChild(Y)}if(b.length>0){let Y=Pd(b,!F&&!!x,()=>{F&&O&&(O.style.display="")});Y?A.appendChild(Y):F&&O&&(O.style.display="")}if(A.appendChild(S),d&&m==="below"&&e.createdAt){let Y=Fl(e,c);Y.classList.add("persona-mt-1"),A.appendChild(Y)}if(e.streaming&&e.role==="assistant"&&(!e.content||!e.content.trim())){let Y=_l("inline",o==null?void 0:o.loadingIndicatorRenderer,o==null?void 0:o.widgetConfig);Y&&A.appendChild(Y)}if(e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(n==null?void 0:n.enabled)!==!1&&n){let Y=jl(e,n,s);A.appendChild(Y)}if(!u||e.role==="system")return A;let U=h("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ue=Wd(p,e.role);return f==="right"||f==="left"&&e.role==="user"?U.append(A,ue):U.append(ue,A),A.classList.remove("persona-max-w-[85%]"),A.classList.add("persona-max-w-[calc(85%-2.5rem)]"),U},Hd=(e,r,t,n,s,o)=>{let a=t!=null?t:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):lo(e,r,t,n,s,o)};var kr=new Set,zl=(e,r)=>{let t=kr.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 p=me(t?"chevron-up":"chevron-down",16,"currentColor",2);p?a.appendChild(p):a.textContent=t?"Hide":"Show"}s.style.display=t?"":"none"},vs=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=kr.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=fl(r),o.appendChild(i),r.status==="complete"?a.style.display="none":a.style.display="";let p=h("div","persona-flex persona-items-center"),u=me(n?"chevron-up":"chevron-down",16,"currentColor",2);u?p.appendChild(u):p.textContent=n?"Hide":"Show";let d=h("div","persona-flex persona-items-center persona-ml-auto");d.append(p),s.append(o,d);let f=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");f.style.display=n?"":"none";let m=r.chunks.join(""),v=h("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return v.textContent=m||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),f.appendChild(v),(()=>{s.setAttribute("aria-expanded",n?"true":"false"),p.innerHTML="";let x=me(n?"chevron-up":"chevron-down",16,"currentColor",2);x?p.appendChild(x):p.textContent=n?"Hide":"Show",f.style.display=n?"":"none"})(),t.append(s,f),t};var Lr=new Set,ql=(e,r,t)=>{var c;let n=Lr.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"),p=i==null?void 0:i.querySelector(":scope > .persona-flex.persona-items-center");if(p){p.innerHTML="";let u=s.toggleTextColor||s.headerTextColor||"currentColor",d=me(n?"chevron-up":"chevron-down",16,u,2);d?p.appendChild(d):p.textContent=n?"Hide":"Show"}a.style.display=n?"":"none"},Cs=(e,r)=>{var A;let t=e.toolCall,n=(A=r==null?void 0:r.toolCall)!=null?A:{},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=Lr.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"),p=h("span","persona-text-xs persona-text-persona-primary");n.headerTextColor&&(p.style.color=n.headerTextColor),p.textContent=hl(t),i.appendChild(p);let c=h("div","persona-flex persona-items-center"),u=n.toggleTextColor||n.headerTextColor||"currentColor",d=me(o?"chevron-up":"chevron-down",16,u,2);d?c.appendChild(d):c.textContent=o?"Hide":"Show";let f=h("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");f.append(c),a.append(i,f);let m=h("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(m.style.display=o?"":"none",n.contentBackgroundColor&&(m.style.backgroundColor=n.contentBackgroundColor),n.contentTextColor&&(m.style.color=n.contentTextColor),n.contentPaddingX&&(m.style.paddingLeft=n.contentPaddingX,m.style.paddingRight=n.contentPaddingX),n.contentPaddingY&&(m.style.paddingTop=n.contentPaddingY,m.style.paddingBottom=n.contentPaddingY),t.name){let b=h("div","persona-text-xs persona-text-persona-muted persona-italic");n.contentTextColor?b.style.color=n.contentTextColor:n.headerTextColor&&(b.style.color=n.headerTextColor),b.textContent=t.name,m.appendChild(b)}if(t.args!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Arguments";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Zr(t.args),b.append(x,M),m.appendChild(b)}if(t.chunks&&t.chunks.length){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Activity";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=t.chunks.join(`
16
+ `),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&t.result!==void 0){let b=h("div","persona-space-y-1"),x=h("div","persona-text-xs persona-text-persona-muted");n.labelTextColor&&(x.style.color=n.labelTextColor),x.textContent="Result";let M=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");M.style.fontSize="0.75rem",M.style.lineHeight="1rem",n.codeBlockBackgroundColor&&(M.style.backgroundColor=n.codeBlockBackgroundColor),n.codeBlockBorderColor&&(M.style.borderColor=n.codeBlockBorderColor),n.codeBlockTextColor&&(M.style.color=n.codeBlockTextColor),M.textContent=Zr(t.result),b.append(x,M),m.appendChild(b)}if(t.status==="complete"&&typeof t.duration=="number"){let b=h("div","persona-text-xs persona-text-persona-muted");n.contentTextColor&&(b.style.color=n.contentTextColor),b.textContent=`Duration: ${t.duration}ms`,m.appendChild(b)}return(()=>{a.setAttribute("aria-expanded",o?"true":"false"),c.innerHTML="";let b=n.toggleTextColor||n.headerTextColor||"currentColor",x=me(o?"chevron-up":"chevron-down",16,b,2);x?c.appendChild(x):c.textContent=o?"Hide":"Show",m.style.display=o?"":"none"})(),s.append(a,m),s};var ws=(e,r)=>{var A,b,x,M,F,S,I,O,k,U,ue,ie;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=(A=n==null?void 0:n.backgroundColor)!=null?A:"var(--persona-approval-bg, #fefce8)",o.style.borderColor=(b=n==null?void 0:n.borderColor)!=null?b:"var(--persona-approval-border, #fef08a)",!t)return o;let a=h("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=h("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let p=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=n==null?void 0:n.titleColor)!=null?x:"currentColor",u=me(p,20,c,2);u&&i.appendChild(u);let d=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=(M=n==null?void 0:n.title)!=null?M:"Approval Required",f.appendChild(m),!s){let _=h("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");_.setAttribute("data-approval-status",t.status),t.status==="approved"?(_.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",_.style.color="var(--persona-palette-colors-success-700, #15803d)",_.textContent="Approved"):t.status==="denied"?(_.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",_.style.color="var(--persona-palette-colors-error-700, #b91c1c)",_.textContent="Denied"):t.status==="timeout"&&(_.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",_.style.color="var(--persona-palette-colors-warning-700, #b45309)",_.textContent="Timeout"),f.appendChild(_)}d.appendChild(f);let v=h("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(n!=null&&n.descriptionColor&&(v.style.color=n.descriptionColor),v.textContent=t.description,d.appendChild(v),t.parameters){let _=h("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");n!=null&&n.parameterBackgroundColor&&(_.style.backgroundColor=n.parameterBackgroundColor),n!=null&&n.parameterTextColor&&(_.style.color=n.parameterTextColor),_.style.fontSize="0.75rem",_.style.lineHeight="1rem",_.textContent=Zr(t.parameters),d.appendChild(_)}if(s){let _=h("div","persona-flex persona-gap-2 persona-mt-2");_.setAttribute("data-approval-buttons","true");let ne=h("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");ne.type="button",ne.style.backgroundColor=(F=n==null?void 0:n.approveButtonColor)!=null?F:"var(--persona-approval-approve-bg, #22c55e)",ne.style.color=(S=n==null?void 0:n.approveButtonTextColor)!=null?S:"#ffffff",ne.setAttribute("data-approval-action","approve");let Me=me("shield-check",14,(I=n==null?void 0:n.approveButtonTextColor)!=null?I:"#ffffff",2);Me&&(Me.style.marginRight="4px",ne.appendChild(Me));let le=document.createTextNode((O=n==null?void 0:n.approveLabel)!=null?O:"Approve");ne.appendChild(le);let Le=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");Le.type="button",Le.style.backgroundColor=(k=n==null?void 0:n.denyButtonColor)!=null?k:"transparent",Le.style.color=(U=n==null?void 0:n.denyButtonTextColor)!=null?U:"var(--persona-feedback-error, #dc2626)",Le.style.border=`1px solid ${n!=null&&n.denyButtonTextColor?n.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,Le.setAttribute("data-approval-action","deny");let de=me("shield-x",14,(ue=n==null?void 0:n.denyButtonTextColor)!=null?ue:"var(--persona-feedback-error, #dc2626)",2);de&&(de.style.marginRight="4px",Le.appendChild(de));let Y=document.createTextNode((ie=n==null?void 0:n.denyLabel)!=null?ie:"Deny");Le.appendChild(Y),_.append(ne,Le),d.appendChild(_)}return a.append(i,d),o.appendChild(a),o};var Vl=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(),d=s?s.isStreaming():!1,f=m=>{switch(m){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};n.forEach(m=>{let v=h("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");v.type="button",v.textContent=m,v.disabled=d,i!=null&&i.fontFamily&&(v.style.fontFamily=f(i.fontFamily)),i!=null&&i.fontWeight&&(v.style.fontWeight=i.fontWeight),i!=null&&i.paddingX&&(v.style.paddingLeft=i.paddingX,v.style.paddingRight=i.paddingX),i!=null&&i.paddingY&&(v.style.paddingTop=i.paddingY,v.style.paddingBottom=i.paddingY),v.addEventListener("click",()=>{!s||s.isStreaming()||(o.value="",s.sendMessage(m))}),u.appendChild(v),r.push(v)}),e.appendChild(u)}}};var co=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 po=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 Ir(e,r){r&&r.split(/\s+/).forEach(t=>t&&e.classList.add(t))}var Bd={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Dd={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Nd=["flowName","stepName","reasoningText","text","name","tool","toolName"],Od=100;function $d(e,r){let t={...Bd,...r};if(t[e])return t[e];for(let n of Object.keys(t))if(n.endsWith("_")&&e.startsWith(n))return t[n];return Dd}function Fd(e,r){return`+${((e-r)/1e3).toFixed(3)}s`}function _d(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 jd(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 zd(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 qd(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 Vd(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]"),p=h("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return p.textContent=n,i.appendChild(p),i}}function Ss(e,r,t,n,s,o,a,i){var f;let p=s.has(e.id),c=h("div","persona-border-b persona-border-persona-divider persona-text-xs");Ir(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:()=>d(),isExpanded:p,onToggleExpand:()=>o(e.id)});if(m)return c.appendChild(m),c}return c.appendChild(d()),c;function d(){var ne,Me;let m=h("div",""),v=h("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");v.setAttribute("data-event-id",e.id);let A=h("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),b=me(p?"chevron-down":"chevron-right","14px","currentColor",2);b&&A.appendChild(b);let x=h("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),M=(ne=n.timestampFormat)!=null?ne:"relative";x.textContent=M==="relative"?Fd(e.timestamp,t):_d(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 S=$d(e.type,n.badgeColors),I=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");I.style.backgroundColor=S.bg,I.style.color=S.text,I.style.borderColor=S.text+"50",I.textContent=e.type;let O=(Me=n.descriptionFields)!=null?Me:Nd,k=jd(e.payload,O),U=null;k&&(U=h("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),U.textContent=k);let ue=h("div","persona-flex-1 persona-min-w-0"),ie=h("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),_=me("clipboard","12px","currentColor",1.5);return _&&ie.appendChild(_),ie.addEventListener("click",async le=>{le.stopPropagation(),await zd(qd(e)),ie.innerHTML="";let Le=me("check","12px","currentColor",1.5);Le&&ie.appendChild(Le),setTimeout(()=>{ie.innerHTML="";let de=me("clipboard","12px","currentColor",1.5);de&&ie.appendChild(de)},1500)}),v.appendChild(A),v.appendChild(x),F&&v.appendChild(F),v.appendChild(I),U&&v.appendChild(U),v.appendChild(ue),v.appendChild(ie),m.appendChild(v),p&&m.appendChild(Vd(e,a,i)),m}}function Ul(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(d=>d.renderEventStreamView);if(i!=null&&i.renderEventStreamView&&s){let d=i.renderEventStreamView({config:s,events:r.getAll(),defaultRenderer:()=>p().element,onClose:n});if(d)return{element:d,update:()=>{},destroy:()=>{}}}return p();function p(){let d=a.classNames,f=h("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ir(f,d==null?void 0:d.panel);let m=[],v="",A="",b=null,x=[],M={},F=0,S=!1,I=0,O=0,k=!1,U=null,ue=!1,ie=0,_=new Set,ne=new Map,Me="",le="",Le=null,de,Y,ce,q,K;function Ce(){let pe=h("div","persona-flex persona-flex-col persona-flex-shrink-0"),T=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");Ir(T,d==null?void 0:d.headerBar);let Ee=h("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ee.textContent="Events",de=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"),de.textContent="0";let re=h("div","persona-flex-1");Y=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 be=h("option","");be.value="",be.textContent="All events",Y.appendChild(be),ce=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"),ce.type="button",ce.title="Copy All";let ze=me("clipboard-copy","12px","currentColor",1.5);ze&&ce.appendChild(ze);let fe=h("span","persona-text-xs");fe.textContent="Copy All",ce.appendChild(fe),T.appendChild(Ee),T.appendChild(de),T.appendChild(re),T.appendChild(Y),T.appendChild(ce);let Re=h("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ir(Re,d==null?void 0:d.searchBar);let Be=me("search","14px","var(--persona-muted, #9ca3af)",1.5),rt=h("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Be&&rt.appendChild(Be),q=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"),Ir(q,d==null?void 0:d.searchInput),q.type="text",q.placeholder="Search event payloads...",K=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"),K.type="button",K.style.display="none";let At=me("x","12px","currentColor",2);return At&&K.appendChild(At),Re.appendChild(rt),Re.appendChild(q),Re.appendChild(K),pe.appendChild(T),pe.appendChild(Re),pe}let ve,Ge=o.find(pe=>pe.renderEventStreamToolbar);if(Ge!=null&&Ge.renderEventStreamToolbar&&s){let pe=Ge.renderEventStreamToolbar({config:s,defaultRenderer:()=>Ce(),eventCount:r.getSize(),filteredCount:0,onFilterChange:T=>{v=T,Ie(),je()},onSearchChange:T=>{A=T,Ie(),je()}});ve=pe!=null?pe:Ce()}else ve=Ce();let Ze=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");Ze.style.display="none";let ft=h("div","persona-flex-1 persona-min-h-0 persona-relative"),We=h("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");We.style.height="100%";let nt=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");Ir(nt,d==null?void 0:d.scrollIndicator),nt.style.display="none";let ke=me("arrow-down","12px","currentColor",2);ke&&nt.appendChild(ke);let D=h("span","");nt.appendChild(D);let se=h("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");se.style.display="none",ft.appendChild(We),ft.appendChild(se),ft.appendChild(nt),f.setAttribute("tabindex","0"),f.appendChild(ve),f.appendChild(Ze),f.appendChild(ft);function te(){let pe=r.getAll(),T={};for(let fe of pe)T[fe.type]=(T[fe.type]||0)+1;let Ee=Object.keys(T).sort(),re=Ee.length!==x.length||!Ee.every((fe,Re)=>fe===x[Re]),be=!re&&Ee.some(fe=>T[fe]!==M[fe]),we=pe.length!==Object.values(M).reduce((fe,Re)=>fe+Re,0);if(!re&&!be&&!we||(x=Ee,M=T,!Y))return;let ze=Y.value;if(Y.options[0].textContent="All events",re){for(;Y.options.length>1;)Y.remove(1);for(let fe of Ee){let Re=h("option","");Re.value=fe,Re.textContent=`${fe} (${T[fe]||0})`,Y.appendChild(Re)}ze&&Ee.includes(ze)?Y.value=ze:ze&&(Y.value="",v="")}else for(let fe=1;fe<Y.options.length;fe++){let Re=Y.options[fe];Re.textContent=`${Re.value} (${T[Re.value]||0})`}}function z(){let pe=r.getAll();if(v&&(pe=pe.filter(T=>T.type===v)),A){let T=A.toLowerCase();pe=pe.filter(Ee=>Ee.type.toLowerCase().includes(T)||Ee.payload.toLowerCase().includes(T))}return pe}function oe(){return v!==""||A!==""}function Ie(){F=0,I=0,S=!1,nt.style.display="none"}function Z(pe){_.has(pe)?_.delete(pe):_.add(pe),Le=pe;let T=We.scrollTop,Ee=S;ue=!0,S=!0,je(),We.scrollTop=T,S=Ee,ue=!1}function G(){return We.scrollHeight-We.scrollTop-We.clientHeight<=50}function je(){O=Date.now(),k=!1,te();let pe=r.getEvictedCount();pe>0?(Ze.textContent=`${pe.toLocaleString()} older events truncated`,Ze.style.display=""):Ze.style.display="none",m=z();let T=m.length,Ee=r.getSize()>0;de&&(de.textContent=String(r.getSize())),T===0&&Ee&&oe()?(se.textContent=A?`No events matching '${A}'`:"No events matching filter",se.style.display="",We.style.display="none"):(se.style.display="none",We.style.display=""),ce&&(ce.title=oe()?`Copy Filtered (${T})`:"Copy All"),S&&T>F&&(I+=T-F,D.textContent=`${I} new event${I===1?"":"s"}`,nt.style.display=""),F=T;let re=r.getAll(),be=re.length>0?re[0].timestamp:0,we=new Set(m.map(Re=>Re.id));for(let Re of _)we.has(Re)||_.delete(Re);let ze=v!==Me||A!==le,fe=ne.size===0&&m.length>0;if(ze||fe||m.length===0){We.innerHTML="",ne.clear();let Re=document.createDocumentFragment();for(let Be=0;Be<m.length;Be++){let rt=Ss(m[Be],Be,be,a,_,Z,o,s);ne.set(m[Be].id,rt),Re.appendChild(rt)}We.appendChild(Re),Me=v,le=A,Le=null}else{if(Le!==null){let Be=ne.get(Le);if(Be&&Be.parentNode===We){let rt=m.findIndex(At=>At.id===Le);if(rt>=0){let At=Ss(m[rt],rt,be,a,_,Z,o,s);We.insertBefore(At,Be),Be.remove(),ne.set(Le,At)}}Le=null}let Re=new Set(m.map(Be=>Be.id));for(let[Be,rt]of ne)Re.has(Be)||(rt.remove(),ne.delete(Be));for(let Be=0;Be<m.length;Be++){let rt=m[Be];if(!ne.has(rt.id)){let At=Ss(rt,Be,be,a,_,Z,o,s);ne.set(rt.id,At),We.appendChild(At)}}}S||(We.scrollTop=We.scrollHeight)}function Ue(){if(Date.now()-O>=Od){U!==null&&(cancelAnimationFrame(U),U=null),je();return}k||(k=!0,U=requestAnimationFrame(()=>{U=null,je()}))}let St=(pe,T)=>{if(!ce)return;ce.innerHTML="";let Ee=me(pe,"12px","currentColor",1.5);Ee&&ce.appendChild(Ee);let re=h("span","persona-text-xs");re.textContent="Copy All",ce.appendChild(re),setTimeout(()=>{ce.innerHTML="";let be=me("clipboard-copy","12px","currentColor",1.5);be&&ce.appendChild(be);let we=h("span","persona-text-xs");we.textContent="Copy All",ce.appendChild(we),ce.disabled=!1},T)},jt=async()=>{if(ce){ce.disabled=!0;try{let pe;oe()?pe=m:t?(pe=await t(),pe.length===0&&(pe=r.getAll())):pe=r.getAll();let T=pe.map(Ee=>{try{return JSON.parse(Ee.payload)}catch{return Ee.payload}});await navigator.clipboard.writeText(JSON.stringify(T,null,2)),St("check",1500)}catch{St("x",1500)}}},zt=()=>{Y&&(v=Y.value,Ie(),je())},J=()=>{!q||!K||(K.style.display=q.value?"":"none",b&&clearTimeout(b),b=setTimeout(()=>{A=q.value,Ie(),je()},150))},Pe=()=>{!q||!K||(q.value="",A="",K.style.display="none",b&&clearTimeout(b),Ie(),je())},ht=()=>{if(ue)return;let pe=We.scrollTop,T=pe>ie;ie=pe,G()&&T?(S=!1,I=0,nt.style.display="none"):G()||(S=!0)},yt=pe=>{pe.deltaY<0&&(S=!0)},Qe=()=>{We.scrollTop=We.scrollHeight,S=!1,I=0,nt.style.display="none"},it=pe=>{let T=pe.target;if(!T||T.closest("button"))return;let Ee=T.closest("[data-event-id]");if(!Ee)return;let re=Ee.getAttribute("data-event-id");re&&Z(re)},Wt=pe=>{if((pe.metaKey||pe.ctrlKey)&&pe.key==="f"){pe.preventDefault(),q==null||q.focus(),q==null||q.select();return}pe.key==="Escape"&&(q&&document.activeElement===q?(Pe(),q.blur(),f.focus()):n&&n())};ce&&ce.addEventListener("click",jt),Y&&Y.addEventListener("change",zt),q&&q.addEventListener("input",J),K&&K.addEventListener("click",Pe),We.addEventListener("scroll",ht),We.addEventListener("wheel",yt,{passive:!0}),We.addEventListener("click",it),nt.addEventListener("click",Qe),f.addEventListener("keydown",Wt);function qt(){b&&clearTimeout(b),U!==null&&(cancelAnimationFrame(U),U=null),k=!1,ne.clear(),ce&&ce.removeEventListener("click",jt),Y&&Y.removeEventListener("change",zt),q&&q.removeEventListener("input",J),K&&K.removeEventListener("click",Pe),We.removeEventListener("scroll",ht),We.removeEventListener("wheel",yt),We.removeEventListener("click",it),nt.removeEventListener("click",Qe),f.removeEventListener("keydown",Wt)}return{element:f,update:Ue,destroy:qt}}}function Jl(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 p=document.createElement("div");p.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",p.style.border="1px solid var(--persona-border, #e5e7eb)",p.style.color="var(--persona-muted, #9ca3af)",p.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 d=document.createElement("div");if(d.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",d.style.color="var(--persona-muted, #9ca3af)",s==="streaming"){let f=document.createElement("span");f.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",f.style.backgroundColor="var(--persona-primary, #171717)",f.style.animation="persona-pulse 1.5s ease-in-out infinite",d.appendChild(f);let m=document.createElement("span");m.textContent=`Generating ${a.toLowerCase()}...`,d.appendChild(m)}else d.textContent=a;if(c.append(u,d),i.append(p,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 Kl=(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:"",p=e.status==="streaming"?"streaming":"complete",c=typeof e.artifactType=="string"?e.artifactType:"markdown",u=t({artifact:{artifactId:i,title:a,artifactType:c,status:p},config:r.config,defaultRenderer:()=>Jl(e,r)});if(u)return u}return Jl(e,r)};var As=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)})}},Kn=new As;Kn.register("PersonaArtifactCard",Kl);function Ud(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 Gl(e,r){var ft,We,nt,ke;let t=(We=(ft=e.features)==null?void 0:ft.artifacts)==null?void 0:We.layout,s=((nt=t==null?void 0:t.toolbarPreset)!=null?nt:"default")==="document",o=(ke=t==null?void 0:t.panePadding)==null?void 0:ke.trim(),a=e.markdown?Cr(e.markdown):null,i=Xr(e.sanitize),p=D=>{let se=a?a(D):Yr(D);return i?i(se):se},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"),d.classList.remove("persona-artifact-drawer-open"),_==null||_.hide()};c&&c.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let d=h("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");d.setAttribute("data-persona-theme-zone","artifact-pane"),s&&d.classList.add("persona-artifact-pane-document");let f=h("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");f.setAttribute("data-persona-theme-zone","artifact-toolbar"),s&&f.classList.add("persona-artifact-toolbar-document");let m=h("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let v=h("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let A="rendered",b=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),x=s?vt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):vt({icon:"eye",label:"Rendered view"}),M=s?vt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):vt({icon:"code-2",label:"Source"}),F=h("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),S=(t==null?void 0:t.documentToolbarShowCopyLabel)===!0,I=(t==null?void 0:t.documentToolbarShowCopyChevron)===!0,O=t==null?void 0:t.documentToolbarCopyMenuItems,k=!!(I&&O&&O.length>0),U=null,ue,ie=null,_=null;if(s&&(S||I)&&!k){if(ue=S?jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I){let D=me("chevron-down",14,"currentColor",2);D&&ue.appendChild(D)}}else s&&k?(U=h("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),ue=S?jo({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),ie=vt({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(ue,ie)):s?ue=vt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):ue=vt({icon:"copy",label:"Copy"});let ne=s?vt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):vt({icon:"refresh-cw",label:"Refresh"}),Me=s?vt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):vt({icon:"x",label:"Close"}),le=()=>{var oe,Ie,Z;let D=(oe=K.find(G=>G.id===Ce))!=null?oe:K[K.length-1],se=(Ie=D==null?void 0:D.id)!=null?Ie:null,te=(D==null?void 0:D.artifactType)==="markdown"&&(Z=D.markdown)!=null?Z:"",z=D?JSON.stringify({component:D.component,props:D.props},null,2):"";return{markdown:te,jsonPayload:z,id:se}},Le=async()=>{var oe;let{markdown:D,jsonPayload:se}=le(),te=(oe=K.find(Ie=>Ie.id===Ce))!=null?oe:K[K.length-1],z=(te==null?void 0:te.artifactType)==="markdown"?D:te?se:"";try{await navigator.clipboard.writeText(z)}catch{}};if(ue.addEventListener("click",async()=>{let D=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;if(D&&k){let{markdown:se,jsonPayload:te,id:z}=le();try{await D({actionId:"primary",artifactId:z,markdown:se,jsonPayload:te})}catch{}return}await Le()}),ie&&(O!=null&&O.length)){let D=()=>{var te;return(te=d.closest("[data-persona-root]"))!=null?te:document.body},se=()=>{_=pr({items:O.map(te=>({id:te.id,label:te.label})),onSelect:async te=>{let{markdown:z,jsonPayload:oe,id:Ie}=le(),Z=t==null?void 0:t.onDocumentToolbarCopyMenuSelect;try{Z?await Z({actionId:te,artifactId:Ie,markdown:z,jsonPayload:oe}):te==="markdown"||te==="md"?await navigator.clipboard.writeText(z):te==="json"||te==="source"?await navigator.clipboard.writeText(oe):await navigator.clipboard.writeText(z||oe)}catch{}},anchor:U!=null?U:ie,position:"bottom-right",portal:D()})};d.isConnected?se():requestAnimationFrame(se),ie.addEventListener("click",te=>{te.stopPropagation(),_==null||_.toggle()})}ne.addEventListener("click",async()=>{var D;try{await((D=t==null?void 0:t.onDocumentToolbarRefresh)==null?void 0:D.call(t))}catch{}Ge()}),Me.addEventListener("click",()=>{var D;u(),(D=r.onDismiss)==null||D.call(r)});let de=()=>{s&&(x.setAttribute("aria-pressed",A==="rendered"?"true":"false"),M.setAttribute("aria-pressed",A==="source"?"true":"false"))};x.addEventListener("click",()=>{A="rendered",de(),Ge()}),M.addEventListener("click",()=>{A="source",de(),Ge()});let Y=h("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");s?(f.replaceChildren(),b.append(x,M),U?F.append(U,ne,Me):F.append(ue,ne,Me),f.append(b,Y,F),de()):(f.appendChild(m),f.appendChild(v)),o&&(f.style.paddingLeft=o,f.style.paddingRight=o);let ce=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"),q=h("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");o&&(ce.style.paddingLeft=o,ce.style.paddingRight=o,q.style.padding=o),d.appendChild(f),d.appendChild(ce),d.appendChild(q);let K=[],Ce=null,ve=!1,Ge=()=>{var z,oe,Ie,Z;let D=s&&K.length<=1;ce.classList.toggle("persona-hidden",D),ce.replaceChildren();for(let G of K){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=G.title||G.id.slice(0,8),G.id===Ce&&je.classList.add("persona-bg-persona-container","persona-border-persona-border"),je.addEventListener("click",()=>r.onSelect(G.id)),ce.appendChild(je)}q.replaceChildren();let se=Ce&&K.find(G=>G.id===Ce)||K[K.length-1];if(!se)return;if(s){let G=se.artifactType==="markdown"?"MD":(z=se.component)!=null?z:"Component",Ue=(se.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Y.textContent=`${Ue} \xB7 ${G}`}else m.textContent="Artifacts";if(se.artifactType==="markdown"){if(s&&A==="source"){let je=h("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");je.textContent=(oe=se.markdown)!=null?oe:"",q.appendChild(je);return}let G=h("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");G.innerHTML=p((Ie=se.markdown)!=null?Ie:""),q.appendChild(G);return}let te=se.component?Kn.get(se.component):void 0;if(te){let je={message:{id:se.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let Ue=te((Z=se.props)!=null?Z:{},je);if(Ue){q.appendChild(Ue);return}}catch{}}q.appendChild(Ud(se))},Ze=()=>{var se;let D=K.length>0;if(d.classList.toggle("persona-hidden",!D),c){let te=typeof d.closest=="function"?d.closest("[data-persona-root]"):null,oe=((se=te==null?void 0:te.classList.contains("persona-artifact-narrow-host"))!=null?se:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;D&&oe&&ve?(c.classList.remove("persona-hidden"),d.classList.add("persona-artifact-drawer-open")):(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open"))}};return{element:d,backdrop:c,update(D){var se,te,z;K=D.artifacts,Ce=(z=(te=D.selectedId)!=null?te:(se=D.artifacts[D.artifacts.length-1])==null?void 0:se.id)!=null?z:null,K.length>0&&(ve=!0),Ge(),Ze()},setMobileOpen(D){ve=D,!D&&c?(c.classList.add("persona-hidden"),d.classList.remove("persona-artifact-drawer-open")):Ze()}}}function mn(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 Yl(e,r){var o,a,i,p;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"),!mn(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=(p=t==null?void 0:t.paneBorderLeft)==null?void 0:p.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 Jd(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 qo(e,r){var p,c,u,d,f,m,v,A,b,x;if(!mn(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"),Jd(e),Yl(e,r);return}let t=(c=(p=r.features)==null?void 0:p.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",(d=t==null?void 0:t.paneWidth)!=null?d:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(f=t==null?void 0:t.paneMaxWidth)!=null?f:"28rem"),t!=null&&t.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",t.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let n=(m=t==null?void 0:t.paneBackground)==null?void 0:m.trim();n?e.style.setProperty("--persona-artifact-pane-bg",n):e.style.removeProperty("--persona-artifact-pane-bg");let s=(v=t==null?void 0:t.panePadding)==null?void 0:v.trim();s?e.style.setProperty("--persona-artifact-pane-padding",s):e.style.removeProperty("--persona-artifact-pane-padding");let o=(A=t==null?void 0:t.documentToolbarIconColor)==null?void 0:A.trim();o?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",o):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(b=t==null?void 0:t.documentToolbarToggleActiveBackground)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(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"),Yl(e,r)}var Xl=["panel","seamless"];function Vo(e,r){var i,p,c,u,d,f;for(let m of Xl)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"),!mn(r))return;let t=(p=(i=r.features)==null?void 0:i.artifacts)==null?void 0:p.layout,n=(c=t==null?void 0:t.paneAppearance)!=null?c:"panel",s=Xl.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=(d=t==null?void 0:t.paneShadow)==null?void 0:d.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(t==null?void 0:t.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((f=t.unifiedSplitOuterRadius)==null?void 0:f.trim())||o;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Zl(e,r){var t,n,s;return!r||!mn(e)?!1:((s=(n=(t=e.features)==null?void 0:t.artifacts)==null?void 0:n.layout)==null?void 0:s.expandLauncherPanelWhenOpen)!==!1}function Kd(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 Gd(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 Yd(e,r,t){return t<r?r:Math.min(t,Math.max(r,e))}function Xd(e,r,t,n){let s=e-n-2*r-t;return Math.max(0,s)}function Ql(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 ec(e,r,t,n,s,o){let a=Kd(s,200),i=Xd(r,t,n,200);i=Math.max(a,i);let p=Gd(o);return p!==null&&(i=Math.min(i,p)),Yd(e,a,i)}var tc={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"}},Es=(e,r,t,n)=>{let s=e.querySelectorAll("[data-tv-form]");s.length&&s.forEach(o=>{var v,A,b;if(o.dataset.enhanced==="true")return;let a=(v=o.dataset.tvForm)!=null?v:"init";o.dataset.enhanced="true";let i=(A=tc[a])!=null?A:tc.init;o.classList.add("persona-form-card","persona-space-y-4");let p=h("div","persona-space-y-1"),c=h("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(c.textContent=i.title,p.appendChild(c),i.description){let x=h("p","persona-text-sm persona-text-persona-muted");x.textContent=i.description,p.appendChild(x)}let u=document.createElement("form");u.className="persona-form-grid persona-space-y-3",i.fields.forEach(x=>{var O,k;let M=h("label","persona-form-field persona-flex persona-flex-col persona-gap-1");M.htmlFor=`${r.id}-${a}-${x.name}`;let F=h("span","persona-text-xs persona-font-medium persona-text-persona-muted");F.textContent=x.label,M.appendChild(F);let S=(O=x.type)!=null?O:"text",I;S==="textarea"?(I=document.createElement("textarea"),I.rows=3):(I=document.createElement("input"),I.type=S),I.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",I.id=`${r.id}-${a}-${x.name}`,I.name=x.name,I.placeholder=(k=x.placeholder)!=null?k:"",x.required&&(I.required=!0),M.appendChild(I),u.appendChild(M)});let d=h("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),f=h("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=h("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(b=i.submitLabel)!=null?b:"Submit",d.appendChild(f),d.appendChild(m),u.appendChild(d),o.replaceChildren(p,u),u.addEventListener("submit",async x=>{var I,O;x.preventDefault();let M=(I=t.formEndpoint)!=null?I:"/form",F=new FormData(u),S={};F.forEach((k,U)=>{S[U]=k}),S.type=a,m.disabled=!0,f.textContent="Submitting\u2026";try{let k=await fetch(M,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S)});if(!k.ok)throw new Error(`Form submission failed (${k.status})`);let U=await k.json();f.textContent=(O=U.message)!=null?O:"Thanks! We'll be in touch soon.",U.success&&U.nextPrompt&&await n.sendMessage(String(U.nextPrompt))}catch(k){f.textContent=k instanceof Error?k.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var Ts=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,p;return((i=a.priority)!=null?i:0)-((p=o.priority)!=null?p:0)})}clear(){this.plugins.forEach(r=>{var t;return(t=r.onUnregister)==null?void 0:t.call(r)}),this.plugins.clear()}},Uo=new Ts;var Ct={apiUrl:"http://localhost:43111/api/chat/dispatch",clientToken:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:{enabled:!0,mountMode:"floating",dock:{side:"right",width:"420px"},title:"Chat Assistant",subtitle:"Here to help you get answers fast",agentIconText:"\u{1F4AC}",agentIconName:"bot",headerIconName:"bot",position:"bottom-right",width:"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:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0},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 nc(e,r){if(!(!e&&!r))return e?r?oo(e,r):e:r}function Ms(e){var r,t,n,s,o,a,i,p,c,u,d,f,m,v,A,b,x,M,F,S,I;return e?{...Ct,...e,theme:nc(Ct.theme,e.theme),darkTheme:nc(Ct.darkTheme,e.darkTheme),launcher:{...Ct.launcher,...e.launcher,dock:{...(r=Ct.launcher)==null?void 0:r.dock,...(t=e.launcher)==null?void 0:t.dock},clearChat:{...(n=Ct.launcher)==null?void 0:n.clearChat,...(s=e.launcher)==null?void 0:s.clearChat}},copy:{...Ct.copy,...e.copy},sendButton:{...Ct.sendButton,...e.sendButton},statusIndicator:{...Ct.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ct.voiceRecognition,...e.voiceRecognition},features:(()=>{var ue,ie;let O=(ue=Ct.features)==null?void 0:ue.artifacts,k=(ie=e.features)==null?void 0:ie.artifacts,U=O===void 0&&k===void 0?void 0:{...O,...k,layout:{...O==null?void 0:O.layout,...k==null?void 0:k.layout}};return{...Ct.features,...e.features,...U!==void 0?{artifacts:U}:{}}})(),suggestionChips:(o=e.suggestionChips)!=null?o:Ct.suggestionChips,suggestionChipsConfig:{...Ct.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ct.layout,...e.layout,header:{...(a=Ct.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(p=Ct.layout)==null?void 0:p.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(d=(u=Ct.layout)==null?void 0:u.messages)==null?void 0:d.avatar,...(m=(f=e.layout)==null?void 0:f.messages)==null?void 0:m.avatar},timestamp:{...(A=(v=Ct.layout)==null?void 0:v.messages)==null?void 0:A.timestamp,...(x=(b=e.layout)==null?void 0:b.messages)==null?void 0:x.timestamp}},slots:{...(M=Ct.layout)==null?void 0:M.slots,...(F=e.layout)==null?void 0:F.slots}},markdown:{...Ct.markdown,...e.markdown,options:{...(S=Ct.markdown)==null?void 0:S.options,...(I=e.markdown)==null?void 0:I.options}},messageActions:{...Ct.messageActions,...e.messageActions}}:Ct}var rc=()=>{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(p){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",p)}})}}};var Zd=e=>{let r=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return r?r[1]:e},Qd=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},Jo=({text:e})=>{if(!e||!e.includes("{"))return null;try{let r=Zd(e),t=Qd(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}},ks=e=>typeof e=="string"?e:e==null?"":String(e),Pr={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:ks(e.payload.text)},messageAndClick:(e,r)=>{var s;if(e.type!=="message_and_click")return;let t=e.payload,n=ks(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:ks(t.text)}}},oc=e=>Array.isArray(e)?e.map(r=>String(r)):[],Ko=e=>{let r=new Set(oc(e.getSessionMetadata().processedActionMessageIds)),t=()=>{r=new Set(oc(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 p={action:i,message:o.message};e.emit("action:detected",p);for(let c of e.handlers)if(c)try{let u=()=>{e.emit("action:resubmit",p)},d=c(i,{message:o.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:u});if(!d)continue;if(d.handled){let f=d.persistMessage!==!1;return{text:d.displayText!==void 0?d.displayText:"",persist:f,resubmit:d.resubmit}}}catch(u){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",u)}return{text:"",persist:!0}},syncFromMetadata:t}};var ep=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}},tp=e=>e.map(r=>({...r,streaming:!1})),Ls=(e="persona-state")=>{let r=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let t=r();return t?ep(t.getItem(e)):null},save:t=>{let n=r();if(n)try{let s={...t,messages:t.messages?tp(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 np,STR as rp,OBJ as op}from"partial-json";function sp(e){if(!e||typeof e!="object"||!("component"in e))return!1;let r=e.component;return typeof r=="string"&&r.length>0}function ap(e,r){if(!sp(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 Is(){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=np(t,rp|op),o=ap(s,t);o&&(e=o)}catch{}return r=t.length,e},reset:()=>{e=null,r=0}}}function ip(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Ps(e,r){let{config:t,message:n,onPropsUpdate:s}=r,o=Kn.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 lp(){let e=Is();return{processChunk:r=>e.processChunk(r),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Ws(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 Rs(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 cp=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Hs(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:p=!0,ratingLabels:c=cp}=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 d=null,f=document.createElement("div");f.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=n,m.appendChild(v);let A=document.createElement("p");A.className="persona-feedback-subtitle",A.textContent=s,m.appendChild(A),f.appendChild(m);let b=document.createElement("div");b.className="persona-feedback-rating persona-feedback-rating-csat",b.setAttribute("role","radiogroup"),b.setAttribute("aria-label","Satisfaction rating from 1 to 5");let x=[];for(let O=1;O<=5;O++){let k=document.createElement("button");k.type="button",k.className="persona-feedback-rating-btn persona-feedback-star-btn",k.setAttribute("role","radio"),k.setAttribute("aria-checked","false"),k.setAttribute("aria-label",`${O} star${O>1?"s":""}: ${c[O-1]}`),k.title=c[O-1],k.dataset.rating=String(O),k.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
- `,k.addEventListener("click",()=>{d=O,x.forEach((V,ge)=>{let ie=ge<O;V.classList.toggle("selected",ie),V.setAttribute("aria-checked",ge===O-1?"true":"false")})}),x.push(k),b.appendChild(k)}f.appendChild(b);let M=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),O.appendChild(M),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{t==null||t(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(d===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let O=(M==null?void 0:M.value.trim())||void 0;await r(d,O),u.remove()}catch(O){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),F.appendChild(S),F.appendChild(I),f.appendChild(F),u.appendChild(f),u}function Bs(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:p=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,v.appendChild(A);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);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 M=document.createElement("div");M.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let S=document.createElement("span");S.className="persona-feedback-label-high",S.textContent=u,M.appendChild(F),M.appendChild(S);let I=document.createElement("div");I.className="persona-feedback-numbers";let O=[];for(let _=0;_<=10;_++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${_} out of 10`),ne.textContent=String(_),ne.dataset.rating=String(_),_<=6?ne.classList.add("persona-feedback-detractor"):_<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=_,O.forEach((Te,le)=>{Te.classList.toggle("selected",le===_),Te.setAttribute("aria-checked",le===_?"true":"false")})}),O.push(ne),I.appendChild(ne)}x.appendChild(M),x.appendChild(I),m.appendChild(x);let k=null;if(p){let _=document.createElement("div");_.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"),_.appendChild(k),m.appendChild(_)}let V=document.createElement("div");V.className="persona-feedback-actions";let ge=document.createElement("button");ge.type="button",ge.className="persona-feedback-btn persona-feedback-btn-skip",ge.textContent=i,ge.addEventListener("click",()=>{t==null||t(),d.remove()});let ie=document.createElement("button");return ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-submit",ie.textContent=a,ie.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ie.disabled=!0,ie.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await r(f,_),d.remove()}catch(_){ie.disabled=!1,ie.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),V.appendChild(ge),V.appendChild(ie),m.appendChild(V),d.appendChild(m),d}var Ir="persona-chat-history",dp=30*1e3,pp={"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 up(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 p=(s=pp[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${p}`,{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 gp(e){var r,t,n,s,o,a,i,p,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:(p=(i=e.persist)==null?void 0:i.focusInput)!=null?p:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function mp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ds=e=>!e||typeof e!="object"?{}:{...e},sc=e=>e.map(r=>({...r,streaming:!1})),ac=(e,r,t)=>{let n=e!=null&&e.markdown?xr(e.markdown):null,s=Xr(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,d;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 p;return e!=null&&e.postprocessMessage?p=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?p=n(a):p=Yr(a),s?s(p):p}},Ns=(e,r,t)=>{var Ee,ct,Rt,Mt,Nt,Ht,dt,ut,It,gt,Ot,en,dn,Ks,Gs,Ys,Xs,Zs,Qs,ea,ta,na,ra,oa,sa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba;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=Ms(r),s=Vo.getForInstance(n.plugins);n.components&&Un.registerAll(n.components);let o=rc(),a=(Ee=n.storageAdapter)!=null?Ee:Ls(),i={},p=null,c=!1,u=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}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")p=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Ds(y.metadata)),(ct=y.messages)!=null&&ct.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=u({messages:[],metadata:{}});(Rt=l.messages)!=null&&Rt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Fr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Jo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Lr.message,Lr.messageAndClick],A=Ko({parsers:m,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let b=(Nt=(Mt=n.launcher)==null?void 0:Mt.enabled)!=null?Nt:!0,x=(dt=(Ht=n.launcher)==null?void 0:Ht.autoExpand)!=null?dt:!1,M=(ut=n.autoFocusInput)!=null?ut:!1,F=x,S=b,I=(gt=(It=n.layout)==null?void 0:It.header)==null?void 0:gt.layout,O=!1,k=b?x:!0,V=!1,ge=null,ie=()=>{V=!0,ge&&clearTimeout(ge),ge=setTimeout(()=>{V&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),V=!1)},1e4)},_=ac(n,A,ie),ne=(en=(Ot=n.features)==null?void 0:Ot.showReasoning)!=null?en:!0,Te=(Ks=(dn=n.features)==null?void 0:dn.showToolCalls)!=null?Ks:!0,le=(Ys=(Gs=n.features)==null?void 0:Gs.showEventStreamToggle)!=null?Ys:!1,de=`${(Zs=typeof n.persistState=="object"?(Xs=n.persistState)==null?void 0:Xs.keyPrefix:void 0)!=null?Zs:"persona-"}event-stream`,Y=le?new po(de):null,ce=(ta=(ea=(Qs=n.features)==null?void 0:Qs.eventStream)==null?void 0:ea.maxEvents)!=null?ta:2e3,q=le?new co(ce,Y):null,G=null,ve=!1,xe=null,Ke=0;Y==null||Y.open().then(()=>q==null?void 0:q.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Xe={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},mt=(na=n.statusIndicator)!=null?na:{},Be=l=>{var g,y,E,L;return l==="idle"?(g=mt.idleText)!=null?g:Gt.idle:l==="connecting"?(y=mt.connectingText)!=null?y:Gt.connecting:l==="connected"?(E=mt.connectedText)!=null?E:Gt.connected:l==="error"?(L=mt.errorText)!=null?L:Gt.error:Gt[l]};function rt(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:Me,panel:D}=Ol(n),se=$l(n,b),{container:te,body:z,messagesWrapper:oe,suggestions:Le,textarea:Z,sendButton:J,sendButtonWrapper:ze,composerForm:Ue,statusText:St,introTitle:qt,introSubtitle:Ut,closeButton:K,iconHolder:Ie,headerTitle:ft,headerSubtitle:yt,header:Ze,footer:it,actionsRow:Wt,leftActions:Vt,rightActions:ue}=se,T=se.micButton,Ae=se.micButtonWrapper,re=se.attachmentButton,ye=se.attachmentButtonWrapper,Ce=se.attachmentInput,Qe=se.attachmentPreviewsContainer,he=null,Pe=null,Ne=s.find(l=>l.renderHeader);if(Ne!=null&&Ne.renderHeader){let l=Ne.renderHeader({config:n,defaultRenderer:()=>{let g=qn({config:n,showClose:b});return Ar(te,g,n),g.header},onClose:()=>bt(!1,"user")});if(l){let g=te.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Ze=l)}}let ot=()=>{var g,y,E,L;if(!q)return;if(ve=!0,!G&&q&&(G=Vl({buffer:q,getFullHistory:()=>q.getAllFromStore(),onClose:()=>At(),config:n,plugins:s})),G&&(z.style.display="none",(g=it.parentNode)==null||g.insertBefore(G.element,it),G.update()),Oe){Oe.classList.remove("persona-text-persona-muted"),Oe.classList.add("persona-text-persona-accent"),Oe.style.boxShadow="inset 0 0 0 1.5px var(--persona-accent, #3b82f6)";let W=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;W&&W.split(/\s+/).forEach(P=>P&&Oe.classList.add(P))}let l=()=>{if(!ve)return;let W=Date.now();W-Ke>=200&&(G==null||G.update(),Ke=W),xe=requestAnimationFrame(l)};Ke=0,xe=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},At=()=>{var l,g,y;if(ve){if(ve=!1,G&&G.element.remove(),z.style.display="",Oe){Oe.classList.remove("persona-text-persona-accent"),Oe.classList.add("persona-text-persona-muted"),Oe.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&Oe.classList.remove(L))}xe!==null&&(cancelAnimationFrame(xe),xe=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},Oe=null;if(le){let l=(oa=(ra=n.features)==null?void 0:ra.eventStream)==null?void 0:oa.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:"");Oe=h("button",g),Oe.style.width="28px",Oe.style.height="28px",Oe.type="button",Oe.setAttribute("aria-label","Event Stream"),Oe.title="Event Stream";let y=fe("activity","18px","currentColor",1.5);y&&Oe.appendChild(y);let E=se.clearChatButtonWrapper,L=se.closeButtonWrapper,W=E||L;W&&W.parentNode===Ze?Ze.insertBefore(Oe,W):Ze.appendChild(Oe),Oe.addEventListener("click",()=>{ve?At():ot()})}let Jn=l=>{var E,L,W;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 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=((E=g.allowedTypes)!=null?E:Hn).join(","),P.multiple=((L=g.maxFiles)!=null?L:4)>1,P.style.display="none",P.setAttribute("aria-label",(W=g.buttonTooltipText)!=null?W:"Attach files"),l.appendChild(P)}},xn=s.find(l=>l.renderComposer);if(xn!=null&&xn.renderComposer){let l=n.composer,g=xn.renderComposer({config:n,defaultRenderer:()=>io({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{Ce==null||Ce.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((sa=n.voiceRecognition)==null?void 0:sa.enabled)===!0?()=>{Pe==null||Pe()}:void 0});g&&(it.replaceWith(g),it=g)}let Kn=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),W=l.querySelector("[data-persona-composer-status]");g&&(Ue=g),y&&(Z=y),E&&(J=E),L&&(T=L,Ae=L.parentElement),W&&(St=W);let P=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");P&&(Le=P);let U=l.querySelector(".persona-attachment-button");U&&(re=U,ye=U.parentElement),Ce=l.querySelector('input[type="file"]'),Qe=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(Wt=N)};Jn(it),Kn(it);let Dn=(aa=n.layout)==null?void 0:aa.contentMaxWidth;Dn&&Ue&&(Ue.style.maxWidth=Dn,Ue.style.marginLeft="auto",Ue.style.marginRight="auto"),(ia=n.attachments)!=null&&ia.enabled&&Ce&&Qe&&(he=Sr.fromConfig(n.attachments),he.setPreviewsContainer(Qe),Ce.addEventListener("change",l=>{let g=l.target;he==null||he.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=W=>{switch(W){case"body-top":return te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return oe;case"footer-top":return Le;case"composer":return Ue;case"footer-bottom":return St;default:return null}},y=(W,P)=>{var U;switch(W){case"header-left":case"header-center":case"header-right":if(W==="header-left")Ze.insertBefore(P,Ze.firstChild);else if(W==="header-right")Ze.appendChild(P);else{let N=Ze.querySelector(".persona-flex-col");N?(U=N.parentNode)==null||U.insertBefore(P,N.nextSibling):Ze.appendChild(P)}break;case"body-top":{let N=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(P):z.insertBefore(P,z.firstChild);break}case"body-bottom":z.appendChild(P);break;case"footer-top":Le.replaceWith(P);break;case"footer-bottom":St.replaceWith(P);break;default:break}};for(let[W,P]of Object.entries(l))if(P)try{let U=P({config:n,defaultContent:()=>g(W)});U&&y(W,U)}catch(U){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${W}":`,U)}})();let Nn=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-bubble-type");W==="reasoning"?(Tr.has(L)?Tr.delete(L):Tr.add(L),zl(L,E)):W==="tool"&&(Mr.has(L)?Mr.delete(L):Mr.add(L),ql(L,E,n))};oe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nn(l))}),oe.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),Nn(l))});let Mn=new Map;oe.addEventListener("click",l=>{var P;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let W=y.getAttribute("data-action");if(W==="copy"){let N=H.getMessages().find(ae=>ae.id===L);if(N&&Xe.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).then(()=>{y.classList.add("persona-message-action-success");let be=fe("check",14,"currentColor",2);be&&(y.innerHTML="",y.appendChild(be)),setTimeout(()=>{y.classList.remove("persona-message-action-success");let we=fe("copy",14,"currentColor",2);we&&(y.innerHTML="",y.appendChild(we))},2e3)}).catch(be=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to copy message:",be)}),Xe.onCopy(N)}}else if(W==="upvote"||W==="downvote")if(((P=Mn.get(L))!=null?P:null)===W)Mn.delete(L),y.classList.remove("persona-message-action-active");else{let ae=W==="upvote"?"downvote":"upvote",be=E.querySelector(`[data-action="${ae}"]`);be&&be.classList.remove("persona-message-action-active"),Mn.set(L,W),y.classList.add("persona-message-action-active");let We=H.getMessages().find(Se=>Se.id===L);We&&Xe.onFeedback&&Xe.onFeedback({type:W,messageId:We.id,message:We})}}),oe.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let W=y.getAttribute("data-approval-action");if(!W)return;let P=W==="approve"?"approved":"denied",N=H.getMessages().find(be=>be.id===L);if(!(N!=null&&N.approval))return;let ae=E.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(we=>{we.disabled=!0,we.style.opacity="0.5",we.style.cursor="not-allowed"}),H.resolveApproval(N.approval,P)});let et=null,X=null,an={artifacts:[],selectedId:null},rn=!1,Wr={current:null};oe.addEventListener("click",l=>{var we,We,Se,R,He;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((Se=(We=(we=n.features)==null?void 0:we.artifacts)==null?void 0:We.onArtifactAction)==null?void 0:Se.call(We,{type:"download",artifactId:E}))===!0)return;let W=H.getArtifactById(E),P=W==null?void 0:W.markdown,U=(W==null?void 0:W.title)||"artifact";if(!P){let Re=y.closest("[data-open-artifact]"),pe=Re==null?void 0:Re.closest("[data-message-id]"),De=pe==null?void 0:pe.getAttribute("data-message-id");if(De){let Je=H.getMessages().find(me=>me.id===De);if(Je!=null&&Je.rawContent)try{let me=JSON.parse(Je.rawContent);P=(R=me==null?void 0:me.props)==null?void 0:R.markdown,U=((He=me==null?void 0:me.props)==null?void 0:He.title)||U}catch{}}}if(!P)return;let N=new Blob([P],{type:"text/markdown"}),ae=URL.createObjectURL(N),be=document.createElement("a");be.href=ae,be.download=`${U}.md`,be.click(),URL.revokeObjectURL(ae)}),oe.addEventListener("click",l=>{var W,P,U;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((U=(P=(W=n.features)==null?void 0:W.artifacts)==null?void 0:P.onArtifactAction)==null?void 0:U.call(P,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),Cn())}),oe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let vn=null,ht=null,ln=null,kn=null,Rr=()=>{};function dr(){kn==null||kn(),kn=null}let Hr=()=>{var P;if(!vn||!ht)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){ht.style.removeProperty("position"),ht.style.removeProperty("left"),ht.style.removeProperty("top"),ht.style.removeProperty("bottom"),ht.style.removeProperty("width"),ht.style.removeProperty("z-index");return}let E=vn.firstElementChild;if(!E||E===ht)return;let L=10;ht.style.position="absolute",ht.style.top="0",ht.style.bottom="0",ht.style.width=`${L}px`,ht.style.zIndex="5";let W=E.offsetWidth-L/2;ht.style.left=`${Math.max(0,W)}px`},Gn=()=>{},Cn=()=>{var y,E,L,W,P;if(!et||!un(n))return;qo(e,n),Uo(e,n),Gn();let l=(W=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?W:520,g=D.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),et.update(an),rn?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(P=et.backdrop)==null||P.classList.add("persona-hidden")):an.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),Rr()};if(un(n)){D.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(te),et=Gl(n,{onSelect:y=>{var E;return(E=Wr.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{rn=!0,Cn()}}),et.element.classList.add("persona-hidden"),vn=g,g.appendChild(l),g.appendChild(et.element),et.backdrop&&D.appendChild(et.backdrop),D.appendChild(g),Rr=()=>{var E,L,W,P;if(!vn||!et)return;if(!(((W=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:W.resizable)===!0)){ln==null||ln(),ln=null,dr(),ht&&(ht.remove(),ht=null),et.element.style.removeProperty("width"),et.element.style.removeProperty("maxWidth");return}if(!ht){let U=h("div","persona-artifact-split-handle persona-shrink-0 persona-h-full");U.setAttribute("role","separator"),U.setAttribute("aria-orientation","vertical"),U.setAttribute("aria-label","Resize artifacts panel"),U.tabIndex=0;let N=e.ownerDocument,ae=(P=N.defaultView)!=null?P:window,be=we=>{var pe,De;if(!et||we.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;we.preventDefault(),dr();let We=we.clientX,Se=et.element.getBoundingClientRect().width,R=(De=(pe=n.features)==null?void 0:pe.artifacts)==null?void 0:De.layout,He=lt=>{let Je=vn.getBoundingClientRect().width,me=e.classList.contains("persona-artifact-appearance-seamless"),Bt=me?0:Ql(vn,ae),pt=me?0:U.getBoundingClientRect().width||6,tn=Se-(lt.clientX-We),Jt=ec(tn,Je,Bt,pt,R==null?void 0:R.resizableMinWidth,R==null?void 0:R.resizableMaxWidth);et.element.style.width=`${Jt}px`,et.element.style.maxWidth="none",Hr()},Re=()=>{N.removeEventListener("pointermove",He),N.removeEventListener("pointerup",Re),N.removeEventListener("pointercancel",Re),kn=null;try{U.releasePointerCapture(we.pointerId)}catch{}};kn=Re,N.addEventListener("pointermove",He),N.addEventListener("pointerup",Re),N.addEventListener("pointercancel",Re);try{U.setPointerCapture(we.pointerId)}catch{}};U.addEventListener("pointerdown",be),ht=U,vn.insertBefore(U,et.element),ln=()=>{U.removeEventListener("pointerdown",be)}}if(ht){let U=an.artifacts.length>0&&!rn;ht.classList.toggle("persona-hidden",!U),Hr()}},Gn=()=>{var ae,be,we,We,Se,R,He,Re,pe,De,lt,Je,me,Bt;if(!b||!et||((be=(ae=n.launcher)==null?void 0:ae.sidebarMode)!=null?be:!1)||zt(n)&&hn(n).reveal==="emerge")return;let E=(we=e.ownerDocument.defaultView)!=null?we:window,L=(Se=(We=n.launcher)==null?void 0:We.mobileFullscreen)!=null?Se:!0,W=(He=(R=n.launcher)==null?void 0:R.mobileBreakpoint)!=null?He:640;if(L&&E.innerWidth<=W||!Zl(n,b))return;let P=(De=(pe=(Re=n.launcher)==null?void 0:Re.width)!=null?pe:n.launcherWidth)!=null?De:"min(400px, calc(100vw - 24px))",U=(Bt=(me=(Je=(lt=n.features)==null?void 0:lt.artifacts)==null?void 0:Je.layout)==null?void 0:me.expandedPanelWidth)!=null?Bt:"min(720px, calc(100vw - 24px))";an.artifacts.length>0&&!rn?(D.style.width=U,D.style.maxWidth=U):(D.style.width=P,D.style.maxWidth=P)},typeof ResizeObserver!="undefined"&&(X=new ResizeObserver(()=>{Cn()}),X.observe(D))}else D.appendChild(te);e.appendChild(Me);let Yn=()=>{var pt,tn,Jt,Xt,$t,pn,Ge,wt,So,Ao,Eo,To,Mo,os,ss,Pt,ko,Vr,Jr,br,Lo,jn;let l=zt(n),g=(tn=(pt=n.launcher)==null?void 0:pt.sidebarMode)!=null?tn:!1,y=l||g||((Xt=(Jt=n.launcher)==null?void 0:Jt.fullHeight)!=null?Xt:!1),E=(($t=n.launcher)==null?void 0:$t.enabled)===!1,L=(Ge=(pn=n.theme)==null?void 0:pn.components)==null?void 0:Ge.panel,W=Fo(n),P=(Kt,Ft)=>{var An;return Kt==null||Kt===""?Ft:(An=no(W,Kt))!=null?An:Kt},U=(wt=e.ownerDocument.defaultView)!=null?wt:window,N=(Ao=(So=n.launcher)==null?void 0:So.mobileFullscreen)!=null?Ao:!0,ae=(To=(Eo=n.launcher)==null?void 0:Eo.mobileBreakpoint)!=null?To:640,be=U.innerWidth<=ae,we=N&&be&&b,We=(os=(Mo=n.launcher)==null?void 0:Mo.position)!=null?os:"bottom-left",Se=We==="bottom-left"||We==="top-left",R=(Pt=(ss=n.launcher)==null?void 0:ss.zIndex)!=null?Pt:9999,He=g||we?"none":"1px solid var(--persona-border)",Re=we?"none":g?Se?"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&&!we&&(Re="none",He="none");let pe=g||we?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",De=P(L==null?void 0:L.border,He),lt=P(L==null?void 0:L.shadow,Re),Je=P(L==null?void 0:L.borderRadius,pe);if(e.style.cssText="",Me.style.cssText="",D.style.cssText="",te.style.cssText="",z.style.cssText="",it.style.cssText="",we){Me.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"),Me.style.cssText=`
20
+ `,k.addEventListener("click",()=>{d=O,x.forEach((U,ue)=>{let ie=ue<O;U.classList.toggle("selected",ie),U.setAttribute("aria-checked",ue===O-1?"true":"false")})}),x.push(k),b.appendChild(k)}f.appendChild(b);let M=null;if(p){let O=document.createElement("div");O.className="persona-feedback-comment-container",M=document.createElement("textarea"),M.className="persona-feedback-comment",M.placeholder=o,M.rows=3,M.setAttribute("aria-label","Additional comments"),O.appendChild(M),f.appendChild(O)}let F=document.createElement("div");F.className="persona-feedback-actions";let S=document.createElement("button");S.type="button",S.className="persona-feedback-btn persona-feedback-btn-skip",S.textContent=i,S.addEventListener("click",()=>{t==null||t(),u.remove()});let I=document.createElement("button");return I.type="button",I.className="persona-feedback-btn persona-feedback-btn-submit",I.textContent=a,I.addEventListener("click",async()=>{if(d===null){b.classList.add("persona-feedback-shake"),setTimeout(()=>b.classList.remove("persona-feedback-shake"),500);return}I.disabled=!0,I.textContent="Submitting...";try{let O=(M==null?void 0:M.value.trim())||void 0;await r(d,O),u.remove()}catch(O){I.disabled=!1,I.textContent=a,console.error("[CSAT Feedback] Failed to submit:",O)}}),F.appendChild(S),F.appendChild(I),f.appendChild(F),u.appendChild(f),u}function Bs(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:p=!0,lowLabel:c="Not likely",highLabel:u="Very likely"}=e,d=document.createElement("div");d.className="persona-feedback-container persona-feedback-nps",d.setAttribute("role","dialog"),d.setAttribute("aria-label","Net Promoter Score feedback");let f=null,m=document.createElement("div");m.className="persona-feedback-content";let v=document.createElement("div");v.className="persona-feedback-header";let A=document.createElement("h3");A.className="persona-feedback-title",A.textContent=n,v.appendChild(A);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=s,v.appendChild(b),m.appendChild(v);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 M=document.createElement("div");M.className="persona-feedback-labels";let F=document.createElement("span");F.className="persona-feedback-label-low",F.textContent=c;let S=document.createElement("span");S.className="persona-feedback-label-high",S.textContent=u,M.appendChild(F),M.appendChild(S);let I=document.createElement("div");I.className="persona-feedback-numbers";let O=[];for(let _=0;_<=10;_++){let ne=document.createElement("button");ne.type="button",ne.className="persona-feedback-rating-btn persona-feedback-number-btn",ne.setAttribute("role","radio"),ne.setAttribute("aria-checked","false"),ne.setAttribute("aria-label",`Rating ${_} out of 10`),ne.textContent=String(_),ne.dataset.rating=String(_),_<=6?ne.classList.add("persona-feedback-detractor"):_<=8?ne.classList.add("persona-feedback-passive"):ne.classList.add("persona-feedback-promoter"),ne.addEventListener("click",()=>{f=_,O.forEach((Me,le)=>{Me.classList.toggle("selected",le===_),Me.setAttribute("aria-checked",le===_?"true":"false")})}),O.push(ne),I.appendChild(ne)}x.appendChild(M),x.appendChild(I),m.appendChild(x);let k=null;if(p){let _=document.createElement("div");_.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"),_.appendChild(k),m.appendChild(_)}let U=document.createElement("div");U.className="persona-feedback-actions";let ue=document.createElement("button");ue.type="button",ue.className="persona-feedback-btn persona-feedback-btn-skip",ue.textContent=i,ue.addEventListener("click",()=>{t==null||t(),d.remove()});let ie=document.createElement("button");return ie.type="button",ie.className="persona-feedback-btn persona-feedback-btn-submit",ie.textContent=a,ie.addEventListener("click",async()=>{if(f===null){I.classList.add("persona-feedback-shake"),setTimeout(()=>I.classList.remove("persona-feedback-shake"),500);return}ie.disabled=!0,ie.textContent="Submitting...";try{let _=(k==null?void 0:k.value.trim())||void 0;await r(f,_),d.remove()}catch(_){ie.disabled=!1,ie.textContent=a,console.error("[NPS Feedback] Failed to submit:",_)}}),U.appendChild(ue),U.appendChild(ie),m.appendChild(U),d.appendChild(m),d}var Wr="persona-chat-history",dp=30*1e3,pp={"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 up(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 p=(s=pp[i.type])!=null?s:"png";r.push(new File([i],`clipboard-image-${Date.now()}.${p}`,{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 gp(e){var r,t,n,s,o,a,i,p,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:(p=(i=e.persist)==null?void 0:i.focusInput)!=null?p:!0},clearOnChatClear:(c=e.clearOnChatClear)!=null?c:!0}:null}function mp(e){try{let r=e==="local"?localStorage:sessionStorage,t="__persist_test__";return r.setItem(t,"1"),r.removeItem(t),r}catch{return null}}var Ds=e=>!e||typeof e!="object"?{}:{...e},sc=e=>e.map(r=>({...r,streaming:!1})),ac=(e,r,t)=>{let n=e!=null&&e.markdown?Cr(e.markdown):null,s=Xr(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,d;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 p;return e!=null&&e.postprocessMessage?p=e.postprocessMessage({...o,text:a,raw:(d=i!=null?i:o.text)!=null?d:""}):n?p=n(a):p=Yr(a),s?s(p):p}},Ns=(e,r,t)=>{var Te,lt,Rt,Mt,Nt,Ht,ct,ut,It,gt,Ot,nn,un,Ks,Gs,Ys,Xs,Zs,Qs,ea,ta,na,ra,oa,sa,aa,ia,la,ca,da,pa,ua,ga,ma,fa,ha,ya,ba;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=Ms(r),s=Uo.getForInstance(n.plugins);n.components&&Kn.registerAll(n.components);let o=rc(),a=(Te=n.storageAdapter)!=null?Te:Ls(),i={},p=null,c=!1,u=l=>{if(n.onStateLoaded)try{let g=n.onStateLoaded(l);if(g&&typeof g=="object"&&"state"in g){let{state:y,open:E}=g;return E&&(c=!0),y}return g}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")p=l.then(g=>{let y=g!=null?g:{messages:[],metadata:{}};return u(y)});else{let g=l!=null?l:{messages:[],metadata:{}},y=u(g);y.metadata&&(i=Ds(y.metadata)),(lt=y.messages)!=null&&lt.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=u({messages:[],metadata:{}});(Rt=l.messages)!=null&&Rt.length&&(n={...n,initialMessages:l.messages})}catch(l){typeof console!="undefined"&&console.error("[AgentWidget] onStateLoaded hook failed:",l)}let d=()=>i,f=l=>{var y;i=(y=l({...i}))!=null?y:{},Fr()},m=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Jo],v=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Pr.message,Pr.messageAndClick],A=Ko({parsers:m,handlers:v,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null});A.syncFromMetadata();let b=(Nt=(Mt=n.launcher)==null?void 0:Mt.enabled)!=null?Nt:!0,x=(ct=(Ht=n.launcher)==null?void 0:Ht.autoExpand)!=null?ct:!1,M=(ut=n.autoFocusInput)!=null?ut:!1,F=x,S=b,I=(gt=(It=n.layout)==null?void 0:It.header)==null?void 0:gt.layout,O=!1,k=b?x:!0,U=!1,ue=null,ie=()=>{U=!0,ue&&clearTimeout(ue),ue=setTimeout(()=>{U&&(typeof console!="undefined"&&console.warn("[AgentWidget] Resubmit requested but no injection occurred within 10s"),U=!1)},1e4)},_=ac(n,A,ie),ne=(nn=(Ot=n.features)==null?void 0:Ot.showReasoning)!=null?nn:!0,Me=(Ks=(un=n.features)==null?void 0:un.showToolCalls)!=null?Ks:!0,le=(Ys=(Gs=n.features)==null?void 0:Gs.showEventStreamToggle)!=null?Ys:!1,de=`${(Zs=typeof n.persistState=="object"?(Xs=n.persistState)==null?void 0:Xs.keyPrefix:void 0)!=null?Zs:"persona-"}event-stream`,Y=le?new po(de):null,ce=(ta=(ea=(Qs=n.features)==null?void 0:Qs.eventStream)==null?void 0:ea.maxEvents)!=null?ta:2e3,q=le?new co(ce,Y):null,K=null,Ce=!1,ve=null,Ge=0;Y==null||Y.open().then(()=>q==null?void 0:q.restore()).catch(l=>{n.debug&&console.warn("[AgentWidget] IndexedDB not available for event stream:",l)});let Ze={onCopy:l=>{var g,y;o.emit("message:copy",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.id,"copy").catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit copy feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onCopy)==null||y.call(g,l)},onFeedback:l=>{var g,y;o.emit("message:feedback",l),H!=null&&H.isClientTokenMode()&&H.submitMessageFeedback(l.messageId,l.type).catch(E=>{n.debug&&console.error("[AgentWidget] Failed to submit feedback:",E)}),(y=(g=n.messageActions)==null?void 0:g.onFeedback)==null||y.call(g,l)}},ft=(na=n.statusIndicator)!=null?na:{},We=l=>{var g,y,E,L;return l==="idle"?(g=ft.idleText)!=null?g:Gt.idle:l==="connecting"?(y=ft.connectingText)!=null?y:Gt.connecting:l==="connected"?(E=ft.connectedText)!=null?E:Gt.connected:l==="error"?(L=ft.errorText)!=null?L:Gt.error:Gt[l]};function nt(l,g,y,E){if(E==="idle"&&y.idleLink){l.textContent="";let L=document.createElement("a");L.href=y.idleLink,L.target="_blank",L.rel="noopener noreferrer",L.textContent=g,L.style.color="inherit",L.style.textDecoration="none",l.appendChild(L)}else l.textContent=g}let{wrapper:ke,panel:D}=Ol(n),se=$l(n,b),{container:te,body:z,messagesWrapper:oe,suggestions:Ie,textarea:Z,sendButton:G,sendButtonWrapper:je,composerForm:Ue,statusText:St,introTitle:jt,introSubtitle:zt,closeButton:J,iconHolder:Pe,headerTitle:ht,headerSubtitle:yt,header:Qe,footer:it,actionsRow:Wt,leftActions:qt,rightActions:pe}=se,T=se.micButton,Ee=se.micButtonWrapper,re=se.attachmentButton,be=se.attachmentButtonWrapper,we=se.attachmentInput,ze=se.attachmentPreviewsContainer,fe=null,Re=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 Tr(te,g,n),g.header},onClose:()=>bt(!1,"user")});if(l){let g=te.querySelector(".persona-border-b-persona-divider");g&&(g.replaceWith(l),Qe=l)}}let rt=()=>{var g,y,E,L;if(!q)return;if(Ce=!0,!K&&q&&(K=Ul({buffer:q,getFullHistory:()=>q.getAllFromStore(),onClose:()=>At(),config:n,plugins:s})),K&&(z.style.display="none",(g=it.parentNode)==null||g.insertBefore(K.element,it),K.update()),_e){_e.style.boxShadow=`inset 0 0 0 1.5px ${sn.actionIconColor}`;let P=(L=(E=(y=n.features)==null?void 0:y.eventStream)==null?void 0:E.classNames)==null?void 0:L.toggleButtonActive;P&&P.split(/\s+/).forEach(R=>R&&_e.classList.add(R))}let l=()=>{if(!Ce)return;let P=Date.now();P-Ge>=200&&(K==null||K.update(),Ge=P),ve=requestAnimationFrame(l)};Ge=0,ve=requestAnimationFrame(l),o.emit("eventStream:opened",{timestamp:Date.now()})},At=()=>{var l,g,y;if(Ce){if(Ce=!1,K&&K.element.remove(),z.style.display="",_e){_e.style.boxShadow="";let E=(y=(g=(l=n.features)==null?void 0:l.eventStream)==null?void 0:g.classNames)==null?void 0:y.toggleButtonActive;E&&E.split(/\s+/).forEach(L=>L&&_e.classList.remove(L))}ve!==null&&(cancelAnimationFrame(ve),ve=null),o.emit("eventStream:closed",{timestamp:Date.now()})}},_e=null;if(le){let l=(oa=(ra=n.features)==null?void 0:ra.eventStream)==null?void 0:oa.classNames,g="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(l!=null&&l.toggleButton?" "+l.toggleButton:"");_e=h("button",g),_e.style.width="28px",_e.style.height="28px",_e.style.color=sn.actionIconColor,_e.type="button",_e.setAttribute("aria-label","Event Stream"),_e.title="Event Stream";let y=me("activity","18px","currentColor",1.5);y&&_e.appendChild(y);let E=se.clearChatButtonWrapper,L=se.closeButtonWrapper,P=E||L;P&&P.parentNode===Qe?Qe.insertBefore(_e,P):Qe.appendChild(_e),_e.addEventListener("click",()=>{Ce?At():rt()})}let Yn=l=>{var E,L,P;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 R=l.querySelector("[data-persona-composer-form]");R!=null&&R.parentNode?R.parentNode.insertBefore(y,R):l.insertBefore(y,l.firstChild)}if(!l.querySelector('input[type="file"]')){let R=h("input");R.type="file",R.accept=((E=g.allowedTypes)!=null?E:Dn).join(","),R.multiple=((L=g.maxFiles)!=null?L:4)>1,R.style.display="none",R.setAttribute("aria-label",(P=g.buttonTooltipText)!=null?P:"Attach files"),l.appendChild(R)}},Sn=s.find(l=>l.renderComposer);if(Sn!=null&&Sn.renderComposer){let l=n.composer,g=Sn.renderComposer({config:n,defaultRenderer:()=>io({config:n}).footer,onSubmit:y=>{H&&!H.isStreaming()&&H.sendMessage(y)},streaming:!1,disabled:!1,openAttachmentPicker:()=>{we==null||we.click()},models:l==null?void 0:l.models,selectedModelId:l==null?void 0:l.selectedModelId,onModelChange:y=>{n.composer={...n.composer,selectedModelId:y}},onVoiceToggle:((sa=n.voiceRecognition)==null?void 0:sa.enabled)===!0?()=>{Re==null||Re()}:void 0});g&&(it.replaceWith(g),it=g)}let Xn=l=>{let g=l.querySelector("[data-persona-composer-form]"),y=l.querySelector("[data-persona-composer-input]"),E=l.querySelector("[data-persona-composer-submit]"),L=l.querySelector("[data-persona-composer-mic]"),P=l.querySelector("[data-persona-composer-status]");g&&(Ue=g),y&&(Z=y),E&&(G=E),L&&(T=L,Ee=L.parentElement),P&&(St=P);let R=l.querySelector(".persona-mb-3.persona-flex.persona-flex-wrap.persona-gap-2");R&&(Ie=R);let V=l.querySelector(".persona-attachment-button");V&&(re=V,be=V.parentElement),we=l.querySelector('input[type="file"]'),ze=l.querySelector(".persona-attachment-previews");let N=l.querySelector(".persona-widget-composer .persona-flex.persona-items-center.persona-justify-between");N&&(Wt=N)};Yn(it),Xn(it);let An=(aa=n.layout)==null?void 0:aa.contentMaxWidth;An&&Ue&&(Ue.style.maxWidth=An,Ue.style.marginLeft="auto",Ue.style.marginRight="auto"),An&&ze&&(ze.style.maxWidth=An,ze.style.marginLeft="auto",ze.style.marginRight="auto"),(ia=n.attachments)!=null&&ia.enabled&&we&&ze&&(fe=Er.fromConfig(n.attachments),fe.setPreviewsContainer(ze),we.addEventListener("change",l=>{let g=l.target;fe==null||fe.handleFileSelect(g.files),g.value=""})),(()=>{var E,L;let l=(L=(E=n.layout)==null?void 0:E.slots)!=null?L:{},g=P=>{switch(P){case"body-top":return te.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6")||null;case"messages":return oe;case"footer-top":return Ie;case"composer":return Ue;case"footer-bottom":return St;default:return null}},y=(P,R)=>{var V;switch(P){case"header-left":case"header-center":case"header-right":if(P==="header-left")Qe.insertBefore(R,Qe.firstChild);else if(P==="header-right")Qe.appendChild(R);else{let N=Qe.querySelector(".persona-flex-col");N?(V=N.parentNode)==null||V.insertBefore(R,N.nextSibling):Qe.appendChild(R)}break;case"body-top":{let N=z.querySelector(".persona-rounded-2xl.persona-bg-persona-surface.persona-p-6");N?N.replaceWith(R):z.insertBefore(R,z.firstChild);break}case"body-bottom":z.appendChild(R);break;case"footer-top":Ie.replaceWith(R);break;case"footer-bottom":St.replaceWith(R);break;default:break}};for(let[P,R]of Object.entries(l))if(R)try{let V=R({config:n,defaultContent:()=>g(P)});V&&y(P,V)}catch(V){typeof console!="undefined"&&console.error(`[AgentWidget] Error rendering slot "${P}":`,V)}})();let On=l=>{let y=l.target.closest('button[data-expand-header="true"]');if(!y)return;let E=y.closest(".vanilla-reasoning-bubble, .vanilla-tool-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let P=y.getAttribute("data-bubble-type");P==="reasoning"?(kr.has(L)?kr.delete(L):kr.add(L),zl(L,E)):P==="tool"&&(Lr.has(L)?Lr.delete(L):Lr.add(L),ql(L,E,n))};oe.addEventListener("pointerdown",l=>{l.target.closest('button[data-expand-header="true"]')&&(l.preventDefault(),On(l))}),oe.addEventListener("keydown",l=>{let g=l.target;(l.key==="Enter"||l.key===" ")&&g.closest('button[data-expand-header="true"]')&&(l.preventDefault(),On(l))});let Pn=new Map;oe.addEventListener("click",l=>{var R;let y=l.target.closest(".persona-message-action-btn[data-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest("[data-actions-for]");if(!E)return;let L=E.getAttribute("data-actions-for");if(!L)return;let P=y.getAttribute("data-action");if(P==="copy"){let N=H.getMessages().find(ae=>ae.id===L);if(N&&Ze.onCopy){let ae=N.content||"";navigator.clipboard.writeText(ae).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)}),Ze.onCopy(N)}}else if(P==="upvote"||P==="downvote")if(((R=Pn.get(L))!=null?R:null)===P)Pn.delete(L),y.classList.remove("persona-message-action-active");else{let ae=P==="upvote"?"downvote":"upvote",he=E.querySelector(`[data-action="${ae}"]`);he&&he.classList.remove("persona-message-action-active"),Pn.set(L,P),y.classList.add("persona-message-action-active");let xe=H.getMessages().find(Ve=>Ve.id===L);xe&&Ze.onFeedback&&Ze.onFeedback({type:P,messageId:xe.id,message:xe})}}),oe.addEventListener("click",l=>{let y=l.target.closest("button[data-approval-action]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.closest(".vanilla-approval-bubble");if(!E)return;let L=E.getAttribute("data-message-id");if(!L)return;let P=y.getAttribute("data-approval-action");if(!P)return;let R=P==="approve"?"approved":"denied",N=H.getMessages().find(he=>he.id===L);if(!(N!=null&&N.approval))return;let ae=E.querySelector("[data-approval-buttons]");ae&&ae.querySelectorAll("button").forEach(Se=>{Se.disabled=!0,Se.style.opacity="0.5",Se.style.cursor="not-allowed"}),H.resolveApproval(N.approval,R)});let et=null,an=null,fn={artifacts:[],selectedId:null},en=!1,$n={current:null};oe.addEventListener("click",l=>{var Se,xe,Ve,W,Oe;let y=l.target.closest("[data-download-artifact]");if(!y)return;l.preventDefault(),l.stopPropagation();let E=y.getAttribute("data-download-artifact");if(!E||((Ve=(xe=(Se=n.features)==null?void 0:Se.artifacts)==null?void 0:xe.onArtifactAction)==null?void 0:Ve.call(xe,{type:"download",artifactId:E}))===!0)return;let P=H.getArtifactById(E),R=P==null?void 0:P.markdown,V=(P==null?void 0:P.title)||"artifact";if(!R){let Ae=y.closest("[data-open-artifact]"),ye=Ae==null?void 0:Ae.closest("[data-message-id]"),He=ye==null?void 0:ye.getAttribute("data-message-id");if(He){let Ke=H.getMessages().find(ge=>ge.id===He);if(Ke!=null&&Ke.rawContent)try{let ge=JSON.parse(Ke.rawContent);R=(W=ge==null?void 0:ge.props)==null?void 0:W.markdown,V=((Oe=ge==null?void 0:ge.props)==null?void 0:Oe.title)||V}catch{}}}if(!R)return;let N=new Blob([R],{type:"text/markdown"}),ae=URL.createObjectURL(N),he=document.createElement("a");he.href=ae,he.download=`${V}.md`,he.click(),URL.revokeObjectURL(ae)}),oe.addEventListener("click",l=>{var P,R,V;let y=l.target.closest("[data-open-artifact]");if(!y)return;let E=y.getAttribute("data-open-artifact");!E||((V=(R=(P=n.features)==null?void 0:P.artifacts)==null?void 0:R.onArtifactAction)==null?void 0:V.call(R,{type:"open",artifactId:E}))===!0||(l.preventDefault(),l.stopPropagation(),H.selectArtifact(E),En())}),oe.addEventListener("keydown",l=>{if(l.key!=="Enter"&&l.key!==" ")return;let g=l.target;g.hasAttribute("data-open-artifact")&&(l.preventDefault(),g.click())});let ln=null,dt=null,Yt=null,X=null,Wn=()=>{};function Fn(){X==null||X(),X=null}let Hr=()=>{var R;if(!ln||!dt)return;let l=e.classList.contains("persona-artifact-appearance-seamless"),y=((R=e.ownerDocument.defaultView)!=null?R: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 E=ln.firstElementChild;if(!E||E===dt)return;let L=10;dt.style.position="absolute",dt.style.top="0",dt.style.bottom="0",dt.style.width=`${L}px`,dt.style.zIndex="5";let P=E.offsetWidth-L/2;dt.style.left=`${Math.max(0,P)}px`},Zn=()=>{},En=()=>{var y,E,L,P,R;if(!et||!mn(n))return;qo(e,n),Vo(e,n),Zn();let l=(P=(L=(E=(y=n.features)==null?void 0:y.artifacts)==null?void 0:E.layout)==null?void 0:L.narrowHostMaxWidth)!=null?P:520,g=D.getBoundingClientRect().width||0;e.classList.toggle("persona-artifact-narrow-host",g>0&&g<=l),et.update(fn),en?(et.setMobileOpen(!1),et.element.classList.add("persona-hidden"),(R=et.backdrop)==null||R.classList.add("persona-hidden")):fn.artifacts.length>0&&(et.element.classList.remove("persona-hidden"),et.setMobileOpen(!0)),Wn()};if(mn(n)){D.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(te),et=Gl(n,{onSelect:y=>{var E;return(E=$n.current)==null?void 0:E.selectArtifact(y)},onDismiss:()=>{en=!0,En()}}),et.element.classList.add("persona-hidden"),ln=g,g.appendChild(l),g.appendChild(et.element),et.backdrop&&D.appendChild(et.backdrop),D.appendChild(g),Wn=()=>{var E,L,P,R;if(!ln||!et)return;if(!(((P=(L=(E=n.features)==null?void 0:E.artifacts)==null?void 0:L.layout)==null?void 0:P.resizable)===!0)){Yt==null||Yt(),Yt=null,Fn(),dt&&(dt.remove(),dt=null),et.element.style.removeProperty("width"),et.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 N=e.ownerDocument,ae=(R=N.defaultView)!=null?R:window,he=Se=>{var ye,He;if(!et||Se.button!==0||e.classList.contains("persona-artifact-narrow-host")||ae.innerWidth<=640)return;Se.preventDefault(),Fn();let xe=Se.clientX,Ve=et.element.getBoundingClientRect().width,W=(He=(ye=n.features)==null?void 0:ye.artifacts)==null?void 0:He.layout,Oe=mt=>{let Ke=ln.getBoundingClientRect().width,ge=e.classList.contains("persona-artifact-appearance-seamless"),Bt=ge?0:Ql(ln,ae),pt=ge?0:V.getBoundingClientRect().width||6,rn=Ve-(mt.clientX-xe),Vt=ec(rn,Ke,Bt,pt,W==null?void 0:W.resizableMinWidth,W==null?void 0:W.resizableMaxWidth);et.element.style.width=`${Vt}px`,et.element.style.maxWidth="none",Hr()},Ae=()=>{N.removeEventListener("pointermove",Oe),N.removeEventListener("pointerup",Ae),N.removeEventListener("pointercancel",Ae),X=null;try{V.releasePointerCapture(Se.pointerId)}catch{}};X=Ae,N.addEventListener("pointermove",Oe),N.addEventListener("pointerup",Ae),N.addEventListener("pointercancel",Ae);try{V.setPointerCapture(Se.pointerId)}catch{}};V.addEventListener("pointerdown",he),dt=V,ln.insertBefore(V,et.element),Yt=()=>{V.removeEventListener("pointerdown",he)}}if(dt){let V=fn.artifacts.length>0&&!en;dt.classList.toggle("persona-hidden",!V),Hr()}},Zn=()=>{var ae,he,Se,xe,Ve,W,Oe,Ae,ye,He,mt,Ke,ge,Bt;if(!b||!et||((he=(ae=n.launcher)==null?void 0:ae.sidebarMode)!=null?he:!1)||_t(n)&&Cn(n).reveal==="emerge")return;let E=(Se=e.ownerDocument.defaultView)!=null?Se:window,L=(Ve=(xe=n.launcher)==null?void 0:xe.mobileFullscreen)!=null?Ve:!0,P=(Oe=(W=n.launcher)==null?void 0:W.mobileBreakpoint)!=null?Oe:640;if(L&&E.innerWidth<=P||!Zl(n,b))return;let R=(He=(ye=(Ae=n.launcher)==null?void 0:Ae.width)!=null?ye:n.launcherWidth)!=null?He:"min(400px, calc(100vw - 24px))",V=(Bt=(ge=(Ke=(mt=n.features)==null?void 0:mt.artifacts)==null?void 0:Ke.layout)==null?void 0:ge.expandedPanelWidth)!=null?Bt:"min(720px, calc(100vw - 24px))";fn.artifacts.length>0&&!en?(D.style.width=V,D.style.maxWidth=V):(D.style.width=R,D.style.maxWidth=R)},typeof ResizeObserver!="undefined"&&(an=new ResizeObserver(()=>{En()}),an.observe(D))}else D.appendChild(te);e.appendChild(ke);let Qn=()=>{var pt,rn,Vt,Zt,$t,gn,Ye,wt,So,Ao,Eo,To,Mo,os,ss,Pt,ko,Ur,Jr,vr,Lo,Vn;let l=_t(n),g=(rn=(pt=n.launcher)==null?void 0:pt.sidebarMode)!=null?rn:!1,y=l||g||((Zt=(Vt=n.launcher)==null?void 0:Vt.fullHeight)!=null?Zt:!1),E=(($t=n.launcher)==null?void 0:$t.enabled)===!1,L=(Ye=(gn=n.theme)==null?void 0:gn.components)==null?void 0:Ye.panel,P=Fo(n),R=(Ut,Jt)=>{var kn;return Ut==null||Ut===""?Jt:(kn=no(P,Ut))!=null?kn:Ut},V=(wt=e.ownerDocument.defaultView)!=null?wt:window,N=(Ao=(So=n.launcher)==null?void 0:So.mobileFullscreen)!=null?Ao:!0,ae=(To=(Eo=n.launcher)==null?void 0:Eo.mobileBreakpoint)!=null?To:640,he=V.innerWidth<=ae,Se=N&&he&&b,xe=(os=(Mo=n.launcher)==null?void 0:Mo.position)!=null?os:"bottom-left",Ve=xe==="bottom-left"||xe==="top-left",W=(Pt=(ss=n.launcher)==null?void 0:ss.zIndex)!=null?Pt:9999,Oe=g||Se?"none":"1px solid var(--persona-border)",Ae=Se?"none":g?Ve?"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&&(Ae="none",Oe="none");let ye=g||Se?"0":"var(--persona-panel-radius, var(--persona-radius-xl, 0.75rem))",He=R(L==null?void 0:L.border,Oe),mt=R(L==null?void 0:L.shadow,Ae),Ke=R(L==null?void 0:L.borderRadius,ye);if(e.style.cssText="",ke.style.cssText="",D.style.cssText="",te.style.cssText="",z.style.cssText="",it.style.cssText="",Se){ke.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"),ke.style.cssText=`
21
21
  position: fixed !important;
22
22
  inset: 0 !important;
23
23
  width: 100% !important;
@@ -27,7 +27,7 @@ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=
27
27
  padding: 0 !important;
28
28
  display: flex !important;
29
29
  flex-direction: column !important;
30
- z-index: ${R} !important;
30
+ z-index: ${W} !important;
31
31
  background-color: var(--persona-surface, #ffffff) !important;
32
32
  `,D.style.cssText=`
33
33
  position: relative !important;
@@ -53,19 +53,19 @@ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=
53
53
  overflow: hidden !important;
54
54
  border-radius: 0 !important;
55
55
  border: none !important;
56
- `,z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0",O=!0;return}let me=(Vr=(ko=n==null?void 0:n.launcher)==null?void 0:ko.width)!=null?Vr:n==null?void 0:n.launcherWidth,Bt=me!=null?me:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(D.style.width="100%",D.style.maxWidth="100%"):(D.style.width=Bt,D.style.maxWidth=Bt);else if(l)if(hn(n).reveal==="emerge"){let Ft=hn(n).width;D.style.width=Ft,D.style.maxWidth=Ft}else D.style.width="100%",D.style.maxWidth="100%";if(Gn(),D.style.boxShadow=lt,D.style.borderRadius=Je,te.style.border=De,te.style.borderRadius=Je,l&&!we&&(L==null?void 0:L.border)===void 0&&(te.style.border="none",hn(n).side==="right"?te.style.borderLeft="1px solid var(--persona-border)":te.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",E&&(e.style.width="100%"),Me.style.display="flex",Me.style.flexDirection="column",Me.style.flex="1 1 0%",Me.style.minHeight="0",Me.style.maxHeight="100%",Me.style.height="100%",E&&(Me.style.overflow="hidden"),D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.height="100%",D.style.overflow="hidden",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0"),Me.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&&!E&&!l&&((Jr=yn[We])!=null?Jr:yn["bottom-right"]).split(" ").forEach(Ft=>Me.classList.add(Ft)),g){let Kt=(Lo=(br=n.launcher)==null?void 0:br.sidebarWidth)!=null?Lo:"420px";Me.style.cssText=`
56
+ `,z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0",O=!0;return}let ge=(Ur=(ko=n==null?void 0:n.launcher)==null?void 0:ko.width)!=null?Ur:n==null?void 0:n.launcherWidth,Bt=ge!=null?ge:"min(400px, calc(100vw - 24px))";if(!g&&!l)E&&y?(D.style.width="100%",D.style.maxWidth="100%"):(D.style.width=Bt,D.style.maxWidth=Bt);else if(l)if(Cn(n).reveal==="emerge"){let Jt=Cn(n).width;D.style.width=Jt,D.style.maxWidth=Jt}else D.style.width="100%",D.style.maxWidth="100%";if(Zn(),D.style.boxShadow=mt,D.style.borderRadius=Ke,te.style.border=He,te.style.borderRadius=Ke,l&&!Se&&(L==null?void 0:L.border)===void 0&&(te.style.border="none",Cn(n).side==="right"?te.style.borderLeft="1px solid var(--persona-border)":te.style.borderRight="1px solid var(--persona-border)"),y&&(e.style.display="flex",e.style.flexDirection="column",e.style.height="100%",e.style.minHeight="0",E&&(e.style.width="100%"),ke.style.display="flex",ke.style.flexDirection="column",ke.style.flex="1 1 0%",ke.style.minHeight="0",ke.style.maxHeight="100%",ke.style.height="100%",E&&(ke.style.overflow="hidden"),D.style.display="flex",D.style.flexDirection="column",D.style.flex="1 1 0%",D.style.minHeight="0",D.style.maxHeight="100%",D.style.height="100%",D.style.overflow="hidden",te.style.display="flex",te.style.flexDirection="column",te.style.flex="1 1 0%",te.style.minHeight="0",te.style.maxHeight="100%",te.style.overflow="hidden",z.style.flex="1 1 0%",z.style.minHeight="0",z.style.overflowY="auto",it.style.flexShrink="0"),ke.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&&!E&&!l&&((Jr=wn[xe])!=null?Jr:wn["bottom-right"]).split(" ").forEach(Jt=>ke.classList.add(Jt)),g){let Ut=(Lo=(vr=n.launcher)==null?void 0:vr.sidebarWidth)!=null?Lo:"420px";ke.style.cssText=`
57
57
  position: fixed !important;
58
58
  top: 0 !important;
59
59
  bottom: 0 !important;
60
- width: ${Kt} !important;
60
+ width: ${Ut} !important;
61
61
  height: 100vh !important;
62
62
  max-height: 100vh !important;
63
63
  margin: 0 !important;
64
64
  padding: 0 !important;
65
65
  display: flex !important;
66
66
  flex-direction: column !important;
67
- z-index: ${R} !important;
68
- ${Se?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
67
+ z-index: ${W} !important;
68
+ ${Ve?"left: 0 !important; right: auto !important;":"left: auto !important; right: 0 !important;"}
69
69
  `,D.style.cssText=`
70
70
  position: relative !important;
71
71
  display: flex !important;
@@ -77,8 +77,8 @@ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=
77
77
  min-height: 0 !important;
78
78
  margin: 0 !important;
79
79
  padding: 0 !important;
80
- box-shadow: ${lt} !important;
81
- border-radius: ${Je} !important;
80
+ box-shadow: ${mt} !important;
81
+ border-radius: ${Ke} !important;
82
82
  `,D.style.setProperty("width","100%","important"),D.style.setProperty("max-width","100%","important"),te.style.cssText=`
83
83
  display: flex !important;
84
84
  flex-direction: column !important;
@@ -88,13 +88,13 @@ import{Marked as zc}from"marked";var qc=e=>{if(e)return e},Io=e=>{var s,o;let r=
88
88
  min-height: 0 !important;
89
89
  max-height: 100% !important;
90
90
  overflow: hidden !important;
91
- border-radius: ${Je} !important;
92
- border: ${De} !important;
91
+ border-radius: ${Ke} !important;
92
+ border: ${He} !important;
93
93
  `,it.style.cssText=`
94
94
  flex-shrink: 0 !important;
95
95
  border-top: none !important;
96
96
  padding: 8px 16px 12px 16px !important;
97
- `}if(!E&&!l){let Kt="max-height: -moz-available !important; max-height: stretch !important;",Ft=g?"":"padding-top: 1.25em !important;",An=!g&&((jn=n.launcher)==null?void 0:jn.zIndex)!=null?`z-index: ${n.launcher.zIndex} !important;`:"";Me.style.cssText+=Kt+Ft+An}};Yn(),ir(e,n),qo(e,n),Uo(e,n);let Et=[];X&&Et.push(()=>{X==null||X.disconnect(),X=null}),Et.push(()=>{ln==null||ln(),ln=null,dr(),ht&&(ht.remove(),ht=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),le&&Et.push(()=>{xe!==null&&(cancelAnimationFrame(xe),xe=null),G==null||G.destroy(),G=null,q==null||q.destroy(),q=null,Y=null});let wn=null,Br=()=>{wn&&(wn(),wn=null),n.colorScheme==="auto"&&(wn=ys(()=>{ir(e,n)}))};Br(),Et.push(()=>{wn&&(wn(),wn=null)});let On=Ul(Le),Sn=null,H,$n=!1,Fn=Pl(),Dr=0,Ln=!0,Xn=0,Nr=0,In=null,Pn=!1,pr=0,ur=!1,uo=125,go=2e3,mo=5,Or=50,gr=new Map,Ve={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},$r=(ca=(la=n.voiceRecognition)==null?void 0:la.autoResume)!=null?ca:!1,cn=l=>{o.emit("voice:state",{active:Ve.active,source:l,timestamp:Date.now()})},Qt=()=>{f(l=>({...l,voiceState:{active:Ve.active,timestamp:Date.now(),manuallyDeactivated:Ve.manuallyDeactivated}}))},fo=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Ds(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Ve.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<dp&&setTimeout(()=>{var W,P;Ve.active||(Ve.manuallyDeactivated=!1,((P=(W=n.voiceRecognition)==null?void 0:W.provider)==null?void 0:P.type)==="runtype"?H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("restore"),H.isVoiceActive()&&_n()}):tr("restore"))},1e3)},ho=()=>H?sc(H.getMessages()).filter(l=>!l.__skipPersist):[];function Fr(l){if(!(a!=null&&a.save))return;let y={messages:l?sc(l):H?ho():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let Zn=(l=!1)=>{if(!Ln)return;let g=Date.now();Pn&&g<pr&&!l||(Pn&&g>=pr&&(Pn=!1),!(!l&&!$n)&&(g-Nr<uo||(Nr=g,In&&cancelAnimationFrame(In),In=requestAnimationFrame(()=>{Pn||!Ln||(ur=!0,z.scrollTop=z.scrollHeight,Xn=z.scrollTop,requestAnimationFrame(()=>{ur=!1}),In=null)}))))},Wn=null,yo=()=>Me.querySelector("#persona-scroll-container")||z,bo=(l,g=500)=>{let y=l.scrollTop,E=l.clientHeight,L=l.scrollHeight,W=L-y;if(y+E>=L-2||Math.abs(W)<5)return;Wn!==null&&(cancelAnimationFrame(Wn),Wn=null);let U=performance.now(),N=be=>1-Math.pow(1-be,3),ae=be=>{let we=l.scrollHeight;we!==L&&(L=we,W=L-y);let We=be-U,Se=Math.min(We/g,1),R=N(Se),He=y+W*R;l.scrollTop=He,Se<1?Wn=requestAnimationFrame(ae):(l.scrollTop=l.scrollHeight,Wn=null)};Wn=requestAnimationFrame(ae)},xo=l=>{let g=new Map;l.forEach(y=>{let E=gr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),gr.clear(),g.forEach((y,E)=>{gr.set(E,y)})},Qn=(l,g,y)=>{var be,we,We,Se;let E=document.createElement("div"),W=(()=>{var He;let R=s.find(Re=>Re.renderLoadingIndicator);if(R!=null&&R.renderLoadingIndicator)return R.renderLoadingIndicator;if((He=n.loadingIndicator)!=null&&He.render)return n.loadingIndicator.render})(),P=new Set;g.forEach(R=>{var me,Bt;P.add(R.id);let He=Il(R,Dr),Re=Wl(Fn,R.id,He);if(Re){E.appendChild(Re.cloneNode(!0));return}let pe=null,De=s.find(pt=>!!(R.variant==="reasoning"&&pt.renderReasoning||R.variant==="tool"&&pt.renderToolCall||R.variant==="approval"&&pt.renderApproval||!R.variant&&pt.renderMessage)),lt=(me=n.layout)==null?void 0:me.messages;if(De)if(R.variant==="reasoning"&&R.reasoning&&De.renderReasoning){if(!ne)return;pe=De.renderReasoning({message:R,defaultRenderer:()=>vs(R),config:n})}else if(R.variant==="tool"&&R.toolCall&&De.renderToolCall){if(!Te)return;pe=De.renderToolCall({message:R,defaultRenderer:()=>Cs(R,n),config:n})}else if(R.variant==="approval"&&R.approval&&De.renderApproval){if(n.approval===!1)return;pe=De.renderApproval({message:R,defaultRenderer:()=>ws(R,n),config:n})}else De.renderMessage&&(pe=De.renderMessage({message:R,defaultRenderer:()=>{let pt=lo(R,y,lt,n.messageActions,Xe,{loadingIndicatorRenderer:W,widgetConfig:n});return R.role!=="user"&&Es(pt,R,n,H),pt},config:n}));if(!pe&&R.role==="assistant"&&!R.variant&&n.enableComponentStreaming!==!1&&Ws(R)){let tn=Rs(R);if(tn){let Jt=Ps(tn,{config:n,message:R,transform:y});if(Jt)if(n.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-${R.id}`,$t.setAttribute("data-message-id",R.id),R.content&&R.content.trim()){let pn=document.createElement("div");pn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",pn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),pe=$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-${R.id}`,$t.setAttribute("data-message-id",R.id),$t.setAttribute("data-persona-component-directive","true"),R.content&&R.content.trim()){let pn=document.createElement("div");pn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",pn.innerHTML=y({text:R.content,message:R,streaming:!!R.streaming,raw:R.rawContent}),$t.appendChild(pn)}$t.appendChild(Jt),pe=$t}}}if(!pe)if(R.variant==="reasoning"&&R.reasoning){if(!ne)return;pe=vs(R)}else if(R.variant==="tool"&&R.toolCall){if(!Te)return;pe=Cs(R,n)}else if(R.variant==="approval"&&R.approval){if(n.approval===!1)return;pe=ws(R,n)}else{let pt=(Bt=n.layout)==null?void 0:Bt.messages;pt!=null&&pt.renderUserMessage&&R.role==="user"?pe=pt.renderUserMessage({message:R,config:n,streaming:!!R.streaming}):pt!=null&&pt.renderAssistantMessage&&R.role==="assistant"?pe=pt.renderAssistantMessage({message:R,config:n,streaming:!!R.streaming}):pe=lo(R,y,pt,n.messageActions,Xe,{loadingIndicatorRenderer:W,widgetConfig:n}),R.role!=="user"&&pe&&Es(pe,R,n,H)}let Je=document.createElement("div");Je.className="persona-flex",Je.id=`wrapper-${R.id}`,Je.setAttribute("data-wrapper-id",R.id),R.role==="user"&&Je.classList.add("persona-justify-end"),(pe==null?void 0:pe.getAttribute("data-persona-component-directive"))==="true"&&Je.classList.add("persona-w-full"),Je.appendChild(pe),Rl(Fn,R.id,He,Je),E.appendChild(Je)}),Hl(Fn,P);let U=g.some(R=>R.role==="assistant"&&R.streaming),N=g[g.length-1],ae=(N==null?void 0:N.role)==="assistant"&&!N.streaming&&N.variant!=="approval";if($n&&g.some(R=>R.role==="user")&&!U&&!ae){let R={config:n,streaming:!0,location:"standalone",defaultRenderer:Er},He=s.find(pe=>pe.renderLoadingIndicator),Re=null;if(He!=null&&He.renderLoadingIndicator&&(Re=He.renderLoadingIndicator(R)),Re===null&&((be=n.loadingIndicator)!=null&&be.render)&&(Re=n.loadingIndicator.render(R)),Re===null&&(Re=Er()),Re){let pe=document.createElement("div"),De=((we=n.loadingIndicator)==null?void 0:we.showBubble)!==!1;pe.className=De?["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-typing-indicator","true"),pe.appendChild(Re);let lt=document.createElement("div");lt.className="persona-flex",lt.id="wrapper-typing-indicator",lt.setAttribute("data-wrapper-id","typing-indicator"),lt.appendChild(pe),E.appendChild(lt)}}if(!$n&&g.length>0){let R=g[g.length-1],He={config:n,lastMessage:R,messageCount:g.length},Re=s.find(De=>De.renderIdleIndicator),pe=null;if(Re!=null&&Re.renderIdleIndicator&&(pe=Re.renderIdleIndicator(He)),pe===null&&((We=n.loadingIndicator)!=null&&We.renderIdle)&&(pe=n.loadingIndicator.renderIdle(He)),pe){let De=document.createElement("div"),lt=((Se=n.loadingIndicator)==null?void 0:Se.showBubble)!==!1;De.className=lt?["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(" "),De.setAttribute("data-idle-indicator","true"),De.appendChild(pe);let Je=document.createElement("div");Je.className="persona-flex",Je.id="wrapper-idle-indicator",Je.setAttribute("data-wrapper-id","idle-indicator"),Je.appendChild(De),E.appendChild(Je)}}Ll(l,E),requestAnimationFrame(()=>{requestAnimationFrame(()=>{let R=yo();bo(R)})})},er=()=>{var N,ae,be,we,We;if(!b)return;let l=zt(n),g=(N=e.ownerDocument.defaultView)!=null?N:window,y=(be=(ae=n.launcher)==null?void 0:ae.mobileBreakpoint)!=null?be:640,E=(We=(we=n.launcher)==null?void 0:we.mobileFullscreen)!=null?We:!0,L=g.innerWidth<=y,W=E&&L&&b,P=hn(n).reveal;k?(Me.style.removeProperty("display"),Me.style.display=l?"flex":"",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-95","persona-opacity-0"),D.classList.add("persona-scale-100","persona-opacity-100"),_e?_e.element.style.display="none":qe&&(qe.style.display="none")):(l?l&&(P==="overlay"||P==="push")&&!W?(Me.style.removeProperty("display"),Me.style.display="flex",Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.setProperty("display","none","important"),Me.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(Me.style.display="",Me.classList.add("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100"),D.classList.add("persona-scale-95","persona-opacity-0")),_e?_e.element.style.display=l?"none":"":qe&&(qe.style.display=l?"none":""))},bt=(l,g="user")=>{if(!b||k===l)return;let y=k;k=l,er(),k&&(Lt(),Zn(!0));let E={open:k,source:g,timestamp:Date.now()};k&&!y?o.emit("widget:opened",E):!k&&y&&o.emit("widget:closed",E),o.emit("widget:state",{open:k,launcherEnabled:b,voiceActive:Ve.active,streaming:H.isStreaming()})},mr=l=>{J.disabled=l,T&&(T.disabled=l),On.buttons.forEach(g=>{g.disabled=l}),it.dataset.personaComposerStreaming=l?"true":"false",it.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},fr=()=>{Ve.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>fr(),200)});let _r=()=>{var y,E,L,W,P,U,N,ae,be,we,We;qt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",Ut.textContent=(W=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?W:"Ask anything about your account or products.",Z.placeholder=(U=(P=n.copy)==null?void 0:P.inputPlaceholder)!=null?U:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let Se=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Se?"":"none",Se?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(be=(ae=n.sendButton)==null?void 0:ae.useIcon)!=null&&be||(J.textContent=(We=(we=n.copy)==null?void 0:we.sendButtonLabel)!=null?We:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.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=>{f(g=>({...g,sessionId:l}))}}),H=new to(n,{onMessagesChanged(l){Qn(oe,l,_),H&&(l.some(L=>L.role==="user")?On.render([],H,Z,l):On.render(n.suggestionChips,H,Z,l,n.suggestionChipsConfig)),Zn(!$n),xo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Ve.lastUserMessageId;g&&g.id!==y&&(Ve.lastUserMessageId=g.id,o.emit("user:message",g)),Ve.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Fr(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};rt(St,(L=>{var W,P,U,N;return L==="idle"?(W=g.idleText)!=null?W:Gt.idle:L==="connecting"?(P=g.connectingText)!=null?P:Gt.connecting:L==="connected"?(U=g.connectedText)!=null?U:Gt.connected:L==="error"?(N=g.errorText)!=null?N:Gt.error:Gt[L]})(l),g,l)},onStreamingChanged(l){$n=l,mr(l),H&&Qn(oe,H.getMessages(),_),l||Zn(!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(),Co();break;case"speaking":mn(),wo();break;default:l==="idle"&&H.isBargeInActive()?(mn(),_n(),T==null||T.setAttribute("aria-label","End voice session")):(Ve.active=!1,mn(),cn("system"),Qt());break}},onArtifactsState(l){an=l,Cn()}}),Wr.current=H,((pa=(da=n.voiceRecognition)==null?void 0:da.provider)==null?void 0:pa.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),q&&H.setSSEEventCallback((l,g)=>{q==null||q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),p&&p.then(l=>{var g;l&&(l.metadata&&(i=Ds(l.metadata),A.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let jr=l=>{var L;l.preventDefault();let g=Z.value.trim(),y=(L=he==null?void 0:he.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...he.getContentParts()),g&&E.push(gs(g))),Z.value="",Z.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&he.clearAttachments()},zr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),J.click())},qr=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!he)return;let g=up(l.clipboardData);g.length!==0&&(l.preventDefault(),await he.handleFiles(g))},Yt=null,on=!1,Rn=null,$e=null,Ur=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,tr=(l="user")=>{var W,P,U,N,ae,be,we,We;if(on||H.isStreaming())return;let g=Ur();if(!g)return;Yt=new g;let E=(P=((W=n.voiceRecognition)!=null?W:{}).pauseDuration)!=null?P:2e3;Yt.continuous=!0,Yt.interimResults=!0,Yt.lang="en-US";let L=Z.value;Yt.onresult=Se=>{let R="",He="";for(let pe=0;pe<Se.results.length;pe++){let De=Se.results[pe],lt=De[0].transcript;De.isFinal?R+=lt+" ":He=lt}let Re=L+R+He;Z.value=Re,Rn&&clearTimeout(Rn),(R||He)&&(Rn=window.setTimeout(()=>{let pe=Z.value.trim();pe&&Yt&&on&&(gn(),Z.value="",Z.style.height="auto",H.sendMessage(pe,{viaVoice:!0}))},E))},Yt.onerror=Se=>{Se.error!=="no-speech"&&gn()},Yt.onend=()=>{if(on){let Se=Z.value.trim();Se&&Se!==L.trim()&&(Z.value="",Z.style.height="auto",H.sendMessage(Se,{viaVoice:!0})),gn()}};try{if(Yt.start(),on=!0,Ve.active=!0,l!=="system"&&(Ve.manuallyDeactivated=!1),cn(l),Qt(),T){let Se=(U=n.voiceRecognition)!=null?U:{};$e={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(N=Se.iconName)!=null?N:"mic",iconSize:parseFloat((we=(be=Se.iconSize)!=null?be:(ae=n.sendButton)==null?void 0:ae.size)!=null?we:"40")||24};let R=(We=Se.recordingBackgroundColor)!=null?We:"#ef4444",He=Se.recordingIconColor,Re=Se.recordingBorderColor;if(T.classList.add("persona-voice-recording"),T.style.backgroundColor=R,He){T.style.color=He;let pe=T.querySelector("svg");pe&&pe.setAttribute("stroke",He)}Re&&(T.style.borderColor=Re),T.setAttribute("aria-label","Stop voice recognition")}}catch{gn("system")}},gn=(l="user")=>{if(on){if(on=!1,Rn&&(clearTimeout(Rn),Rn=null),Yt){try{Yt.stop()}catch{}Yt=null}if(Ve.active=!1,cn(l),Qt(),T){if(T.classList.remove("persona-voice-recording"),$e){T.style.backgroundColor=$e.backgroundColor,T.style.color=$e.color,T.style.borderColor=$e.borderColor;let g=T.querySelector("svg");g&&g.setAttribute("stroke",$e.color||"currentColor"),$e=null}T.setAttribute("aria-label","Start voice recognition")}}},vo=(l,g)=>{var pe,De,lt,Je,me,Bt,pt,tn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((pe=l==null?void 0:l.provider)==null?void 0:pe.type)==="runtype";if(!(y||E))return null;let W=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 U=(De=l==null?void 0:l.iconName)!=null?De:"mic",N=(lt=g==null?void 0:g.size)!=null?lt:"40px",ae=(Je=l==null?void 0:l.iconSize)!=null?Je:N,be=parseFloat(ae)||24,we=(me=l==null?void 0:l.backgroundColor)!=null?me:g==null?void 0:g.backgroundColor,We=(Bt=l==null?void 0:l.iconColor)!=null?Bt:g==null?void 0:g.textColor;P.style.width=ae,P.style.height=ae,P.style.minWidth=ae,P.style.minHeight=ae,P.style.fontSize="18px",P.style.lineHeight="1";let Se=We||"currentColor",R=fe(U,be,Se,1.5);R?(P.appendChild(R),P.style.color=Se):(P.textContent="\u{1F3A4}",P.style.color=Se),we?P.style.backgroundColor=we:P.classList.add("persona-bg-persona-primary"),We?P.style.color=We:!We&&!(g!=null&&g.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),W.appendChild(P);let He=(pt=l==null?void 0:l.tooltipText)!=null?pt:"Start voice recognition";if(((tn=l==null?void 0:l.showTooltip)!=null?tn:!1)&&He){let Jt=h("div","persona-send-button-tooltip");Jt.textContent=He,W.appendChild(Jt)}return{micButton:P,micButtonWrapper:W}},hr=()=>{var g,y,E,L,W;if(!T||$e)return;let l=(g=n.voiceRecognition)!=null?g:{};$e={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((W=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?W:"40")||24}},yr=(l,g)=>{var W,P,U,N,ae;if(!T)return;let y=T.querySelector("svg");y&&y.remove();let E=(ae=$e==null?void 0:$e.iconSize)!=null?ae:parseFloat((N=(U=(W=n.voiceRecognition)==null?void 0:W.iconSize)!=null?U:(P=n.sendButton)==null?void 0:P.size)!=null?N:"40")||24,L=fe(l,E,g,1.5);L&&T.appendChild(L)},nr=()=>{T&&T.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},_n=()=>{var L,W;if(!T)return;hr();let l=(L=n.voiceRecognition)!=null?L:{},g=(W=l.recordingBackgroundColor)!=null?W:"#ef4444",y=l.recordingIconColor,E=l.recordingBorderColor;if(nr(),T.classList.add("persona-voice-recording"),T.style.backgroundColor=g,y){T.style.color=y;let P=T.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(T.style.borderColor=E),T.setAttribute("aria-label","Stop voice recognition")},Co=()=>{var U,N,ae,be,we,We,Se,R;if(!T)return;hr();let l=(U=n.voiceRecognition)!=null?U:{},g=H.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",E=(be=(ae=l.processingIconColor)!=null?ae:$e==null?void 0:$e.color)!=null?be:"",L=(We=(we=l.processingBackgroundColor)!=null?we:$e==null?void 0:$e.backgroundColor)!=null?We:"",W=(R=(Se=l.processingBorderColor)!=null?Se:$e==null?void 0:$e.borderColor)!=null?R:"";nr(),T.classList.add("persona-voice-processing"),T.style.backgroundColor=L,T.style.borderColor=W;let P=E||"currentColor";T.style.color=P,yr(y,P),T.setAttribute("aria-label","Processing voice input"),g==="none"&&(T.style.cursor="default")},wo=()=>{var ae,be,we,We,Se,R,He,Re,pe,De,lt,Je;if(!T)return;hr();let l=(ae=n.voiceRecognition)!=null?ae:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(be=l.speakingIconName)!=null?be:y,L=(R=l.speakingIconColor)!=null?R:g==="barge-in"?(We=(we=l.recordingIconColor)!=null?we:$e==null?void 0:$e.color)!=null?We:"":(Se=$e==null?void 0:$e.color)!=null?Se:"",W=(pe=l.speakingBackgroundColor)!=null?pe:g==="barge-in"?(He=l.recordingBackgroundColor)!=null?He:"#ef4444":(Re=$e==null?void 0:$e.backgroundColor)!=null?Re:"",P=(Je=l.speakingBorderColor)!=null?Je:g==="barge-in"?(De=l.recordingBorderColor)!=null?De:"":(lt=$e==null?void 0:$e.borderColor)!=null?lt:"";nr(),T.classList.add("persona-voice-speaking"),T.style.backgroundColor=W,T.style.borderColor=P;let U=L||"currentColor";T.style.color=U,yr(E,U);let N=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";T.setAttribute("aria-label",N),g==="none"&&(T.style.cursor="default"),g==="barge-in"&&T.classList.add("persona-voice-recording")},mn=()=>{var l,g,y;T&&(nr(),$e&&(T.style.backgroundColor=(l=$e.backgroundColor)!=null?l:"",T.style.color=(g=$e.color)!=null?g:"",T.style.borderColor=(y=$e.borderColor)!=null?y:"",yr($e.iconName,$e.color||"currentColor"),$e=null),T.style.cursor="",T.setAttribute("aria-label","Start voice recognition"))},rr=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,Qt(),cn("user"),mn()});return}H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),Ve.manuallyDeactivated=!H.isVoiceActive(),Qt(),cn("user"),H.isVoiceActive()?_n():mn()});return}if(on){let y=Z.value.trim();Ve.manuallyDeactivated=!0,Qt(),gn("user"),y&&(Z.value="",Z.style.height="auto",H.sendMessage(y))}else Ve.manuallyDeactivated=!1,Qt(),tr("user")};Pe=rr,T&&(T.addEventListener("click",rr),Et.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),mn()):gn("system"),T&&T.removeEventListener("click",rr)}));let Q=o.on("assistant:complete",()=>{$r&&(Ve.active||Ve.manuallyDeactivated||$r==="assistant"&&!Ve.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Ve.active&&!Ve.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("auto"),H.isVoiceActive()&&_n()}):tr("auto"))},600))});Et.push(Q);let Ye=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});Et.push(Ye);let st=()=>{bt(!k,"user")},_e=null,qe=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>so(n,st).element,onToggle:st});g&&(qe=g)}qe||(_e=so(n,st))}_e?e.appendChild(_e.element):qe&&e.appendChild(qe),er(),On.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),_r(),mr(H.isStreaming()),Zn(!0),fo(),M&&(b?k&&setTimeout(()=>fr(),200):setTimeout(()=>fr(),0));let Lt=()=>{var N,ae,be,we,We,Se,R,He,Re,pe,De,lt,Je;let l=zt(n),g=(ae=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,y=l||g||((we=(be=n.launcher)==null?void 0:be.fullHeight)!=null?we:!1),E=(We=e.ownerDocument.defaultView)!=null?We:window,L=(R=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?R:!0,W=(Re=(He=n.launcher)==null?void 0:He.mobileBreakpoint)!=null?Re:640,P=E.innerWidth<=W,U=L&&P&&b;try{if(U){Yn(),ir(e,n);return}if(O&&(O=!1,Yn(),ir(e,n)),!b&&!l){D.style.height="",D.style.width="";return}if(!g&&!l){let me=(De=(pe=n==null?void 0:n.launcher)==null?void 0:pe.width)!=null?De:n==null?void 0:n.launcherWidth,Bt=me!=null?me:"min(400px, calc(100vw - 24px))";D.style.width=Bt,D.style.maxWidth=Bt}if(Gn(),!y){let me=E.innerHeight,Bt=64,pt=(Je=(lt=n.launcher)==null?void 0:lt.heightOffset)!=null?Je:0,tn=Math.max(200,me-Bt),Jt=Math.min(640,tn),Xt=Math.max(200,Jt-pt);D.style.height=`${Xt}px`}}finally{er()}};Lt();let Tt=(ua=e.ownerDocument.defaultView)!=null?ua:window;Tt.addEventListener("resize",Lt),Et.push(()=>Tt.removeEventListener("resize",Lt)),Xn=z.scrollTop;let C=()=>{let l=z.scrollTop,g=z.scrollHeight,y=z.clientHeight,E=g-l-y,L=Math.abs(l-Xn);if(Xn=l,!ur&&!(L<=mo)){if(!Ln&&E<Or){Pn=!1,Ln=!0;return}Ln&&E>Or&&(Pn=!0,pr=Date.now()+go,Ln=!1)}};z.addEventListener("scroll",C,{passive:!0}),Et.push(()=>z.removeEventListener("scroll",C)),Et.push(()=>{In&&cancelAnimationFrame(In)});let Fe=()=>{K&&(Sn&&(K.removeEventListener("click",Sn),Sn=null),b?(K.style.display="",Sn=()=>{bt(!1,"user")},K.addEventListener("click",Sn)):K.style.display="none")};Fe(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{H.clearMessages(),Fn.clear();try{localStorage.removeItem(Ir),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ir}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ir)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(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},A.syncFromMetadata(),q==null||q.clear(),G==null||G.update()})})(),Ue&&Ue.addEventListener("submit",jr),Z==null||Z.addEventListener("keydown",zr),Z==null||Z.addEventListener("paste",qr),Et.push(()=>{Ue&&Ue.removeEventListener("submit",jr),Z==null||Z.removeEventListener("keydown",zr),Z==null||Z.removeEventListener("paste",qr)}),Et.push(()=>{H.cancel()}),_e?Et.push(()=>{_e==null||_e.destroy()}):qe&&Et.push(()=>{qe==null||qe.remove()});let w={update(l){var xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Oa,$a,Fa,_a,ja,za,qa,Ua,Va,Ja,Ka,Ga,Ya,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,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Oi,$i,Fi,_i,ji,zi,qi,Ui,Vi,Ji,Ki,Gi,Yi,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al;let g=n.toolCall,y=n.messageActions,E=(xa=n.layout)==null?void 0:xa.messages,L=n.colorScheme,W=n.loadingIndicator,P=n.iterationDisplay;n={...n,...l},Yn(),ir(e,n),qo(e,n),Uo(e,n),Cn(),n.colorScheme!==L&&Br();let U=Vo.getForInstance(n.plugins);s.length=0,s.push(...U),b=(Ca=(va=n.launcher)==null?void 0:va.enabled)!=null?Ca:!0,x=(Sa=(wa=n.launcher)==null?void 0:wa.autoExpand)!=null?Sa:!1,ne=(Ea=(Aa=n.features)==null?void 0:Aa.showReasoning)!=null?Ea:!0,Te=(Ma=(Ta=n.features)==null?void 0:Ta.showToolCalls)!=null?Ma:!0;let N=le;if(le=(La=(ka=n.features)==null?void 0:ka.showEventStreamToggle)!=null?La:!1,le&&!N){if(q||(Y=new po(de),q=new co(ce,Y),Y.open().then(()=>q==null?void 0:q.restore()).catch(()=>{}),H.setSSEEventCallback((j,tt)=>{q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:j,timestamp:Date.now(),payload:JSON.stringify(tt)})})),!Oe&&Ze){let j=(Pa=(Ia=n.features)==null?void 0:Ia.eventStream)==null?void 0:Pa.classNames,tt="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"+(j!=null&&j.toggleButton?" "+j.toggleButton:"");Oe=h("button",tt),Oe.style.width="28px",Oe.style.height="28px",Oe.type="button",Oe.setAttribute("aria-label","Event Stream"),Oe.title="Event Stream";let xt=fe("activity","18px","currentColor",1.5);xt&&Oe.appendChild(xt);let je=se.clearChatButtonWrapper,at=se.closeButtonWrapper,Dt=je||at;Dt&&Dt.parentNode===Ze?Ze.insertBefore(Oe,Dt):Ze.appendChild(Oe),Oe.addEventListener("click",()=>{ve?At():ot()})}}else!le&&N&&(At(),Oe&&(Oe.remove(),Oe=null),q==null||q.clear(),Y==null||Y.destroy(),q=null,Y=null);if(((Wa=n.launcher)==null?void 0:Wa.enabled)===!1&&_e&&(_e.destroy(),_e=null),((Ra=n.launcher)==null?void 0:Ra.enabled)===!1&&qe&&(qe.remove(),qe=null),((Ha=n.launcher)==null?void 0:Ha.enabled)!==!1&&!_e&&!qe){let j=s.find(tt=>tt.renderLauncher);if(j!=null&&j.renderLauncher){let tt=j.renderLauncher({config:n,defaultRenderer:()=>so(n,st).element,onToggle:st});tt&&(qe=tt,e.appendChild(qe))}qe||(_e=so(n,st),e.appendChild(_e.element))}_e&&_e.update(n),ft&&((Ba=n.launcher)==null?void 0:Ba.title)!==void 0&&(ft.textContent=n.launcher.title),yt&&((Da=n.launcher)==null?void 0:Da.subtitle)!==void 0&&(yt.textContent=n.launcher.subtitle);let ae=(Na=n.layout)==null?void 0:Na.header;if((ae==null?void 0:ae.layout)!==I&&Ze){let j=ae?ao(n,ae,{showClose:b,onClose:()=>bt(!1,"user")}):qn({config:n,showClose:b,onClose:()=>bt(!1,"user")});Ze.replaceWith(j.header),Ze=j.header,Ie=j.iconHolder,ft=j.headerTitle,yt=j.headerSubtitle,K=j.closeButton,I=ae==null?void 0:ae.layout}else if(ae&&(Ie&&(Ie.style.display=ae.showIcon===!1?"none":""),ft&&(ft.style.display=ae.showTitle===!1?"none":""),yt&&(yt.style.display=ae.showSubtitle===!1?"none":""),K&&(K.style.display=ae.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let j=ae.showClearChat;if(j!==void 0){se.clearChatButtonWrapper.style.display=j?"":"none";let{closeButtonWrapper:tt}=se;tt&&!tt.classList.contains("persona-absolute")&&(j?tt.classList.remove("persona-ml-auto"):tt.classList.add("persona-ml-auto"))}}let we=((Oa=n.layout)==null?void 0:Oa.showHeader)!==!1;Ze&&(Ze.style.display=we?"":"none");let We=(($a=n.layout)==null?void 0:$a.showFooter)!==!1;it&&(it.style.display=We?"":"none"),b!==S?b?bt(x,"auto"):(k=!0,er()):x!==F&&bt(x,"auto"),F=x,S=b,Lt(),Fe();let He=JSON.stringify(l.toolCall)!==JSON.stringify(g),Re=JSON.stringify(n.messageActions)!==JSON.stringify(y),pe=JSON.stringify((Fa=n.layout)==null?void 0:Fa.messages)!==JSON.stringify(E),De=((_a=n.loadingIndicator)==null?void 0:_a.render)!==(W==null?void 0:W.render)||((ja=n.loadingIndicator)==null?void 0:ja.renderIdle)!==(W==null?void 0:W.renderIdle)||((za=n.loadingIndicator)==null?void 0:za.showBubble)!==(W==null?void 0:W.showBubble),lt=n.iterationDisplay!==P;(He||Re||pe||De||lt)&&H&&(Dr++,Qn(oe,H.getMessages(),_));let me=(qa=n.launcher)!=null?qa:{},Bt=(Ua=me.headerIconHidden)!=null?Ua:!1,pt=(Ja=(Va=n.layout)==null?void 0:Va.header)==null?void 0:Ja.showIcon,tn=Bt||pt===!1,Jt=me.headerIconName,Xt=(Ka=me.headerIconSize)!=null?Ka:"48px";if(Ie){let j=te.querySelector(".persona-border-b-persona-divider"),tt=j==null?void 0:j.querySelector(".persona-flex-col");if(tn)Ie.style.display="none",j&&tt&&!j.contains(tt)&&j.insertBefore(tt,j.firstChild);else{if(Ie.style.display="",Ie.style.height=Xt,Ie.style.width=Xt,j&&tt&&(j.contains(Ie)?Ie.nextSibling!==tt&&(Ie.remove(),j.insertBefore(Ie,tt)):j.insertBefore(Ie,tt)),Jt){let je=parseFloat(Xt)||24,at=fe(Jt,je*.6,"#ffffff",2);at?Ie.replaceChildren(at):Ie.textContent=(Ga=me.agentIconText)!=null?Ga:"\u{1F4AC}"}else if(me.iconUrl){let je=Ie.querySelector("img");if(je)je.src=me.iconUrl,je.style.height=Xt,je.style.width=Xt;else{let at=document.createElement("img");at.src=me.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=Xt,at.style.width=Xt,Ie.replaceChildren(at)}}else{let je=Ie.querySelector("svg"),at=Ie.querySelector("img");(je||at)&&Ie.replaceChildren(),Ie.textContent=(Ya=me.agentIconText)!=null?Ya:"\u{1F4AC}"}let xt=Ie.querySelector("img");xt&&(xt.style.height=Xt,xt.style.width=Xt)}}let $t=(Za=(Xa=n.layout)==null?void 0:Xa.header)==null?void 0:Za.showTitle,pn=(ei=(Qa=n.layout)==null?void 0:Qa.header)==null?void 0:ei.showSubtitle;if(ft&&(ft.style.display=$t===!1?"none":""),yt&&(yt.style.display=pn===!1?"none":""),K){((ni=(ti=n.layout)==null?void 0:ti.header)==null?void 0:ni.showCloseButton)===!1?K.style.display="none":K.style.display="";let tt=(ri=me.closeButtonSize)!=null?ri:"32px",xt=(oi=me.closeButtonPlacement)!=null?oi:"inline";K.style.height=tt,K.style.width=tt;let{closeButtonWrapper:je}=se,at=xt==="top-right",Dt=je==null?void 0:je.classList.contains("persona-absolute");if(je&&at!==Dt)if(je.remove(),at)je.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",te.style.position="relative",te.appendChild(je);else{let nt=(ai=(si=me.clearChat)==null?void 0:si.placement)!=null?ai:"inline",_t=(li=(ii=me.clearChat)==null?void 0:ii.enabled)!=null?li:!0;je.className=_t&&nt==="inline"?"":"persona-ml-auto";let nn=te.querySelector(".persona-border-b-persona-divider");nn&&nn.appendChild(je)}if(K.style.color=me.closeButtonColor||bn.actionIconColor,me.closeButtonBackgroundColor?(K.style.backgroundColor=me.closeButtonBackgroundColor,K.classList.remove("hover:persona-bg-gray-100")):(K.style.backgroundColor="",K.classList.add("hover:persona-bg-gray-100")),me.closeButtonBorderWidth||me.closeButtonBorderColor){let nt=me.closeButtonBorderWidth||"0px",_t=me.closeButtonBorderColor||"transparent";K.style.border=`${nt} solid ${_t}`,K.classList.remove("persona-border-none")}else K.style.border="",K.classList.add("persona-border-none");me.closeButtonBorderRadius?(K.style.borderRadius=me.closeButtonBorderRadius,K.classList.remove("persona-rounded-full")):(K.style.borderRadius="",K.classList.add("persona-rounded-full")),me.closeButtonPaddingX?(K.style.paddingLeft=me.closeButtonPaddingX,K.style.paddingRight=me.closeButtonPaddingX):(K.style.paddingLeft="",K.style.paddingRight=""),me.closeButtonPaddingY?(K.style.paddingTop=me.closeButtonPaddingY,K.style.paddingBottom=me.closeButtonPaddingY):(K.style.paddingTop="",K.style.paddingBottom="");let jt=(ci=me.closeButtonIconName)!=null?ci:"x",fn=(di=me.closeButtonIconText)!=null?di:"\xD7";K.innerHTML="";let Zt=fe(jt,"20px","currentColor",2);Zt?K.appendChild(Zt):K.textContent=fn;let kt=(pi=me.closeButtonTooltipText)!=null?pi:"Close chat",sn=(ui=me.closeButtonShowTooltip)!=null?ui:!0;if(K.setAttribute("aria-label",kt),je&&(je._cleanupTooltip&&(je._cleanupTooltip(),delete je._cleanupTooltip),sn&&kt)){let nt=null,_t=()=>{if(nt||!K)return;let or=K.ownerDocument,Kr=or.body;if(!Kr)return;nt=En(or,"div","persona-clear-chat-tooltip"),nt.textContent=kt;let Gr=En(or,"div");Gr.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Gr);let sr=K.getBoundingClientRect();nt.style.position="fixed",nt.style.left=`${sr.left+sr.width/2}px`,nt.style.top=`${sr.top-8}px`,nt.style.transform="translate(-50%, -100%)",Kr.appendChild(nt)},nn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};je.addEventListener("mouseenter",_t),je.addEventListener("mouseleave",nn),K.addEventListener("focus",_t),K.addEventListener("blur",nn),je._cleanupTooltip=()=>{nn(),je&&(je.removeEventListener("mouseenter",_t),je.removeEventListener("mouseleave",nn)),K&&(K.removeEventListener("focus",_t),K.removeEventListener("blur",nn))}}}let{clearChatButton:Ge,clearChatButtonWrapper:wt}=se;if(Ge){let j=(gi=me.clearChat)!=null?gi:{},tt=(mi=j.enabled)!=null?mi:!0,xt=(hi=(fi=n.layout)==null?void 0:fi.header)==null?void 0:hi.showClearChat,je=xt!==void 0?xt:tt,at=(yi=j.placement)!=null?yi:"inline";if(wt){wt.style.display=je?"":"none";let{closeButtonWrapper:Dt}=se;Dt&&!Dt.classList.contains("persona-absolute")&&(je?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"));let jt=at==="top-right",fn=wt.classList.contains("persona-absolute");if(jt!==fn&&je){if(wt.remove(),jt)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",te.style.position="relative",te.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let kt=te.querySelector(".persona-border-b-persona-divider"),sn=se.closeButtonWrapper;kt&&sn&&sn.parentElement===kt?kt.insertBefore(wt,sn):kt&&kt.appendChild(wt)}let Zt=se.closeButtonWrapper;Zt&&!Zt.classList.contains("persona-absolute")&&(jt?Zt.classList.add("persona-ml-auto"):Zt.classList.remove("persona-ml-auto"))}}if(je){let Dt=(bi=j.size)!=null?bi:"32px";Ge.style.height=Dt,Ge.style.width=Dt;let jt=(xi=j.iconName)!=null?xi:"refresh-cw",fn=(vi=j.iconColor)!=null?vi:"";Ge.style.color=fn||bn.actionIconColor,Ge.innerHTML="";let Zt=fe(jt,"20px","currentColor",2);if(Zt&&Ge.appendChild(Zt),j.backgroundColor?(Ge.style.backgroundColor=j.backgroundColor,Ge.classList.remove("hover:persona-bg-gray-100")):(Ge.style.backgroundColor="",Ge.classList.add("hover:persona-bg-gray-100")),j.borderWidth||j.borderColor){let nt=j.borderWidth||"0px",_t=j.borderColor||"transparent";Ge.style.border=`${nt} solid ${_t}`,Ge.classList.remove("persona-border-none")}else Ge.style.border="",Ge.classList.add("persona-border-none");j.borderRadius?(Ge.style.borderRadius=j.borderRadius,Ge.classList.remove("persona-rounded-full")):(Ge.style.borderRadius="",Ge.classList.add("persona-rounded-full")),j.paddingX?(Ge.style.paddingLeft=j.paddingX,Ge.style.paddingRight=j.paddingX):(Ge.style.paddingLeft="",Ge.style.paddingRight=""),j.paddingY?(Ge.style.paddingTop=j.paddingY,Ge.style.paddingBottom=j.paddingY):(Ge.style.paddingTop="",Ge.style.paddingBottom="");let kt=(Ci=j.tooltipText)!=null?Ci:"Clear chat",sn=(wi=j.showTooltip)!=null?wi:!0;if(Ge.setAttribute("aria-label",kt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),sn&&kt)){let nt=null,_t=()=>{if(nt||!Ge)return;let or=Ge.ownerDocument,Kr=or.body;if(!Kr)return;nt=En(or,"div","persona-clear-chat-tooltip"),nt.textContent=kt;let Gr=En(or,"div");Gr.className="persona-clear-chat-tooltip-arrow",nt.appendChild(Gr);let sr=Ge.getBoundingClientRect();nt.style.position="fixed",nt.style.left=`${sr.left+sr.width/2}px`,nt.style.top=`${sr.top-8}px`,nt.style.transform="translate(-50%, -100%)",Kr.appendChild(nt)},nn=()=>{nt&&nt.parentNode&&(nt.parentNode.removeChild(nt),nt=null)};wt.addEventListener("mouseenter",_t),wt.addEventListener("mouseleave",nn),Ge.addEventListener("focus",_t),Ge.addEventListener("blur",nn),wt._cleanupTooltip=()=>{nn(),wt&&(wt.removeEventListener("mouseenter",_t),wt.removeEventListener("mouseleave",nn)),Ge&&(Ge.removeEventListener("focus",_t),Ge.removeEventListener("blur",nn))}}}}let So=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Jo],Ao=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Lr.message,Lr.messageAndClick];A=Ko({parsers:So,handlers:Ao,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),_=ac(n,A,ie),H.updateConfig(n),Qn(oe,H.getMessages(),_),On.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),_r(),mr(H.isStreaming());let Eo=((Si=n.voiceRecognition)==null?void 0:Si.enabled)===!0,To=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Mo=((Ei=(Ai=n.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype";if(Eo&&(To||Mo))if(!T||!Ae){let j=vo(n.voiceRecognition,n.sendButton);j&&(T=j.micButton,Ae=j.micButtonWrapper,ue.insertBefore(Ae,ze),T.addEventListener("click",rr),T.disabled=H.isStreaming())}else{let j=(Ti=n.voiceRecognition)!=null?Ti:{},tt=(Mi=n.sendButton)!=null?Mi:{},xt=(ki=j.iconName)!=null?ki:"mic",je=(Li=tt.size)!=null?Li:"40px",at=(Ii=j.iconSize)!=null?Ii:je,Dt=parseFloat(at)||24;T.style.width=at,T.style.height=at,T.style.minWidth=at,T.style.minHeight=at;let jt=(Wi=(Pi=j.iconColor)!=null?Pi:tt.textColor)!=null?Wi:"currentColor";T.innerHTML="";let fn=fe(xt,Dt,jt,2);fn?T.appendChild(fn):T.textContent="\u{1F3A4}";let Zt=(Ri=j.backgroundColor)!=null?Ri:tt.backgroundColor;Zt?(T.style.backgroundColor=Zt,T.classList.remove("persona-bg-persona-primary")):(T.style.backgroundColor="",T.classList.add("persona-bg-persona-primary")),jt?(T.style.color=jt,T.classList.remove("persona-text-white")):!jt&&!tt.textColor&&(T.style.color="",T.classList.add("persona-text-white")),j.borderWidth?(T.style.borderWidth=j.borderWidth,T.style.borderStyle="solid"):(T.style.borderWidth="",T.style.borderStyle=""),j.borderColor?T.style.borderColor=j.borderColor:T.style.borderColor="",j.paddingX?(T.style.paddingLeft=j.paddingX,T.style.paddingRight=j.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),j.paddingY?(T.style.paddingTop=j.paddingY,T.style.paddingBottom=j.paddingY):(T.style.paddingTop="",T.style.paddingBottom="");let kt=Ae==null?void 0:Ae.querySelector(".persona-send-button-tooltip"),sn=(Hi=j.tooltipText)!=null?Hi:"Start voice recognition";if(((Bi=j.showTooltip)!=null?Bi:!1)&&sn)if(kt)kt.textContent=sn,kt.style.display="";else{let _t=document.createElement("div");_t.className="persona-send-button-tooltip",_t.textContent=sn,Ae==null||Ae.insertBefore(_t,T)}else kt&&(kt.style.display="none");Ae.style.display="",T.disabled=H.isStreaming()}else T&&Ae&&(Ae.style.display="none",((Ni=(Di=n.voiceRecognition)==null?void 0:Di.provider)==null?void 0:Ni.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():on&&gn());if(((Oi=n.attachments)==null?void 0:Oi.enabled)===!0)if(!ye||!re){let j=($i=n.attachments)!=null?$i:{},xt=(_i=((Fi=n.sendButton)!=null?Fi:{}).size)!=null?_i:"40px";Qe||(Qe=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),Qe.style.display="none",Ue.insertBefore(Qe,Z)),Ce||(Ce=document.createElement("input"),Ce.type="file",Ce.accept=((ji=j.allowedTypes)!=null?ji:Hn).join(","),Ce.multiple=((zi=j.maxFiles)!=null?zi:4)>1,Ce.style.display="none",Ce.setAttribute("aria-label","Attach files"),Ue.insertBefore(Ce,Z)),ye=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(qi=j.buttonTooltipText)!=null?qi:"Attach file");let je=(Ui=j.buttonIconName)!=null?Ui:"paperclip",at=xt,Dt=parseFloat(at)||40,jt=Math.round(Dt*.6);re.style.width=at,re.style.height=at,re.style.minWidth=at,re.style.minHeight=at,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let fn=fe(je,jt,"currentColor",1.5);fn?re.appendChild(fn):re.textContent="\u{1F4CE}",re.addEventListener("click",sn=>{sn.preventDefault(),Ce==null||Ce.click()}),ye.appendChild(re);let Zt=(Vi=j.buttonTooltipText)!=null?Vi:"Attach file",kt=h("div","persona-send-button-tooltip");kt.textContent=Zt,ye.appendChild(kt),Vt.append(ye),!he&&Ce&&Qe&&(he=Sr.fromConfig(j),he.setPreviewsContainer(Qe),Ce.addEventListener("change",async()=>{he&&(Ce!=null&&Ce.files)&&(await he.handleFileSelect(Ce.files),Ce.value="")}))}else{ye.style.display="";let j=(Ji=n.attachments)!=null?Ji:{};Ce&&(Ce.accept=((Ki=j.allowedTypes)!=null?Ki:Hn).join(","),Ce.multiple=((Gi=j.maxFiles)!=null?Gi:4)>1),he&&he.updateConfig({allowedTypes:j.allowedTypes,maxFileSize:j.maxFileSize,maxFiles:j.maxFiles})}else ye&&(ye.style.display="none"),he&&he.clearAttachments();let Pt=(Yi=n.sendButton)!=null?Yi:{},ko=(Xi=Pt.useIcon)!=null?Xi:!1,Vr=(Zi=Pt.iconText)!=null?Zi:"\u2191",Jr=Pt.iconName,br=(Qi=Pt.tooltipText)!=null?Qi:"Send message",Lo=(el=Pt.showTooltip)!=null?el:!1,jn=(tl=Pt.size)!=null?tl:"40px",Kt=Pt.backgroundColor,Ft=Pt.textColor;if(ko){if(J.style.width=jn,J.style.height=jn,J.style.minWidth=jn,J.style.minHeight=jn,J.style.fontSize="18px",J.style.lineHeight="1",J.innerHTML="",Jr){let j=parseFloat(jn)||24,tt=Ft&&typeof Ft=="string"&&Ft.trim()?Ft.trim():"currentColor",xt=fe(Jr,j,tt,2);xt?(J.appendChild(xt),J.style.color=tt):(J.textContent=Vr,Ft?J.style.color=Ft:J.classList.add("persona-text-white"))}else J.textContent=Vr,Ft?J.style.color=Ft:J.classList.add("persona-text-white");J.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Kt?(J.style.backgroundColor=Kt,J.classList.remove("persona-bg-persona-primary")):J.classList.add("persona-bg-persona-primary")}else J.textContent=(rl=(nl=n.copy)==null?void 0:nl.sendButtonLabel)!=null?rl:"Send",J.style.width="",J.style.height="",J.style.minWidth="",J.style.minHeight="",J.style.fontSize="",J.style.lineHeight="",J.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",Kt?(J.style.backgroundColor=Kt,J.classList.remove("persona-bg-persona-accent")):J.classList.add("persona-bg-persona-accent"),Ft?J.style.color=Ft:J.classList.add("persona-text-white");Pt.borderWidth?(J.style.borderWidth=Pt.borderWidth,J.style.borderStyle="solid"):(J.style.borderWidth="",J.style.borderStyle=""),Pt.borderColor?J.style.borderColor=Pt.borderColor:J.style.borderColor="",Pt.paddingX?(J.style.paddingLeft=Pt.paddingX,J.style.paddingRight=Pt.paddingX):(J.style.paddingLeft="",J.style.paddingRight=""),Pt.paddingY?(J.style.paddingTop=Pt.paddingY,J.style.paddingBottom=Pt.paddingY):(J.style.paddingTop="",J.style.paddingBottom="");let An=ze==null?void 0:ze.querySelector(".persona-send-button-tooltip");if(Lo&&br)if(An)An.textContent=br,An.style.display="";else{let j=document.createElement("div");j.className="persona-send-button-tooltip",j.textContent=br,ze==null||ze.insertBefore(j,J)}else An&&(An.style.display="none");let as=(ol=n.layout)==null?void 0:ol.contentMaxWidth;as?(oe.style.maxWidth=as,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%",Ue&&(Ue.style.maxWidth=as,Ue.style.marginLeft="auto",Ue.style.marginRight="auto")):(oe.style.maxWidth="",oe.style.marginLeft="",oe.style.marginRight="",oe.style.width="",Ue&&(Ue.style.maxWidth="",Ue.style.marginLeft="",Ue.style.marginRight=""));let zn=(sl=n.statusIndicator)!=null?sl:{},_c=(al=zn.visible)!=null?al:!0;if(St.style.display=_c?"":"none",H){let j=H.getStatus();rt(St,(xt=>{var je,at,Dt,jt;return xt==="idle"?(je=zn.idleText)!=null?je:Gt.idle:xt==="connecting"?(at=zn.connectingText)!=null?at:Gt.connecting:xt==="connected"?(Dt=zn.connectedText)!=null?Dt:Gt.connected:xt==="error"?(jt=zn.errorText)!=null?jt:Gt.error:Gt[xt]})(j),zn,j)}St.classList.remove("persona-text-left","persona-text-center","persona-text-right");let jc=zn.align==="left"?"persona-text-left":zn.align==="center"?"persona-text-center":"persona-text-right";St.classList.add(jc)},open(){b&&bt(!0,"api")},close(){b&&bt(!1,"api")},toggle(){b&&bt(!k,"api")},clearChat(){rn=!1,H.clearMessages(),Fn.clear();try{localStorage.removeItem(Ir),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Ir}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Ir)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={},A.syncFromMetadata(),q==null||q.clear(),G==null||G.update()},setMessage(l){return!Z||H.isStreaming()?!1:(!k&&b&&bt(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||Z.value.trim();return g?(!k&&b&&bt(!0,"system"),Z.value="",Z.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!k&&b&&bt(!0,"system"),Ve.manuallyDeactivated=!1,Qt(),H.toggleVoice().then(()=>{Ve.active=H.isVoiceActive(),cn("user"),H.isVoiceActive()&&_n()})),!0):on?!0:Ur()?(!k&&b&&bt(!0,"system"),Ve.manuallyDeactivated=!1,Qt(),tr("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Ve.active=!1,Ve.manuallyDeactivated=!0,Qt(),cn("user"),mn()}),!0):!1:on?(Ve.manuallyDeactivated=!0,Qt(),gn("user"),!0):!1},injectMessage(l){return!k&&b&&bt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!k&&b&&bt(!0,"system");let g=H.injectAssistantMessage(l);return V&&(V=!1,ge&&(clearTimeout(ge),ge=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!k&&b&&bt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!k&&b&&bt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!k&&b&&bt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!k&&b&&bt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){q&&q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!le||!q||ot()},hideEventStream(){ve&&At()},isEventStreamVisible(){return ve},showArtifacts(){un(n)&&(rn=!1,Cn(),et==null||et.setMobileOpen(!0))},hideArtifacts(){un(n)&&(rn=!0,Cn())},upsertArtifact(l){return un(n)?(rn=!1,H.upsertArtifact(l)):null},selectArtifact(l){un(n)&&H.selectArtifact(l)},clearArtifacts(){un(n)&&H.clearArtifacts()},focusInput(){return b&&!k||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var W;return L.variant==="approval"&&((W=L.approval)==null?void 0:W.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&k},isVoiceActive(){return Ve.active},getState(){return{open:b&&k,launcherEnabled:b,voiceActive:Ve.active,streaming:H.isStreaming()}},showCSATFeedback(l){!k&&b&&bt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=Hs({onSubmit:async(E,L)=>{var W;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&b&&bt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=Bs({onSubmit:async(E,L)=>{var W;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(W=l==null?void 0:l.onSubmit)==null||W.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){Et.forEach(l=>l()),Me.remove(),_e==null||_e.destroy(),qe==null||qe.remove(),Sn&&K.removeEventListener("click",Sn)}};if((((ga=t==null?void 0:t.debugTools)!=null?ga:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:w,getMessages:w.getMessages,getStatus:w.getStatus,getMetadata:w.getPersistentMetadata,updateMetadata:w.updatePersistentMetadata,clearHistory:()=>w.clearChat(),setVoiceActive:y=>y?w.startVoiceRecognition():w.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Et.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=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.focusInput()};if(window.addEventListener("persona:focusInput",g),Et.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let U=ae=>{let be=ae.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&w.showEventStream()},N=ae=>{let be=ae.detail;(!(be!=null&&be.instanceId)||be.instanceId===l)&&w.hideEventStream()};window.addEventListener("persona:showEventStream",U),window.addEventListener("persona:hideEventStream",N),Et.push(()=>{window.removeEventListener("persona:showEventStream",U),window.removeEventListener("persona:hideEventStream",N)})}let y=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.showArtifacts()},E=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.hideArtifacts()},L=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&w.upsertArtifact(N.artifact)},W=U=>{let N=U.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&w.selectArtifact(N.id)},P=U=>{let N=U.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",W),window.addEventListener("persona:clearArtifacts",P),Et.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",W),window.removeEventListener("persona:clearArtifacts",P)})}let ee=gp(n.persistState);if(ee&&b){let l=mp(ee.storage),g=`${ee.keyPrefix}widget-open`,y=`${ee.keyPrefix}widget-voice`,E=`${ee.keyPrefix}widget-voice-mode`;if(l){let L=((ma=ee.persist)==null?void 0:ma.openState)&&l.getItem(g)==="true",W=((fa=ee.persist)==null?void 0:fa.voiceState)&&l.getItem(y)==="true",P=((ha=ee.persist)==null?void 0:ha.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{w.open(),setTimeout(()=>{var U;if(W||P)w.startVoiceRecognition();else if((U=ee.persist)!=null&&U.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(ya=ee.persist)!=null&&ya.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ba=ee.persist)!=null&&ba.voiceState&&(o.on("voice:state",U=>{l.setItem(y,U.active?"true":"false")}),o.on("user:message",U=>{l.setItem(E,U.viaVoice?"true":"false")})),ee.clearOnChatClear){let U=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},N=()=>U();window.addEventListener("persona:clear-chat",N),Et.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&b&&setTimeout(()=>{w.open()},0),w};var fp=(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},ic=(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"},_s=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=""},lc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",_s(e)},Os=e=>{e.style.transition=""},$s=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=""},Fs=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Go=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},hp=(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))},yp=(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)},cc=(e,r,t,n,s,o,a)=>{var v,A,b,x,M,F;let i=hn(o),p=i.reveal==="push";hp(e,r,t,n,p),yp(e,r,t,n,i.side,p),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=(A=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?A:!0,d=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=d:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$s(r),Os(n),lc(n),Fs(t),Go(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((F=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?F:9999),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",p&&(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"),lc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$s(r),Os(n),Fs(t),Go(s,n);let S=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",O=a?"translateX(0)":I;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=S,n.style.transform=O,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",Os(n),_s(n),Go(s,n);let S=fp(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),O=i.animate?"transform 180ms ease":"none",k=i.side==="right"?a?`translateX(-${S}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${S}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=`${I+S}px`,r.style.transition=O,r.style.transform=k,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${I}px`,t.style.maxWidth=`${I}px`,t.style.minWidth=`${I}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="",$s(r),_s(n),Fs(t),Go(s,n);let S=i.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",O=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${I}`,n.style.width=I,n.style.maxWidth=I,n.style.minWidth=I,n.style.minHeight="0",n.style.position="relative",n.style.overflow=S||k?"hidden":"visible",n.style.transition=O,S&&(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")}},bp=(e,r)=>{let t=e.ownerDocument.createElement("div");return ic(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){ic(t,n)},destroy(){t.remove()}}},xp=(e,r)=>{var M,F,S,I;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"),p=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),d=(F=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||F?(I=(S=r==null?void 0:r.launcher)==null?void 0:S.autoExpand)!=null?I:!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),p.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),hn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{cc(a,i,p,c,u,r,d)}),f.observe(a))},A=()=>{cc(a,i,p,c,u,r,d),v()},b=a.ownerDocument.defaultView,x=()=>{A()};return b==null||b.addEventListener("resize",x),hn(r).reveal==="push"?(i.appendChild(p),i.appendChild(c),a.appendChild(i)):(a.appendChild(p),a.appendChild(c)),A(),{mode:"docked",host:u,shell:a,syncWidgetState(O){let k=O.launcherEnabled?O.open:!0;d!==k&&(d=k,A())},updateConfig(O){var k,V;r=O,((V=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)!=null?V:!0)===!1&&(d=!0),A()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Yo=(e,r)=>zt(r)?xp(e,r):bp(e,r);var js={},vp=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},Cp=()=>{try{if(typeof js!="undefined"&&js.url)return new URL("../widget.css",js.url).href}catch{}return null},dc=(e,r)=>{let t=Cp(),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)}},pc=e=>{var b;let r=vp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Yo(r,s),a,i=[],p=(x,M)=>{var O,k;let S=!((k=(O=M==null?void 0:M.launcher)==null?void 0:O.enabled)!=null?k:!0)||zt(M),I=n.createElement("div");if(I.setAttribute("data-persona-root","true"),S&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),t){let V=x.attachShadow({mode:"open"});V.appendChild(I),dc(V,n)}else x.appendChild(I),dc(x,n);return r.id&&I.setAttribute("data-persona-instance",r.id),I},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let x=p(o.host,s);a=Ns(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};d(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=Yo(r,x),s=x,d()},v={update(x){var I,O,k,V,ge,ie;let M={...s,...x,launcher:{...(I=s==null?void 0:s.launcher)!=null?I:{},...(O=x==null?void 0:x.launcher)!=null?O:{},dock:{...(V=(k=s==null?void 0:s.launcher)==null?void 0:k.dock)!=null?V:{},...(ie=(ge=x==null?void 0:x.launcher)==null?void 0:ge.dock)!=null?ie:{}}}},F=zt(s),S=zt(M);if(F!==S){m(M);return}s=M,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},A=new Proxy(v,{get(x,M,F){if(M==="host")return o.host;if(M in x)return Reflect.get(x,M,F);let S=a[M];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=A),A};var hc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wp=new Set(["button","a","input","select","textarea","details","summary"]),Sp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zs=/\b(product|card|item|listing|result)\b/i,Us=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ap=3e3,Ep=100;function yc(e){let r=typeof e.className=="string"?e.className:"";if(zs.test(r)||e.id&&zs.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&zs.test(n.value))return!0}return!1}function bc(e){var r;return Us.test(((r=e.textContent)!=null?r:"").trim())}function xc(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 Tp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function uc(e){let r=e.match(Us);return r?r[0]:null}function gc(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 Mp(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 kp="commerce-card",Lp="result-card";function mc(e){return!yc(e)||!bc(e)||!xc(e)&&!Tp(e)?0:5200}function fc(e){var n;return!yc(e)||bc(e)||!xc(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 vc=[{id:kp,scoreElement(e){return mc(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||Us.test(n)&&n.length<32)}return!0},formatSummary(e,r){var p,c,u;if(mc(e)===0)return null;let{title:t,href:n}=gc(e),s=(u=(c=uc(((p=e.textContent)!=null?p:"").trim()))!=null?c:uc(r.text))!=null?u:"",o=Mp(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(`
97
+ `}if(!E&&!l){let Ut="max-height: -moz-available !important; max-height: stretch !important;",Jt=g?"":"padding-top: 1.25em !important;",kn=!g&&((Vn=n.launcher)==null?void 0:Vn.zIndex)!=null?`z-index: ${n.launcher.zIndex} !important;`:"";ke.style.cssText+=Ut+Jt+kn}};Qn(),dr(e,n),qo(e,n),Vo(e,n);let Et=[];an&&Et.push(()=>{an==null||an.disconnect(),an=null}),Et.push(()=>{Yt==null||Yt(),Yt=null,Fn(),dt&&(dt.remove(),dt=null),et==null||et.element.style.removeProperty("width"),et==null||et.element.style.removeProperty("maxWidth")}),le&&Et.push(()=>{ve!==null&&(cancelAnimationFrame(ve),ve=null),K==null||K.destroy(),K=null,q==null||q.destroy(),q=null,Y=null});let Tn=null,Br=()=>{Tn&&(Tn(),Tn=null),n.colorScheme==="auto"&&(Tn=ys(()=>{dr(e,n)}))};Br(),Et.push(()=>{Tn&&(Tn(),Tn=null)});let _n=Vl(Ie),Mn=null,H,jn=!1,zn=Pl(),Dr=0,hn=!0,er=0,Nr=0,Rn=null,yn=!1,gr=0,mr=!1,uo=125,go=2e3,mo=5,Or=50,fr=new Map,Je={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},$r=(ca=(la=n.voiceRecognition)==null?void 0:la.autoResume)!=null?ca:!1,pn=l=>{o.emit("voice:state",{active:Je.active,source:l,timestamp:Date.now()})},tn=()=>{f(l=>({...l,voiceState:{active:Je.active,timestamp:Date.now(),manuallyDeactivated:Je.manuallyDeactivated}}))},fo=()=>{var E,L;if(((E=n.voiceRecognition)==null?void 0:E.enabled)===!1)return;let l=Ds(i.voiceState),g=!!l.active,y=Number((L=l.timestamp)!=null?L:0);Je.manuallyDeactivated=!!l.manuallyDeactivated,g&&Date.now()-y<dp&&setTimeout(()=>{var P,R;Je.active||(Je.manuallyDeactivated=!1,((R=(P=n.voiceRecognition)==null?void 0:P.provider)==null?void 0:R.type)==="runtype"?H.toggleVoice().then(()=>{Je.active=H.isVoiceActive(),pn("restore"),H.isVoiceActive()&&qn()}):or("restore"))},1e3)},ho=()=>H?sc(H.getMessages()).filter(l=>!l.__skipPersist):[];function Fr(l){if(!(a!=null&&a.save))return;let y={messages:l?sc(l):H?ho():[],metadata:i};try{let E=a.save(y);E instanceof Promise&&E.catch(L=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",L)})}catch(E){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)}}let tr=(l=!1)=>{if(!hn)return;let g=Date.now();yn&&g<gr&&!l||(yn&&g>=gr&&(yn=!1),!(!l&&!jn)&&(g-Nr<uo||(Nr=g,Rn&&cancelAnimationFrame(Rn),Rn=requestAnimationFrame(()=>{yn||!hn||(mr=!0,z.scrollTop=z.scrollHeight,er=z.scrollTop,requestAnimationFrame(()=>{mr=!1}),Rn=null)}))))},Hn=null,yo=()=>ke.querySelector("#persona-scroll-container")||z,bo=(l,g=500)=>{let y=l.scrollTop,E=l.clientHeight,L=l.scrollHeight,P=L-y;if(y+E>=L-2||Math.abs(P)<5)return;Hn!==null&&(cancelAnimationFrame(Hn),Hn=null);let V=performance.now(),N=he=>1-Math.pow(1-he,3),ae=he=>{let Se=l.scrollHeight;Se!==L&&(L=Se,P=L-y);let xe=he-V,Ve=Math.min(xe/g,1),W=N(Ve),Oe=y+P*W;l.scrollTop=Oe,Ve<1?Hn=requestAnimationFrame(ae):(l.scrollTop=l.scrollHeight,Hn=null)};Hn=requestAnimationFrame(ae)},xo=l=>{let g=new Map;l.forEach(y=>{let E=fr.get(y.id);g.set(y.id,{streaming:y.streaming,role:y.role}),!E&&y.role==="assistant"&&o.emit("assistant:message",y),y.role==="assistant"&&(E!=null&&E.streaming)&&y.streaming===!1&&o.emit("assistant:complete",y),y.variant==="approval"&&y.approval&&(E?y.approval.status!=="pending"&&o.emit("approval:resolved",{approval:y.approval,decision:y.approval.status}):o.emit("approval:requested",{approval:y.approval,message:y}))}),fr.clear(),g.forEach((y,E)=>{fr.set(E,y)})},nr=(l,g,y)=>{var he,Se,xe,Ve;let E=document.createElement("div"),P=(()=>{var Oe;let W=s.find(Ae=>Ae.renderLoadingIndicator);if(W!=null&&W.renderLoadingIndicator)return W.renderLoadingIndicator;if((Oe=n.loadingIndicator)!=null&&Oe.render)return n.loadingIndicator.render})(),R=new Set;g.forEach(W=>{var ge,Bt;R.add(W.id);let Oe=Il(W,Dr),Ae=Wl(zn,W.id,Oe);if(Ae){E.appendChild(Ae.cloneNode(!0));return}let ye=null,He=s.find(pt=>!!(W.variant==="reasoning"&&pt.renderReasoning||W.variant==="tool"&&pt.renderToolCall||W.variant==="approval"&&pt.renderApproval||!W.variant&&pt.renderMessage)),mt=(ge=n.layout)==null?void 0:ge.messages;if(He)if(W.variant==="reasoning"&&W.reasoning&&He.renderReasoning){if(!ne)return;ye=He.renderReasoning({message:W,defaultRenderer:()=>vs(W),config:n})}else if(W.variant==="tool"&&W.toolCall&&He.renderToolCall){if(!Me)return;ye=He.renderToolCall({message:W,defaultRenderer:()=>Cs(W,n),config:n})}else if(W.variant==="approval"&&W.approval&&He.renderApproval){if(n.approval===!1)return;ye=He.renderApproval({message:W,defaultRenderer:()=>ws(W,n),config:n})}else He.renderMessage&&(ye=He.renderMessage({message:W,defaultRenderer:()=>{let pt=lo(W,y,mt,n.messageActions,Ze,{loadingIndicatorRenderer:P,widgetConfig:n});return W.role!=="user"&&Es(pt,W,n,H),pt},config:n}));if(!ye&&W.role==="assistant"&&!W.variant&&n.enableComponentStreaming!==!1&&Ws(W)){let rn=Rs(W);if(rn){let Vt=Ps(rn,{config:n,message:W,transform:y});if(Vt)if(n.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-${W.id}`,$t.setAttribute("data-message-id",W.id),W.content&&W.content.trim()){let gn=document.createElement("div");gn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",gn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),$t.appendChild(gn)}$t.appendChild(Vt),ye=$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-${W.id}`,$t.setAttribute("data-message-id",W.id),$t.setAttribute("data-persona-component-directive","true"),W.content&&W.content.trim()){let gn=document.createElement("div");gn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",gn.innerHTML=y({text:W.content,message:W,streaming:!!W.streaming,raw:W.rawContent}),$t.appendChild(gn)}$t.appendChild(Vt),ye=$t}}}if(!ye)if(W.variant==="reasoning"&&W.reasoning){if(!ne)return;ye=vs(W)}else if(W.variant==="tool"&&W.toolCall){if(!Me)return;ye=Cs(W,n)}else if(W.variant==="approval"&&W.approval){if(n.approval===!1)return;ye=ws(W,n)}else{let pt=(Bt=n.layout)==null?void 0:Bt.messages;pt!=null&&pt.renderUserMessage&&W.role==="user"?ye=pt.renderUserMessage({message:W,config:n,streaming:!!W.streaming}):pt!=null&&pt.renderAssistantMessage&&W.role==="assistant"?ye=pt.renderAssistantMessage({message:W,config:n,streaming:!!W.streaming}):ye=lo(W,y,pt,n.messageActions,Ze,{loadingIndicatorRenderer:P,widgetConfig:n}),W.role!=="user"&&ye&&Es(ye,W,n,H)}let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id=`wrapper-${W.id}`,Ke.setAttribute("data-wrapper-id",W.id),W.role==="user"&&Ke.classList.add("persona-justify-end"),(ye==null?void 0:ye.getAttribute("data-persona-component-directive"))==="true"&&Ke.classList.add("persona-w-full"),Ke.appendChild(ye),Rl(zn,W.id,Oe,Ke),E.appendChild(Ke)}),Hl(zn,R);let V=g.some(W=>W.role==="assistant"&&W.streaming),N=g[g.length-1],ae=(N==null?void 0:N.role)==="assistant"&&!N.streaming&&N.variant!=="approval";if(jn&&g.some(W=>W.role==="user")&&!V&&!ae){let W={config:n,streaming:!0,location:"standalone",defaultRenderer:Mr},Oe=s.find(ye=>ye.renderLoadingIndicator),Ae=null;if(Oe!=null&&Oe.renderLoadingIndicator&&(Ae=Oe.renderLoadingIndicator(W)),Ae===null&&((he=n.loadingIndicator)!=null&&he.render)&&(Ae=n.loadingIndicator.render(W)),Ae===null&&(Ae=Mr()),Ae){let ye=document.createElement("div"),He=((Se=n.loadingIndicator)==null?void 0:Se.showBubble)!==!1;ye.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-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(" "),ye.setAttribute("data-typing-indicator","true"),ye.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",ye.appendChild(Ae);let mt=document.createElement("div");mt.className="persona-flex",mt.id="wrapper-typing-indicator",mt.setAttribute("data-wrapper-id","typing-indicator"),mt.appendChild(ye),E.appendChild(mt)}}if(!jn&&g.length>0){let W=g[g.length-1],Oe={config:n,lastMessage:W,messageCount:g.length},Ae=s.find(He=>He.renderIdleIndicator),ye=null;if(Ae!=null&&Ae.renderIdleIndicator&&(ye=Ae.renderIdleIndicator(Oe)),ye===null&&((xe=n.loadingIndicator)!=null&&xe.renderIdle)&&(ye=n.loadingIndicator.renderIdle(Oe)),ye){let He=document.createElement("div"),mt=((Ve=n.loadingIndicator)==null?void 0:Ve.showBubble)!==!1;He.className=mt?["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(ye);let Ke=document.createElement("div");Ke.className="persona-flex",Ke.id="wrapper-idle-indicator",Ke.setAttribute("data-wrapper-id","idle-indicator"),Ke.appendChild(He),E.appendChild(Ke)}}Ll(l,E),hn&&!yn&&requestAnimationFrame(()=>{requestAnimationFrame(()=>{if(!hn||yn)return;let W=yo();bo(W)})})},rr=()=>{var N,ae,he,Se,xe;if(!b)return;let l=_t(n),g=(N=e.ownerDocument.defaultView)!=null?N:window,y=(he=(ae=n.launcher)==null?void 0:ae.mobileBreakpoint)!=null?he:640,E=(xe=(Se=n.launcher)==null?void 0:Se.mobileFullscreen)!=null?xe:!0,L=g.innerWidth<=y,P=E&&L&&b,R=Cn(n).reveal;k?(ke.style.removeProperty("display"),ke.style.display=l?"flex":"",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-95","persona-opacity-0"),D.classList.add("persona-scale-100","persona-opacity-100"),$e?$e.element.style.display="none":qe&&(qe.style.display="none")):(l?l&&(R==="overlay"||R==="push")&&!P?(ke.style.removeProperty("display"),ke.style.display="flex",ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.setProperty("display","none","important"),ke.classList.remove("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ke.style.display="",ke.classList.add("persona-pointer-events-none","persona-opacity-0"),D.classList.remove("persona-scale-100","persona-opacity-100"),D.classList.add("persona-scale-95","persona-opacity-0")),$e?$e.element.style.display=l?"none":"":qe&&(qe.style.display=l?"none":""))},bt=(l,g="user")=>{if(!b||k===l)return;let y=k;k=l,rr(),k&&(Lt(),tr(!0));let E={open:k,source:g,timestamp:Date.now()};k&&!y?o.emit("widget:opened",E):!k&&y&&o.emit("widget:closed",E),o.emit("widget:state",{open:k,launcherEnabled:b,voiceActive:Je.active,streaming:H.isStreaming()})},hr=l=>{G.disabled=l,T&&(T.disabled=l),_n.buttons.forEach(g=>{g.disabled=l}),it.dataset.personaComposerStreaming=l?"true":"false",it.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(g=>{(g instanceof HTMLButtonElement||g instanceof HTMLInputElement||g instanceof HTMLTextAreaElement||g instanceof HTMLSelectElement)&&(g.disabled=l)})},yr=()=>{Je.active||Z&&Z.focus()};o.on("widget:opened",()=>{n.autoFocusInput&&setTimeout(()=>yr(),200)});let _r=()=>{var y,E,L,P,R,V,N,ae,he,Se,xe;jt.textContent=(E=(y=n.copy)==null?void 0:y.welcomeTitle)!=null?E:"Hello \u{1F44B}",zt.textContent=(P=(L=n.copy)==null?void 0:L.welcomeSubtitle)!=null?P:"Ask anything about your account or products.",Z.placeholder=(V=(R=n.copy)==null?void 0:R.inputPlaceholder)!=null?V:"How can I help...";let l=z.querySelector("[data-persona-intro-card]");if(l){let Ve=((N=n.copy)==null?void 0:N.showWelcomeCard)!==!1;l.style.display=Ve?"":"none",Ve?(z.classList.remove("persona-gap-3"),z.classList.add("persona-gap-6")):(z.classList.remove("persona-gap-6"),z.classList.add("persona-gap-3"))}(he=(ae=n.sendButton)==null?void 0:ae.useIcon)!=null&&he||(G.textContent=(xe=(Se=n.copy)==null?void 0:Se.sendButtonLabel)!=null?xe:"Send"),Z.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',Z.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=>{f(g=>({...g,sessionId:l}))}}),H=new to(n,{onMessagesChanged(l){nr(oe,l,_),H&&(l.some(L=>L.role==="user")?_n.render([],H,Z,l):_n.render(n.suggestionChips,H,Z,l,n.suggestionChipsConfig)),tr(!jn),xo(l);let g=[...l].reverse().find(E=>E.role==="user"),y=Je.lastUserMessageId;g&&g.id!==y&&(Je.lastUserMessageId=g.id,o.emit("user:message",g)),Je.lastUserMessageWasVoice=!!(g!=null&&g.viaVoice),Fr(l)},onStatusChanged(l){var E;let g=(E=n.statusIndicator)!=null?E:{};nt(St,(L=>{var P,R,V,N;return L==="idle"?(P=g.idleText)!=null?P:Gt.idle:L==="connecting"?(R=g.connectingText)!=null?R:Gt.connecting:L==="connected"?(V=g.connectedText)!=null?V:Gt.connected:L==="error"?(N=g.errorText)!=null?N:Gt.error:Gt[L]})(l),g,l)},onStreamingChanged(l){jn=l,hr(l),H&&nr(oe,H.getMessages(),_),l||tr(!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":xn(),Co();break;case"speaking":xn(),wo();break;default:l==="idle"&&H.isBargeInActive()?(xn(),qn(),T==null||T.setAttribute("aria-label","End voice session")):(Je.active=!1,xn(),pn("system"),tn());break}},onArtifactsState(l){fn=l,En()}}),$n.current=H,((pa=(da=n.voiceRecognition)==null?void 0:da.provider)==null?void 0:pa.type)==="runtype")try{H.setupVoice()}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",l)}n.clientToken&&H.initClientSession().catch(l=>{n.debug&&console.warn("[AgentWidget] Pre-init client session failed:",l)}),q&&H.setSSEEventCallback((l,g)=>{q==null||q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l,timestamp:Date.now(),payload:JSON.stringify(g)})}),p&&p.then(l=>{var g;l&&(l.metadata&&(i=Ds(l.metadata),A.syncFromMetadata()),(g=l.messages)!=null&&g.length&&H.hydrateMessages(l.messages))}).catch(l=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",l)});let jr=l=>{var L;l.preventDefault();let g=Z.value.trim(),y=(L=fe==null?void 0:fe.hasAttachments())!=null?L:!1;if(!g&&!y)return;let E;y&&(E=[],E.push(...fe.getContentParts()),g&&E.push(gs(g))),Z.value="",Z.style.height="auto",H.sendMessage(g,{contentParts:E}),y&&fe.clearAttachments()},zr=l=>{l.key==="Enter"&&!l.shiftKey&&(l.preventDefault(),G.click())},qr=async l=>{var y;if(((y=n.attachments)==null?void 0:y.enabled)!==!0||!fe)return;let g=up(l.clipboardData);g.length!==0&&(l.preventDefault(),await fe.handleFiles(g))},Xt=null,cn=!1,Bn=null,De=null,Vr=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,or=(l="user")=>{var P,R,V,N,ae,he,Se;if(cn||H.isStreaming())return;let g=Vr();if(!g)return;Xt=new g;let E=(R=((P=n.voiceRecognition)!=null?P:{}).pauseDuration)!=null?R:2e3;Xt.continuous=!0,Xt.interimResults=!0,Xt.lang="en-US";let L=Z.value;Xt.onresult=xe=>{let Ve="",W="";for(let Ae=0;Ae<xe.results.length;Ae++){let ye=xe.results[Ae],He=ye[0].transcript;ye.isFinal?Ve+=He+" ":W=He}let Oe=L+Ve+W;Z.value=Oe,Bn&&clearTimeout(Bn),(Ve||W)&&(Bn=window.setTimeout(()=>{let Ae=Z.value.trim();Ae&&Xt&&cn&&(bn(),Z.value="",Z.style.height="auto",H.sendMessage(Ae,{viaVoice:!0}))},E))},Xt.onerror=xe=>{xe.error!=="no-speech"&&bn()},Xt.onend=()=>{if(cn){let xe=Z.value.trim();xe&&xe!==L.trim()&&(Z.value="",Z.style.height="auto",H.sendMessage(xe,{viaVoice:!0})),bn()}};try{if(Xt.start(),cn=!0,Je.active=!0,l!=="system"&&(Je.manuallyDeactivated=!1),pn(l),tn(),T){let xe=(V=n.voiceRecognition)!=null?V:{};De={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(N=xe.iconName)!=null?N:"mic",iconSize:parseFloat((Se=(he=xe.iconSize)!=null?he:(ae=n.sendButton)==null?void 0:ae.size)!=null?Se:"40")||24};let Ve=xe.recordingBackgroundColor,W=xe.recordingIconColor,Oe=xe.recordingBorderColor;if(T.classList.add("persona-voice-recording"),T.style.backgroundColor=Ve!=null?Ve:"var(--persona-voice-recording-bg, #ef4444)",T.style.color=W!=null?W:"var(--persona-voice-recording-indicator, #ffffff)",W){let Ae=T.querySelector("svg");Ae&&Ae.setAttribute("stroke",W)}Oe&&(T.style.borderColor=Oe),T.setAttribute("aria-label","Stop voice recognition")}}catch{bn("system")}},bn=(l="user")=>{if(cn){if(cn=!1,Bn&&(clearTimeout(Bn),Bn=null),Xt){try{Xt.stop()}catch{}Xt=null}if(Je.active=!1,pn(l),tn(),T){if(T.classList.remove("persona-voice-recording"),De){T.style.backgroundColor=De.backgroundColor,T.style.color=De.color,T.style.borderColor=De.borderColor;let g=T.querySelector("svg");g&&g.setAttribute("stroke",De.color||"currentColor"),De=null}T.setAttribute("aria-label","Start voice recognition")}}},vo=(l,g)=>{var ye,He,mt,Ke,ge,Bt,pt,rn;let y=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),E=((ye=l==null?void 0:l.provider)==null?void 0:ye.type)==="runtype";if(!(y||E))return null;let P=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("aria-label","Start voice recognition");let V=(He=l==null?void 0:l.iconName)!=null?He:"mic",N=(mt=g==null?void 0:g.size)!=null?mt:"40px",ae=(Ke=l==null?void 0:l.iconSize)!=null?Ke:N,he=parseFloat(ae)||24,Se=(ge=l==null?void 0:l.backgroundColor)!=null?ge:g==null?void 0:g.backgroundColor,xe=(Bt=l==null?void 0:l.iconColor)!=null?Bt:g==null?void 0:g.textColor;R.style.width=ae,R.style.height=ae,R.style.minWidth=ae,R.style.minHeight=ae,R.style.fontSize="18px",R.style.lineHeight="1",xe?R.style.color=xe:R.style.color="var(--persona-text, #111827)";let W=me(V,he,xe||"currentColor",1.5);W?R.appendChild(W):R.textContent="\u{1F3A4}",Se?R.style.backgroundColor=Se:R.style.backgroundColor="",l!=null&&l.borderWidth&&(R.style.borderWidth=l.borderWidth,R.style.borderStyle="solid"),l!=null&&l.borderColor&&(R.style.borderColor=l.borderColor),l!=null&&l.paddingX&&(R.style.paddingLeft=l.paddingX,R.style.paddingRight=l.paddingX),l!=null&&l.paddingY&&(R.style.paddingTop=l.paddingY,R.style.paddingBottom=l.paddingY),P.appendChild(R);let Oe=(pt=l==null?void 0:l.tooltipText)!=null?pt:"Start voice recognition";if(((rn=l==null?void 0:l.showTooltip)!=null?rn:!1)&&Oe){let Vt=h("div","persona-send-button-tooltip");Vt.textContent=Oe,P.appendChild(Vt)}return{micButton:R,micButtonWrapper:P}},br=()=>{var g,y,E,L,P;if(!T||De)return;let l=(g=n.voiceRecognition)!=null?g:{};De={backgroundColor:T.style.backgroundColor,color:T.style.color,borderColor:T.style.borderColor,iconName:(y=l.iconName)!=null?y:"mic",iconSize:parseFloat((P=(L=l.iconSize)!=null?L:(E=n.sendButton)==null?void 0:E.size)!=null?P:"40")||24}},xr=(l,g)=>{var P,R,V,N,ae;if(!T)return;let y=T.querySelector("svg");y&&y.remove();let E=(ae=De==null?void 0:De.iconSize)!=null?ae:parseFloat((N=(V=(P=n.voiceRecognition)==null?void 0:P.iconSize)!=null?V:(R=n.sendButton)==null?void 0:R.size)!=null?N:"40")||24,L=me(l,E,g,1.5);L&&T.appendChild(L)},sr=()=>{T&&T.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},qn=()=>{var L;if(!T)return;br();let l=(L=n.voiceRecognition)!=null?L:{},g=l.recordingBackgroundColor,y=l.recordingIconColor,E=l.recordingBorderColor;if(sr(),T.classList.add("persona-voice-recording"),T.style.backgroundColor=g!=null?g:"var(--persona-voice-recording-bg, #ef4444)",T.style.color=y!=null?y:"var(--persona-voice-recording-indicator, #ffffff)",y){let P=T.querySelector("svg");P&&P.setAttribute("stroke",y)}E&&(T.style.borderColor=E),T.setAttribute("aria-label","Stop voice recognition")},Co=()=>{var V,N,ae,he,Se,xe,Ve,W;if(!T)return;br();let l=(V=n.voiceRecognition)!=null?V:{},g=H.getVoiceInterruptionMode(),y=(N=l.processingIconName)!=null?N:"loader",E=(he=(ae=l.processingIconColor)!=null?ae:De==null?void 0:De.color)!=null?he:"",L=(xe=(Se=l.processingBackgroundColor)!=null?Se:De==null?void 0:De.backgroundColor)!=null?xe:"",P=(W=(Ve=l.processingBorderColor)!=null?Ve:De==null?void 0:De.borderColor)!=null?W:"";sr(),T.classList.add("persona-voice-processing"),T.style.backgroundColor=L,T.style.borderColor=P;let R=E||"currentColor";T.style.color=R,xr(y,R),T.setAttribute("aria-label","Processing voice input"),g==="none"&&(T.style.cursor="default")},wo=()=>{var ae,he,Se,xe,Ve,W,Oe,Ae,ye,He,mt,Ke;if(!T)return;br();let l=(ae=n.voiceRecognition)!=null?ae:{},g=H.getVoiceInterruptionMode(),y=g==="cancel"?"square":g==="barge-in"?"mic":"volume-2",E=(he=l.speakingIconName)!=null?he:y,L=(W=l.speakingIconColor)!=null?W:g==="barge-in"?(xe=(Se=l.recordingIconColor)!=null?Se:De==null?void 0:De.color)!=null?xe:"":(Ve=De==null?void 0:De.color)!=null?Ve:"",P=(ye=l.speakingBackgroundColor)!=null?ye:g==="barge-in"?(Oe=l.recordingBackgroundColor)!=null?Oe:"var(--persona-voice-recording-bg, #ef4444)":(Ae=De==null?void 0:De.backgroundColor)!=null?Ae:"",R=(Ke=l.speakingBorderColor)!=null?Ke:g==="barge-in"?(He=l.recordingBorderColor)!=null?He:"":(mt=De==null?void 0:De.borderColor)!=null?mt:"";sr(),T.classList.add("persona-voice-speaking"),T.style.backgroundColor=P,T.style.borderColor=R;let V=L||"currentColor";T.style.color=V,xr(E,V);let N=g==="cancel"?"Stop playback and re-record":g==="barge-in"?"Speak to interrupt":"Agent is speaking";T.setAttribute("aria-label",N),g==="none"&&(T.style.cursor="default"),g==="barge-in"&&T.classList.add("persona-voice-recording")},xn=()=>{var l,g,y;T&&(sr(),De&&(T.style.backgroundColor=(l=De.backgroundColor)!=null?l:"",T.style.color=(g=De.color)!=null?g:"",T.style.borderColor=(y=De.borderColor)!=null?y:"",xr(De.iconName,De.color||"currentColor"),De=null),T.style.cursor="",T.setAttribute("aria-label","Start voice recognition"))},ar=()=>{var l,g;if(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"){let y=H.getVoiceStatus(),E=H.getVoiceInterruptionMode();if(E==="none"&&(y==="processing"||y==="speaking"))return;if(E==="cancel"&&(y==="processing"||y==="speaking")){H.stopVoicePlayback();return}if(H.isBargeInActive()){H.stopVoicePlayback(),H.deactivateBargeIn().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,tn(),pn("user"),xn()});return}H.toggleVoice().then(()=>{Je.active=H.isVoiceActive(),Je.manuallyDeactivated=!H.isVoiceActive(),tn(),pn("user"),H.isVoiceActive()?qn():xn()});return}if(cn){let y=Z.value.trim();Je.manuallyDeactivated=!0,tn(),bn("user"),y&&(Z.value="",Z.style.height="auto",H.sendMessage(y))}else Je.manuallyDeactivated=!1,tn(),or("user")};Re=ar,T&&(T.addEventListener("click",ar),Et.push(()=>{var l,g;((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?(H.isVoiceActive()&&H.toggleVoice(),xn()):bn("system"),T&&T.removeEventListener("click",ar)}));let Q=o.on("assistant:complete",()=>{$r&&(Je.active||Je.manuallyDeactivated||$r==="assistant"&&!Je.lastUserMessageWasVoice||setTimeout(()=>{var l,g;!Je.active&&!Je.manuallyDeactivated&&(((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.toggleVoice().then(()=>{Je.active=H.isVoiceActive(),pn("auto"),H.isVoiceActive()&&qn()}):or("auto"))},600))});Et.push(Q);let Xe=o.on("action:resubmit",()=>{setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)});Et.push(Xe);let ot=()=>{bt(!k,"user")},$e=null,qe=null;if(b){let l=s.find(g=>g.renderLauncher);if(l!=null&&l.renderLauncher){let g=l.renderLauncher({config:n,defaultRenderer:()=>so(n,ot).element,onToggle:ot});g&&(qe=g)}qe||($e=so(n,ot))}$e?e.appendChild($e.element):qe&&e.appendChild(qe),rr(),_n.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),_r(),hr(H.isStreaming()),tr(!0),fo(),M&&(b?k&&setTimeout(()=>yr(),200):setTimeout(()=>yr(),0));let Lt=()=>{var N,ae,he,Se,xe,Ve,W,Oe,Ae,ye,He,mt,Ke;let l=_t(n),g=(ae=(N=n.launcher)==null?void 0:N.sidebarMode)!=null?ae:!1,y=l||g||((Se=(he=n.launcher)==null?void 0:he.fullHeight)!=null?Se:!1),E=(xe=e.ownerDocument.defaultView)!=null?xe:window,L=(W=(Ve=n.launcher)==null?void 0:Ve.mobileFullscreen)!=null?W:!0,P=(Ae=(Oe=n.launcher)==null?void 0:Oe.mobileBreakpoint)!=null?Ae:640,R=E.innerWidth<=P,V=L&&R&&b;try{if(V){Qn(),dr(e,n);return}if(O&&(O=!1,Qn(),dr(e,n)),!b&&!l){D.style.height="",D.style.width="";return}if(!g&&!l){let ge=(He=(ye=n==null?void 0:n.launcher)==null?void 0:ye.width)!=null?He:n==null?void 0:n.launcherWidth,Bt=ge!=null?ge:"min(400px, calc(100vw - 24px))";D.style.width=Bt,D.style.maxWidth=Bt}if(Zn(),!y){let ge=E.innerHeight,Bt=64,pt=(Ke=(mt=n.launcher)==null?void 0:mt.heightOffset)!=null?Ke:0,rn=Math.max(200,ge-Bt),Vt=Math.min(640,rn),Zt=Math.max(200,Vt-pt);D.style.height=`${Zt}px`}}finally{rr()}};Lt();let Tt=(ua=e.ownerDocument.defaultView)!=null?ua:window;Tt.addEventListener("resize",Lt),Et.push(()=>Tt.removeEventListener("resize",Lt)),er=z.scrollTop;let C=()=>{let l=z.scrollTop,g=z.scrollHeight,y=z.clientHeight,E=g-l-y,L=Math.abs(l-er);if(er=l,!mr&&!(L<=mo)){if(!hn&&E<Or){yn=!1,hn=!0;return}hn&&E>Or&&(yn=!0,gr=Date.now()+go,hn=!1)}};z.addEventListener("scroll",C,{passive:!0}),Et.push(()=>z.removeEventListener("scroll",C)),Et.push(()=>{Rn&&cancelAnimationFrame(Rn)});let Ne=()=>{J&&(Mn&&(J.removeEventListener("click",Mn),Mn=null),b?(J.style.display="",Mn=()=>{bt(!1,"user")},J.addEventListener("click",Mn)):J.style.display="none")};Ne(),(()=>{let{clearChatButton:l}=se;l&&l.addEventListener("click",()=>{H.clearMessages(),zn.clear();try{localStorage.removeItem(Wr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wr}`)}catch(y){console.error("[AgentWidget] Failed to clear default localStorage:",y)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wr)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(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",E)})}catch(y){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",y)}i={},A.syncFromMetadata(),q==null||q.clear(),K==null||K.update()})})(),Ue&&Ue.addEventListener("submit",jr),Z==null||Z.addEventListener("keydown",zr),Z==null||Z.addEventListener("paste",qr),Et.push(()=>{Ue&&Ue.removeEventListener("submit",jr),Z==null||Z.removeEventListener("keydown",zr),Z==null||Z.removeEventListener("paste",qr)}),Et.push(()=>{H.cancel()}),$e?Et.push(()=>{$e==null||$e.destroy()}):qe&&Et.push(()=>{qe==null||qe.remove()});let w={update(l){var xa,va,Ca,wa,Sa,Aa,Ea,Ta,Ma,ka,La,Ia,Pa,Wa,Ra,Ha,Ba,Da,Na,Oa,$a,Fa,_a,ja,za,qa,Va,Ua,Ja,Ka,Ga,Ya,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,Ii,Pi,Wi,Ri,Hi,Bi,Di,Ni,Oi,$i,Fi,_i,ji,zi,qi,Vi,Ui,Ji,Ki,Gi,Yi,Xi,Zi,Qi,el,tl,nl,rl,ol,sl,al;let g=n.toolCall,y=n.messageActions,E=(xa=n.layout)==null?void 0:xa.messages,L=n.colorScheme,P=n.loadingIndicator,R=n.iterationDisplay;n={...n,...l},Qn(),dr(e,n),qo(e,n),Vo(e,n),En(),n.colorScheme!==L&&Br();let V=Uo.getForInstance(n.plugins);s.length=0,s.push(...V),b=(Ca=(va=n.launcher)==null?void 0:va.enabled)!=null?Ca:!0,x=(Sa=(wa=n.launcher)==null?void 0:wa.autoExpand)!=null?Sa:!1,ne=(Ea=(Aa=n.features)==null?void 0:Aa.showReasoning)!=null?Ea:!0,Me=(Ma=(Ta=n.features)==null?void 0:Ta.showToolCalls)!=null?Ma:!0;let N=le;if(le=(La=(ka=n.features)==null?void 0:ka.showEventStreamToggle)!=null?La:!1,le&&!N){if(q||(Y=new po(de),q=new co(ce,Y),Y.open().then(()=>q==null?void 0:q.restore()).catch(()=>{}),H.setSSEEventCallback((j,st)=>{q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:j,timestamp:Date.now(),payload:JSON.stringify(st)})})),!_e&&Qe){let j=(Pa=(Ia=n.features)==null?void 0:Ia.eventStream)==null?void 0:Pa.classNames,st="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(j!=null&&j.toggleButton?" "+j.toggleButton:"");_e=h("button",st),_e.style.width="28px",_e.style.height="28px",_e.style.color=sn.actionIconColor,_e.type="button",_e.setAttribute("aria-label","Event Stream"),_e.title="Event Stream";let xt=me("activity","18px","currentColor",1.5);xt&&_e.appendChild(xt);let Fe=se.clearChatButtonWrapper,at=se.closeButtonWrapper,Dt=Fe||at;Dt&&Dt.parentNode===Qe?Qe.insertBefore(_e,Dt):Qe.appendChild(_e),_e.addEventListener("click",()=>{Ce?At():rt()})}}else!le&&N&&(At(),_e&&(_e.remove(),_e=null),q==null||q.clear(),Y==null||Y.destroy(),q=null,Y=null);if(((Wa=n.launcher)==null?void 0:Wa.enabled)===!1&&$e&&($e.destroy(),$e=null),((Ra=n.launcher)==null?void 0:Ra.enabled)===!1&&qe&&(qe.remove(),qe=null),((Ha=n.launcher)==null?void 0:Ha.enabled)!==!1&&!$e&&!qe){let j=s.find(st=>st.renderLauncher);if(j!=null&&j.renderLauncher){let st=j.renderLauncher({config:n,defaultRenderer:()=>so(n,ot).element,onToggle:ot});st&&(qe=st,e.appendChild(qe))}qe||($e=so(n,ot),e.appendChild($e.element))}$e&&$e.update(n),ht&&((Ba=n.launcher)==null?void 0:Ba.title)!==void 0&&(ht.textContent=n.launcher.title),yt&&((Da=n.launcher)==null?void 0:Da.subtitle)!==void 0&&(yt.textContent=n.launcher.subtitle);let ae=(Na=n.layout)==null?void 0:Na.header;if((ae==null?void 0:ae.layout)!==I&&Qe){let j=ae?ao(n,ae,{showClose:b,onClose:()=>bt(!1,"user")}):Jn({config:n,showClose:b,onClose:()=>bt(!1,"user")});Qe.replaceWith(j.header),Qe=j.header,Pe=j.iconHolder,ht=j.headerTitle,yt=j.headerSubtitle,J=j.closeButton,I=ae==null?void 0:ae.layout}else if(ae&&(Pe&&(Pe.style.display=ae.showIcon===!1?"none":""),ht&&(ht.style.display=ae.showTitle===!1?"none":""),yt&&(yt.style.display=ae.showSubtitle===!1?"none":""),J&&(J.style.display=ae.showCloseButton===!1?"none":""),se.clearChatButtonWrapper)){let j=ae.showClearChat;if(j!==void 0){se.clearChatButtonWrapper.style.display=j?"":"none";let{closeButtonWrapper:st}=se;st&&!st.classList.contains("persona-absolute")&&(j?st.classList.remove("persona-ml-auto"):st.classList.add("persona-ml-auto"))}}let Se=((Oa=n.layout)==null?void 0:Oa.showHeader)!==!1;Qe&&(Qe.style.display=Se?"":"none");let xe=(($a=n.layout)==null?void 0:$a.showFooter)!==!1;it&&(it.style.display=xe?"":"none"),b!==S?b?bt(x,"auto"):(k=!0,rr()):x!==F&&bt(x,"auto"),F=x,S=b,Lt(),Ne();let Oe=JSON.stringify(l.toolCall)!==JSON.stringify(g),Ae=JSON.stringify(n.messageActions)!==JSON.stringify(y),ye=JSON.stringify((Fa=n.layout)==null?void 0:Fa.messages)!==JSON.stringify(E),He=((_a=n.loadingIndicator)==null?void 0:_a.render)!==(P==null?void 0:P.render)||((ja=n.loadingIndicator)==null?void 0:ja.renderIdle)!==(P==null?void 0:P.renderIdle)||((za=n.loadingIndicator)==null?void 0:za.showBubble)!==(P==null?void 0:P.showBubble),mt=n.iterationDisplay!==R;(Oe||Ae||ye||He||mt)&&H&&(Dr++,nr(oe,H.getMessages(),_));let ge=(qa=n.launcher)!=null?qa:{},Bt=(Va=ge.headerIconHidden)!=null?Va:!1,pt=(Ja=(Ua=n.layout)==null?void 0:Ua.header)==null?void 0:Ja.showIcon,rn=Bt||pt===!1,Vt=ge.headerIconName,Zt=(Ka=ge.headerIconSize)!=null?Ka:"48px";if(Pe){let j=te.querySelector(".persona-border-b-persona-divider"),st=j==null?void 0:j.querySelector(".persona-flex-col");if(rn)Pe.style.display="none",j&&st&&!j.contains(st)&&j.insertBefore(st,j.firstChild);else{if(Pe.style.display="",Pe.style.height=Zt,Pe.style.width=Zt,j&&st&&(j.contains(Pe)?Pe.nextSibling!==st&&(Pe.remove(),j.insertBefore(Pe,st)):j.insertBefore(Pe,st)),Vt){let Fe=parseFloat(Zt)||24,at=me(Vt,Fe*.6,"#ffffff",2);at?Pe.replaceChildren(at):Pe.textContent=(Ga=ge.agentIconText)!=null?Ga:"\u{1F4AC}"}else if(ge.iconUrl){let Fe=Pe.querySelector("img");if(Fe)Fe.src=ge.iconUrl,Fe.style.height=Zt,Fe.style.width=Zt;else{let at=document.createElement("img");at.src=ge.iconUrl,at.alt="",at.className="persona-rounded-xl persona-object-cover",at.style.height=Zt,at.style.width=Zt,Pe.replaceChildren(at)}}else{let Fe=Pe.querySelector("svg"),at=Pe.querySelector("img");(Fe||at)&&Pe.replaceChildren(),Pe.textContent=(Ya=ge.agentIconText)!=null?Ya:"\u{1F4AC}"}let xt=Pe.querySelector("img");xt&&(xt.style.height=Zt,xt.style.width=Zt)}}let $t=(Za=(Xa=n.layout)==null?void 0:Xa.header)==null?void 0:Za.showTitle,gn=(ei=(Qa=n.layout)==null?void 0:Qa.header)==null?void 0:ei.showSubtitle;if(ht&&(ht.style.display=$t===!1?"none":""),yt&&(yt.style.display=gn===!1?"none":""),J){((ni=(ti=n.layout)==null?void 0:ti.header)==null?void 0:ni.showCloseButton)===!1?J.style.display="none":J.style.display="";let st=(ri=ge.closeButtonSize)!=null?ri:"32px",xt=(oi=ge.closeButtonPlacement)!=null?oi:"inline";J.style.height=st,J.style.width=st;let{closeButtonWrapper:Fe}=se,at=xt==="top-right",Dt=Fe==null?void 0:Fe.classList.contains("persona-absolute");if(Fe&&at!==Dt)if(Fe.remove(),at)Fe.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",te.style.position="relative",te.appendChild(Fe);else{let tt=(ai=(si=ge.clearChat)==null?void 0:si.placement)!=null?ai:"inline",Ft=(li=(ii=ge.clearChat)==null?void 0:ii.enabled)!=null?li:!0;Fe.className=Ft&&tt==="inline"?"":"persona-ml-auto";let on=te.querySelector(".persona-border-b-persona-divider");on&&on.appendChild(Fe)}if(J.style.color=ge.closeButtonColor||sn.actionIconColor,ge.closeButtonBackgroundColor?(J.style.backgroundColor=ge.closeButtonBackgroundColor,J.classList.remove("hover:persona-bg-gray-100")):(J.style.backgroundColor="",J.classList.add("hover:persona-bg-gray-100")),ge.closeButtonBorderWidth||ge.closeButtonBorderColor){let tt=ge.closeButtonBorderWidth||"0px",Ft=ge.closeButtonBorderColor||"transparent";J.style.border=`${tt} solid ${Ft}`,J.classList.remove("persona-border-none")}else J.style.border="",J.classList.add("persona-border-none");ge.closeButtonBorderRadius?(J.style.borderRadius=ge.closeButtonBorderRadius,J.classList.remove("persona-rounded-full")):(J.style.borderRadius="",J.classList.add("persona-rounded-full")),ge.closeButtonPaddingX?(J.style.paddingLeft=ge.closeButtonPaddingX,J.style.paddingRight=ge.closeButtonPaddingX):(J.style.paddingLeft="",J.style.paddingRight=""),ge.closeButtonPaddingY?(J.style.paddingTop=ge.closeButtonPaddingY,J.style.paddingBottom=ge.closeButtonPaddingY):(J.style.paddingTop="",J.style.paddingBottom="");let Kt=(ci=ge.closeButtonIconName)!=null?ci:"x",vn=(di=ge.closeButtonIconText)!=null?di:"\xD7";J.innerHTML="";let Qt=me(Kt,"20px","currentColor",2);Qt?J.appendChild(Qt):J.textContent=vn;let kt=(pi=ge.closeButtonTooltipText)!=null?pi:"Close chat",dn=(ui=ge.closeButtonShowTooltip)!=null?ui:!0;if(J.setAttribute("aria-label",kt),Fe&&(Fe._cleanupTooltip&&(Fe._cleanupTooltip(),delete Fe._cleanupTooltip),dn&&kt)){let tt=null,Ft=()=>{if(tt||!J)return;let ir=J.ownerDocument,Kr=ir.body;if(!Kr)return;tt=Ln(ir,"div","persona-clear-chat-tooltip"),tt.textContent=kt;let Gr=Ln(ir,"div");Gr.className="persona-clear-chat-tooltip-arrow",tt.appendChild(Gr);let lr=J.getBoundingClientRect();tt.style.position="fixed",tt.style.left=`${lr.left+lr.width/2}px`,tt.style.top=`${lr.top-8}px`,tt.style.transform="translate(-50%, -100%)",Kr.appendChild(tt)},on=()=>{tt&&tt.parentNode&&(tt.parentNode.removeChild(tt),tt=null)};Fe.addEventListener("mouseenter",Ft),Fe.addEventListener("mouseleave",on),J.addEventListener("focus",Ft),J.addEventListener("blur",on),Fe._cleanupTooltip=()=>{on(),Fe&&(Fe.removeEventListener("mouseenter",Ft),Fe.removeEventListener("mouseleave",on)),J&&(J.removeEventListener("focus",Ft),J.removeEventListener("blur",on))}}}let{clearChatButton:Ye,clearChatButtonWrapper:wt}=se;if(Ye){let j=(gi=ge.clearChat)!=null?gi:{},st=(mi=j.enabled)!=null?mi:!0,xt=(hi=(fi=n.layout)==null?void 0:fi.header)==null?void 0:hi.showClearChat,Fe=xt!==void 0?xt:st,at=(yi=j.placement)!=null?yi:"inline";if(wt){wt.style.display=Fe?"":"none";let{closeButtonWrapper:Dt}=se;Dt&&!Dt.classList.contains("persona-absolute")&&(Fe?Dt.classList.remove("persona-ml-auto"):Dt.classList.add("persona-ml-auto"));let Kt=at==="top-right",vn=wt.classList.contains("persona-absolute");if(Kt!==vn&&Fe){if(wt.remove(),Kt)wt.className="persona-absolute persona-top-4 persona-z-50",wt.style.right="48px",te.style.position="relative",te.appendChild(wt);else{wt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",wt.style.right="";let kt=te.querySelector(".persona-border-b-persona-divider"),dn=se.closeButtonWrapper;kt&&dn&&dn.parentElement===kt?kt.insertBefore(wt,dn):kt&&kt.appendChild(wt)}let Qt=se.closeButtonWrapper;Qt&&!Qt.classList.contains("persona-absolute")&&(Kt?Qt.classList.add("persona-ml-auto"):Qt.classList.remove("persona-ml-auto"))}}if(Fe){let Dt=(bi=j.size)!=null?bi:"32px";Ye.style.height=Dt,Ye.style.width=Dt;let Kt=(xi=j.iconName)!=null?xi:"refresh-cw",vn=(vi=j.iconColor)!=null?vi:"";Ye.style.color=vn||sn.actionIconColor,Ye.innerHTML="";let Qt=me(Kt,"20px","currentColor",2);if(Qt&&Ye.appendChild(Qt),j.backgroundColor?(Ye.style.backgroundColor=j.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),j.borderWidth||j.borderColor){let tt=j.borderWidth||"0px",Ft=j.borderColor||"transparent";Ye.style.border=`${tt} solid ${Ft}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");j.borderRadius?(Ye.style.borderRadius=j.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),j.paddingX?(Ye.style.paddingLeft=j.paddingX,Ye.style.paddingRight=j.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),j.paddingY?(Ye.style.paddingTop=j.paddingY,Ye.style.paddingBottom=j.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let kt=(Ci=j.tooltipText)!=null?Ci:"Clear chat",dn=(wi=j.showTooltip)!=null?wi:!0;if(Ye.setAttribute("aria-label",kt),wt&&(wt._cleanupTooltip&&(wt._cleanupTooltip(),delete wt._cleanupTooltip),dn&&kt)){let tt=null,Ft=()=>{if(tt||!Ye)return;let ir=Ye.ownerDocument,Kr=ir.body;if(!Kr)return;tt=Ln(ir,"div","persona-clear-chat-tooltip"),tt.textContent=kt;let Gr=Ln(ir,"div");Gr.className="persona-clear-chat-tooltip-arrow",tt.appendChild(Gr);let lr=Ye.getBoundingClientRect();tt.style.position="fixed",tt.style.left=`${lr.left+lr.width/2}px`,tt.style.top=`${lr.top-8}px`,tt.style.transform="translate(-50%, -100%)",Kr.appendChild(tt)},on=()=>{tt&&tt.parentNode&&(tt.parentNode.removeChild(tt),tt=null)};wt.addEventListener("mouseenter",Ft),wt.addEventListener("mouseleave",on),Ye.addEventListener("focus",Ft),Ye.addEventListener("blur",on),wt._cleanupTooltip=()=>{on(),wt&&(wt.removeEventListener("mouseenter",Ft),wt.removeEventListener("mouseleave",on)),Ye&&(Ye.removeEventListener("focus",Ft),Ye.removeEventListener("blur",on))}}}}let So=n.actionParsers&&n.actionParsers.length?n.actionParsers:[Jo],Ao=n.actionHandlers&&n.actionHandlers.length?n.actionHandlers:[Pr.message,Pr.messageAndClick];A=Ko({parsers:So,handlers:Ao,getSessionMetadata:d,updateSessionMetadata:f,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),_=ac(n,A,ie),H.updateConfig(n),nr(oe,H.getMessages(),_),_n.render(n.suggestionChips,H,Z,void 0,n.suggestionChipsConfig),_r(),hr(H.isStreaming());let Eo=((Si=n.voiceRecognition)==null?void 0:Si.enabled)===!0,To=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Mo=((Ei=(Ai=n.voiceRecognition)==null?void 0:Ai.provider)==null?void 0:Ei.type)==="runtype";if(Eo&&(To||Mo))if(!T||!Ee){let j=vo(n.voiceRecognition,n.sendButton);j&&(T=j.micButton,Ee=j.micButtonWrapper,pe.insertBefore(Ee,je),T.addEventListener("click",ar),T.disabled=H.isStreaming())}else{let j=(Ti=n.voiceRecognition)!=null?Ti:{},st=(Mi=n.sendButton)!=null?Mi:{},xt=(ki=j.iconName)!=null?ki:"mic",Fe=(Li=st.size)!=null?Li:"40px",at=(Ii=j.iconSize)!=null?Ii:Fe,Dt=parseFloat(at)||24;T.style.width=at,T.style.height=at,T.style.minWidth=at,T.style.minHeight=at;let Kt=(Wi=(Pi=j.iconColor)!=null?Pi:st.textColor)!=null?Wi:"currentColor";T.innerHTML="";let vn=me(xt,Dt,Kt,2);vn?T.appendChild(vn):T.textContent="\u{1F3A4}";let Qt=(Ri=j.backgroundColor)!=null?Ri:st.backgroundColor;Qt?T.style.backgroundColor=Qt:T.style.backgroundColor="",Kt?T.style.color=Kt:T.style.color="var(--persona-text, #111827)",j.borderWidth?(T.style.borderWidth=j.borderWidth,T.style.borderStyle="solid"):(T.style.borderWidth="",T.style.borderStyle=""),j.borderColor?T.style.borderColor=j.borderColor:T.style.borderColor="",j.paddingX?(T.style.paddingLeft=j.paddingX,T.style.paddingRight=j.paddingX):(T.style.paddingLeft="",T.style.paddingRight=""),j.paddingY?(T.style.paddingTop=j.paddingY,T.style.paddingBottom=j.paddingY):(T.style.paddingTop="",T.style.paddingBottom="");let kt=Ee==null?void 0:Ee.querySelector(".persona-send-button-tooltip"),dn=(Hi=j.tooltipText)!=null?Hi:"Start voice recognition";if(((Bi=j.showTooltip)!=null?Bi:!1)&&dn)if(kt)kt.textContent=dn,kt.style.display="";else{let Ft=document.createElement("div");Ft.className="persona-send-button-tooltip",Ft.textContent=dn,Ee==null||Ee.insertBefore(Ft,T)}else kt&&(kt.style.display="none");Ee.style.display="",T.disabled=H.isStreaming()}else T&&Ee&&(Ee.style.display="none",((Ni=(Di=n.voiceRecognition)==null?void 0:Di.provider)==null?void 0:Ni.type)==="runtype"?H.isVoiceActive()&&H.toggleVoice():cn&&bn());if(((Oi=n.attachments)==null?void 0:Oi.enabled)===!0)if(!be||!re){let j=($i=n.attachments)!=null?$i:{},xt=(_i=((Fi=n.sendButton)!=null?Fi:{}).size)!=null?_i:"40px";ze||(ze=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),ze.style.display="none",Ue.insertBefore(ze,Z)),we||(we=document.createElement("input"),we.type="file",we.accept=((ji=j.allowedTypes)!=null?ji:Dn).join(","),we.multiple=((zi=j.maxFiles)!=null?zi:4)>1,we.style.display="none",we.setAttribute("aria-label","Attach files"),Ue.insertBefore(we,Z)),be=h("div","persona-send-button-wrapper"),re=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),re.type="button",re.setAttribute("aria-label",(qi=j.buttonTooltipText)!=null?qi:"Attach file");let Fe=(Vi=j.buttonIconName)!=null?Vi:"paperclip",at=xt,Dt=parseFloat(at)||40,Kt=Math.round(Dt*.6);re.style.width=at,re.style.height=at,re.style.minWidth=at,re.style.minHeight=at,re.style.fontSize="18px",re.style.lineHeight="1",re.style.backgroundColor="transparent",re.style.color="var(--persona-primary, #111827)",re.style.border="none",re.style.borderRadius="6px",re.style.transition="background-color 0.15s ease",re.addEventListener("mouseenter",()=>{re.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),re.addEventListener("mouseleave",()=>{re.style.backgroundColor="transparent"});let vn=me(Fe,Kt,"currentColor",1.5);vn?re.appendChild(vn):re.textContent="\u{1F4CE}",re.addEventListener("click",dn=>{dn.preventDefault(),we==null||we.click()}),be.appendChild(re);let Qt=(Ui=j.buttonTooltipText)!=null?Ui:"Attach file",kt=h("div","persona-send-button-tooltip");kt.textContent=Qt,be.appendChild(kt),qt.append(be),!fe&&we&&ze&&(fe=Er.fromConfig(j),fe.setPreviewsContainer(ze),we.addEventListener("change",async()=>{fe&&(we!=null&&we.files)&&(await fe.handleFileSelect(we.files),we.value="")}))}else{be.style.display="";let j=(Ji=n.attachments)!=null?Ji:{};we&&(we.accept=((Ki=j.allowedTypes)!=null?Ki:Dn).join(","),we.multiple=((Gi=j.maxFiles)!=null?Gi:4)>1),fe&&fe.updateConfig({allowedTypes:j.allowedTypes,maxFileSize:j.maxFileSize,maxFiles:j.maxFiles})}else be&&(be.style.display="none"),fe&&fe.clearAttachments();let Pt=(Yi=n.sendButton)!=null?Yi:{},ko=(Xi=Pt.useIcon)!=null?Xi:!1,Ur=(Zi=Pt.iconText)!=null?Zi:"\u2191",Jr=Pt.iconName,vr=(Qi=Pt.tooltipText)!=null?Qi:"Send message",Lo=(el=Pt.showTooltip)!=null?el:!1,Vn=(tl=Pt.size)!=null?tl:"40px",Ut=Pt.backgroundColor,Jt=Pt.textColor;if(ko){if(G.style.width=Vn,G.style.height=Vn,G.style.minWidth=Vn,G.style.minHeight=Vn,G.style.fontSize="18px",G.style.lineHeight="1",G.innerHTML="",Jt?G.style.color=Jt:G.style.color="var(--persona-button-primary-fg, #ffffff)",Jr){let j=parseFloat(Vn)||24,st=(Jt==null?void 0:Jt.trim())||"currentColor",xt=me(Jr,j,st,2);xt?G.appendChild(xt):G.textContent=Ur}else G.textContent=Ur;G.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",Ut?(G.style.backgroundColor=Ut,G.classList.remove("persona-bg-persona-primary")):(G.style.backgroundColor="",G.classList.add("persona-bg-persona-primary"))}else G.textContent=(rl=(nl=n.copy)==null?void 0:nl.sendButtonLabel)!=null?rl:"Send",G.style.width="",G.style.height="",G.style.minWidth="",G.style.minHeight="",G.style.fontSize="",G.style.lineHeight="",G.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",Ut?(G.style.backgroundColor=Ut,G.classList.remove("persona-bg-persona-accent")):G.classList.add("persona-bg-persona-accent"),Jt?G.style.color=Jt:G.classList.add("persona-text-white");Pt.borderWidth?(G.style.borderWidth=Pt.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Pt.borderColor?G.style.borderColor=Pt.borderColor:G.style.borderColor="",Pt.paddingX?(G.style.paddingLeft=Pt.paddingX,G.style.paddingRight=Pt.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Pt.paddingY?(G.style.paddingTop=Pt.paddingY,G.style.paddingBottom=Pt.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let kn=je==null?void 0:je.querySelector(".persona-send-button-tooltip");if(Lo&&vr)if(kn)kn.textContent=vr,kn.style.display="";else{let j=document.createElement("div");j.className="persona-send-button-tooltip",j.textContent=vr,je==null||je.insertBefore(j,G)}else kn&&(kn.style.display="none");let as=(ol=n.layout)==null?void 0:ol.contentMaxWidth;as?(oe.style.maxWidth=as,oe.style.marginLeft="auto",oe.style.marginRight="auto",oe.style.width="100%",Ue&&(Ue.style.maxWidth=as,Ue.style.marginLeft="auto",Ue.style.marginRight="auto")):(oe.style.maxWidth="",oe.style.marginLeft="",oe.style.marginRight="",oe.style.width="",Ue&&(Ue.style.maxWidth="",Ue.style.marginLeft="",Ue.style.marginRight=""));let Un=(sl=n.statusIndicator)!=null?sl:{},_c=(al=Un.visible)!=null?al:!0;if(St.style.display=_c?"":"none",H){let j=H.getStatus();nt(St,(xt=>{var Fe,at,Dt,Kt;return xt==="idle"?(Fe=Un.idleText)!=null?Fe:Gt.idle:xt==="connecting"?(at=Un.connectingText)!=null?at:Gt.connecting:xt==="connected"?(Dt=Un.connectedText)!=null?Dt:Gt.connected:xt==="error"?(Kt=Un.errorText)!=null?Kt:Gt.error:Gt[xt]})(j),Un,j)}St.classList.remove("persona-text-left","persona-text-center","persona-text-right");let jc=Un.align==="left"?"persona-text-left":Un.align==="center"?"persona-text-center":"persona-text-right";St.classList.add(jc)},open(){b&&bt(!0,"api")},close(){b&&bt(!1,"api")},toggle(){b&&bt(!k,"api")},clearChat(){en=!1,H.clearMessages(),zn.clear();try{localStorage.removeItem(Wr),n.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Wr}`)}catch(g){console.error("[AgentWidget] Failed to clear default localStorage:",g)}if(n.clearChatHistoryStorageKey&&n.clearChatHistoryStorageKey!==Wr)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={},A.syncFromMetadata(),q==null||q.clear(),K==null||K.update()},setMessage(l){return!Z||H.isStreaming()?!1:(!k&&b&&bt(!0,"system"),Z.value=l,Z.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(l){if(H.isStreaming())return!1;let g=(l==null?void 0:l.trim())||Z.value.trim();return g?(!k&&b&&bt(!0,"system"),Z.value="",Z.style.height="auto",H.sendMessage(g),!0):!1},startVoiceRecognition(){var g,y;return H.isStreaming()?!1:((y=(g=n.voiceRecognition)==null?void 0:g.provider)==null?void 0:y.type)==="runtype"?(H.isVoiceActive()||(!k&&b&&bt(!0,"system"),Je.manuallyDeactivated=!1,tn(),H.toggleVoice().then(()=>{Je.active=H.isVoiceActive(),pn("user"),H.isVoiceActive()&&qn()})),!0):cn?!0:Vr()?(!k&&b&&bt(!0,"system"),Je.manuallyDeactivated=!1,tn(),or("user"),!0):!1},stopVoiceRecognition(){var l,g;return((g=(l=n.voiceRecognition)==null?void 0:l.provider)==null?void 0:g.type)==="runtype"?H.isVoiceActive()?(H.toggleVoice().then(()=>{Je.active=!1,Je.manuallyDeactivated=!0,tn(),pn("user"),xn()}),!0):!1:cn?(Je.manuallyDeactivated=!0,tn(),bn("user"),!0):!1},injectMessage(l){return!k&&b&&bt(!0,"system"),H.injectMessage(l)},injectAssistantMessage(l){!k&&b&&bt(!0,"system");let g=H.injectAssistantMessage(l);return U&&(U=!1,ue&&(clearTimeout(ue),ue=null),setTimeout(()=>{H&&!H.isStreaming()&&H.continueConversation()},100)),g},injectUserMessage(l){return!k&&b&&bt(!0,"system"),H.injectUserMessage(l)},injectSystemMessage(l){return!k&&b&&bt(!0,"system"),H.injectSystemMessage(l)},injectMessageBatch(l){return!k&&b&&bt(!0,"system"),H.injectMessageBatch(l)},injectTestMessage(l){!k&&b&&bt(!0,"system"),H.injectTestEvent(l)},async connectStream(l,g){return H.connectStream(l,g)},__pushEventStreamEvent(l){q&&q.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:l.type,timestamp:Date.now(),payload:JSON.stringify(l.payload)})},showEventStream(){!le||!q||rt()},hideEventStream(){Ce&&At()},isEventStreamVisible(){return Ce},showArtifacts(){mn(n)&&(en=!1,En(),et==null||et.setMobileOpen(!0))},hideArtifacts(){mn(n)&&(en=!0,En())},upsertArtifact(l){return mn(n)?(en=!1,H.upsertArtifact(l)):null},selectArtifact(l){mn(n)&&H.selectArtifact(l)},clearArtifacts(){mn(n)&&H.clearArtifacts()},focusInput(){return b&&!k||!Z?!1:(Z.focus(),!0)},async resolveApproval(l,g){let E=H.getMessages().find(L=>{var P;return L.variant==="approval"&&((P=L.approval)==null?void 0:P.id)===l});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${l}`);return H.resolveApproval(E.approval,g)},getMessages(){return H.getMessages()},getStatus(){return H.getStatus()},getPersistentMetadata(){return{...i}},updatePersistentMetadata(l){f(l)},on(l,g){return o.on(l,g)},off(l,g){o.off(l,g)},isOpen(){return b&&k},isVoiceActive(){return Je.active},getState(){return{open:b&&k,launcherEnabled:b,voiceActive:Je.active,streaming:H.isStreaming()}},showCSATFeedback(l){!k&&b&&bt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=Hs({onSubmit:async(E,L)=>{var P;H.isClientTokenMode()&&await H.submitCSATFeedback(E,L),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(l){!k&&b&&bt(!0,"system");let g=oe.querySelector(".persona-feedback-container");g&&g.remove();let y=Bs({onSubmit:async(E,L)=>{var P;H.isClientTokenMode()&&await H.submitNPSFeedback(E,L),(P=l==null?void 0:l.onSubmit)==null||P.call(l,E,L)},onDismiss:l==null?void 0:l.onDismiss,...l});oe.appendChild(y),y.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(l,g){return H.submitCSATFeedback(l,g)},async submitNPSFeedback(l,g){return H.submitNPSFeedback(l,g)},destroy(){Et.forEach(l=>l()),ke.remove(),$e==null||$e.destroy(),qe==null||qe.remove(),Mn&&J.removeEventListener("click",Mn)}};if((((ga=t==null?void 0:t.debugTools)!=null?ga:!1)||!!n.debug)&&typeof window!="undefined"){let l=window.AgentWidgetBrowser,g={controller:w,getMessages:w.getMessages,getStatus:w.getStatus,getMetadata:w.getPersistentMetadata,updateMetadata:w.updatePersistentMetadata,clearHistory:()=>w.clearChat(),setVoiceActive:y=>y?w.startVoiceRecognition():w.stopVoiceRecognition()};window.AgentWidgetBrowser=g,Et.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=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.focusInput()};if(window.addEventListener("persona:focusInput",g),Et.push(()=>{window.removeEventListener("persona:focusInput",g)}),le){let V=ae=>{let he=ae.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&w.showEventStream()},N=ae=>{let he=ae.detail;(!(he!=null&&he.instanceId)||he.instanceId===l)&&w.hideEventStream()};window.addEventListener("persona:showEventStream",V),window.addEventListener("persona:hideEventStream",N),Et.push(()=>{window.removeEventListener("persona:showEventStream",V),window.removeEventListener("persona:hideEventStream",N)})}let y=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.showArtifacts()},E=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.hideArtifacts()},L=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||N!=null&&N.artifact&&w.upsertArtifact(N.artifact)},P=V=>{let N=V.detail;N!=null&&N.instanceId&&N.instanceId!==l||typeof(N==null?void 0:N.id)=="string"&&w.selectArtifact(N.id)},R=V=>{let N=V.detail;(!(N!=null&&N.instanceId)||N.instanceId===l)&&w.clearArtifacts()};window.addEventListener("persona:showArtifacts",y),window.addEventListener("persona:hideArtifacts",E),window.addEventListener("persona:upsertArtifact",L),window.addEventListener("persona:selectArtifact",P),window.addEventListener("persona:clearArtifacts",R),Et.push(()=>{window.removeEventListener("persona:showArtifacts",y),window.removeEventListener("persona:hideArtifacts",E),window.removeEventListener("persona:upsertArtifact",L),window.removeEventListener("persona:selectArtifact",P),window.removeEventListener("persona:clearArtifacts",R)})}let ee=gp(n.persistState);if(ee&&b){let l=mp(ee.storage),g=`${ee.keyPrefix}widget-open`,y=`${ee.keyPrefix}widget-voice`,E=`${ee.keyPrefix}widget-voice-mode`;if(l){let L=((ma=ee.persist)==null?void 0:ma.openState)&&l.getItem(g)==="true",P=((fa=ee.persist)==null?void 0:fa.voiceState)&&l.getItem(y)==="true",R=((ha=ee.persist)==null?void 0:ha.voiceState)&&l.getItem(E)==="true";if(L&&setTimeout(()=>{w.open(),setTimeout(()=>{var V;if(P||R)w.startVoiceRecognition();else if((V=ee.persist)!=null&&V.focusInput){let N=e.querySelector("textarea");N&&N.focus()}},100)},0),(ya=ee.persist)!=null&&ya.openState&&(o.on("widget:opened",()=>{l.setItem(g,"true")}),o.on("widget:closed",()=>{l.setItem(g,"false")})),(ba=ee.persist)!=null&&ba.voiceState&&(o.on("voice:state",V=>{l.setItem(y,V.active?"true":"false")}),o.on("user:message",V=>{l.setItem(E,V.viaVoice?"true":"false")})),ee.clearOnChatClear){let V=()=>{l.removeItem(g),l.removeItem(y),l.removeItem(E)},N=()=>V();window.addEventListener("persona:clear-chat",N),Et.push(()=>{window.removeEventListener("persona:clear-chat",N)})}}}return c&&b&&setTimeout(()=>{w.open()},0),w};var fp=(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},ic=(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"},_s=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=""},lc=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.minWidth="",_s(e)},Os=e=>{e.style.transition=""},$s=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=""},Fs=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Go=(e,r)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",r.style.alignItems=""},hp=(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))},yp=(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)},cc=(e,r,t,n,s,o,a)=>{var v,A,b,x,M,F;let i=Cn(o),p=i.reveal==="push";hp(e,r,t,n,p),yp(e,r,t,n,i.side,p),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=(A=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?A:!0,d=(x=(b=o==null?void 0:o.launcher)==null?void 0:b.mobileBreakpoint)!=null?x:640,f=c!=null?c.innerWidth<=d:!1;if(u&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),$s(r),Os(n),lc(n),Fs(t),Go(s,n),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",t.style.flex="1 1 auto",t.style.width="100%",t.style.minWidth="0",n.style.display="flex",n.style.flexDirection="column",n.style.position="fixed",n.style.inset="0",n.style.width="100%",n.style.height="100%",n.style.maxWidth="100%",n.style.minWidth="0",n.style.minHeight="0",n.style.overflow="hidden",n.style.zIndex=String((F=(M=o==null?void 0:o.launcher)==null?void 0:M.zIndex)!=null?F:9999),n.style.transform="none",n.style.transition="none",n.style.pointerEvents="auto",n.style.flex="none",p&&(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"),lc(n),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",$s(r),Os(n),Fs(t),Go(s,n);let S=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",O=a?"translateX(0)":I;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=S,n.style.transform=O,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",Os(n),_s(n),Go(s,n);let S=fp(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),O=i.animate?"transform 180ms ease":"none",k=i.side==="right"?a?`translateX(-${S}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${S}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=`${I+S}px`,r.style.transition=O,r.style.transform=k,t.style.flex="0 0 auto",t.style.flexGrow="0",t.style.flexShrink="0",t.style.width=`${I}px`,t.style.maxWidth=`${I}px`,t.style.minWidth=`${I}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="",$s(r),_s(n),Fs(t),Go(s,n);let S=i.reveal==="emerge";S?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",O=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",k=!a;n.style.display="flex",n.style.flexDirection="column",n.style.flex=`0 0 ${I}`,n.style.width=I,n.style.maxWidth=I,n.style.minWidth=I,n.style.minHeight="0",n.style.position="relative",n.style.overflow=S||k?"hidden":"visible",n.style.transition=O,S&&(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")}},bp=(e,r)=>{let t=e.ownerDocument.createElement("div");return ic(t,r),e.appendChild(t),{mode:"direct",host:t,shell:null,syncWidgetState:()=>{},updateConfig(n){ic(t,n)},destroy(){t.remove()}}},xp=(e,r)=>{var M,F,S,I;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"),p=t.createElement("div"),c=t.createElement("aside"),u=t.createElement("div"),d=(F=(M=r==null?void 0:r.launcher)==null?void 0:M.enabled)==null||F?(I=(S=r==null?void 0:r.launcher)==null?void 0:S.autoExpand)!=null?I:!1:!0;i.dataset.personaDockRole="push-track",p.dataset.personaDockRole="content",c.dataset.personaDockRole="panel",u.dataset.personaDockRole="host",c.appendChild(u),n.insertBefore(a,e),p.appendChild(e);let f=null,m=()=>{f==null||f.disconnect(),f=null},v=()=>{m(),Cn(r).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{cc(a,i,p,c,u,r,d)}),f.observe(a))},A=()=>{cc(a,i,p,c,u,r,d),v()},b=a.ownerDocument.defaultView,x=()=>{A()};return b==null||b.addEventListener("resize",x),Cn(r).reveal==="push"?(i.appendChild(p),i.appendChild(c),a.appendChild(i)):(a.appendChild(p),a.appendChild(c)),A(),{mode:"docked",host:u,shell:a,syncWidgetState(O){let k=O.launcherEnabled?O.open:!0;d!==k&&(d=k,A())},updateConfig(O){var k,U;r=O,((U=(k=r==null?void 0:r.launcher)==null?void 0:k.enabled)!=null?U:!0)===!1&&(d=!0),A()},destroy(){b==null||b.removeEventListener("resize",x),m(),n.isConnected&&(o&&o.parentNode===n?n.insertBefore(e,o):n.appendChild(e)),a.remove()}}},Yo=(e,r)=>_t(r)?xp(e,r):bp(e,r);var js={},vp=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},Cp=()=>{try{if(typeof js!="undefined"&&js.url)return new URL("../widget.css",js.url).href}catch{}return null},dc=(e,r)=>{let t=Cp(),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)}},pc=e=>{var b;let r=vp(e.target),t=e.useShadowDom===!0,n=r.ownerDocument,s=e.config,o=Yo(r,s),a,i=[],p=(x,M)=>{var O,k;let S=!((k=(O=M==null?void 0:M.launcher)==null?void 0:O.enabled)!=null?k:!0)||_t(M),I=n.createElement("div");if(I.setAttribute("data-persona-root","true"),S&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),t){let U=x.attachShadow({mode:"open"});U.appendChild(I),dc(U,n)}else x.appendChild(I),dc(x,n);return r.id&&I.setAttribute("data-persona-instance",r.id),I},c=()=>{o.syncWidgetState(a.getState())},u=()=>{i.forEach(x=>x()),i=[a.on("widget:opened",c),a.on("widget:closed",c)],c()},d=()=>{let x=p(o.host,s);a=Ns(x,s,{debugTools:e.debugTools}),u()},f=()=>{i.forEach(x=>x()),i=[],a.destroy()};d(),(b=e.onReady)==null||b.call(e);let m=x=>{f(),o.destroy(),o=Yo(r,x),s=x,d()},v={update(x){var I,O,k,U,ue,ie;let M={...s,...x,launcher:{...(I=s==null?void 0:s.launcher)!=null?I:{},...(O=x==null?void 0:x.launcher)!=null?O:{},dock:{...(U=(k=s==null?void 0:s.launcher)==null?void 0:k.dock)!=null?U:{},...(ie=(ue=x==null?void 0:x.launcher)==null?void 0:ue.dock)!=null?ie:{}}}},F=_t(s),S=_t(M);if(F!==S){m(M);return}s=M,o.updateConfig(s),a.update(x),c()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},A=new Proxy(v,{get(x,M,F){if(M==="host")return o.host;if(M in x)return Reflect.get(x,M,F);let S=a[M];return typeof S=="function"?S.bind(a):S}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=A),A};var hc=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),wp=new Set(["button","a","input","select","textarea","details","summary"]),Sp=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),zs=/\b(product|card|item|listing|result)\b/i,Vs=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Ap=3e3,Ep=100;function yc(e){let r=typeof e.className=="string"?e.className:"";if(zs.test(r)||e.id&&zs.test(e.id))return!0;for(let t=0;t<e.attributes.length;t++){let n=e.attributes[t];if(n.name.startsWith("data-")&&zs.test(n.value))return!0}return!1}function bc(e){var r;return Vs.test(((r=e.textContent)!=null?r:"").trim())}function xc(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 Tp(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function uc(e){let r=e.match(Vs);return r?r[0]:null}function gc(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 Mp(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 kp="commerce-card",Lp="result-card";function mc(e){return!yc(e)||!bc(e)||!xc(e)&&!Tp(e)?0:5200}function fc(e){var n;return!yc(e)||bc(e)||!xc(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 vc=[{id:kp,scoreElement(e){return mc(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||Vs.test(n)&&n.length<32)}return!0},formatSummary(e,r){var p,c,u;if(mc(e)===0)return null;let{title:t,href:n}=gc(e),s=(u=(c=uc(((p=e.textContent)!=null?p:"").trim()))!=null?c:uc(r.text))!=null?u:"",o=Mp(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(`
98
98
  `)}},{id:Lp,scoreElement(e){return fc(e)},formatSummary(e,r){if(fc(e)===0)return null;let{title:t,href:n}=gc(e);return[n&&t?`[${t}](${n})`:t||r.text.trim().slice(0,120),`selector: ${r.selector}`].filter(Boolean).join(`
99
99
  `)}}];function Ip(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function Pp(e){var u,d,f,m,v,A,b,x,M,F,S,I,O;let r=(u=e.options)!=null?u:{},t=(f=(d=r.maxElements)!=null?d:e.maxElements)!=null?f:80,n=(v=(m=r.excludeSelector)!=null?m:e.excludeSelector)!=null?v:".persona-host",s=(b=(A=r.maxTextLength)!=null?A:e.maxTextLength)!=null?b:200,o=(M=(x=r.visibleOnly)!=null?x:e.visibleOnly)!=null?M:!0,a=(F=r.root)!=null?F:e.root,i=(S=r.mode)!=null?S:"structured",p=(I=r.maxCandidates)!=null?I:Math.max(500,t*10),c=(O=e.rules)!=null?O:vc;return i==="simple"&&e.rules&&e.rules.length>0?(Ip(),c=[]):i==="simple"&&(c=[]),{mode:i,maxElements:t,maxCandidates:p,excludeSelector:n,maxTextLength:s,visibleOnly:o,root:a,rules:c}}function qs(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var Wp=["data-testid","data-product","data-action","data-id","data-name","data-type"];function Rp(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"||wp.has(r)||t&&Sp.has(t)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Cc(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 Hp(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 p=e.getAttribute("role");p&&(r.role=p);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 wc(e){let r=e.tagName.toLowerCase();if(e.id){let s=`#${qs(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of Wp){let o=e.getAttribute(s);if(o){let a=`${r}[${s}="${qs(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=>qs(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 p=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(p).length===1)return p}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 Bp(e){return e==="static"?Ep:Ap}function Sc(e,r){var s;let t=e.tagName.toLowerCase(),n=((s=e.textContent)!=null?s:"").trim().substring(0,r);return{selector:wc(e),tagName:t,text:n,role:e.getAttribute("role"),interactivity:Rp(e),attributes:Hp(e)}}function Dp(e,r,t,n){let s=Bp(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 Np(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 Op(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(hc.has(u)){i=a.nextNode();continue}if(e.excludeSelector)try{if(c.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Cc(c)){i=a.nextNode();continue}let d=Sc(c,e.maxTextLength),f=d.text.length>0,m=Object.keys(d.attributes).length>0&&!Object.keys(d.attributes).every(b=>b==="role");if(!f&&!m){i=a.nextNode();continue}if(n.has(d.selector)){i=a.nextNode();continue}n.add(d.selector);let{score:v,formattingRule:A}=Dp(c,d,e.rules,t);s.push({el:c,domIndex:o,enriched:d,score:v,formattingRule:A}),o+=1}i=a.nextNode()}s.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex});let p=[];for(let c of s){if(p.length>=e.maxElements)break;Np(p,c)||p.push(c)}return p.sort((c,u)=>{let d=c.enriched.interactivity==="static"?1:0,f=u.enriched.interactivity==="static"?1:0;return d!==f?d-f:d===1&&u.score!==c.score?u.score-c.score:c.domIndex-u.domIndex}),p.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 d={...c.enriched};return u&&(d.formattedSummary=u),d})}function $p(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 p=o,c=p.tagName.toLowerCase();if(hc.has(c)){o=s.nextNode();continue}if(e.excludeSelector)try{if(p.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!Cc(p)){o=s.nextNode();continue}let u=Sc(p,e.maxTextLength),d=u.text.length>0,f=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(m=>m==="role");if(!d&&!f){o=s.nextNode();continue}n.has(u.selector)||(n.add(u.selector),t.push(u))}o=s.nextNode()}let a=[],i=[];for(let p of t)p.interactivity!=="static"?a.push(p):i.push(p);return[...a,...i].slice(0,e.maxElements)}function Fp(e={}){var n;let r=Pp(e),t=(n=r.root)!=null?n:document.body;return t?r.mode==="simple"?$p(r,t):Op(r,t):[]}var Xo=100;function _p(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:
100
100
  ${a.map(i=>`- ${i.split(`
@@ -110,7 +110,7 @@ ${a.join(`
110
110
  ${a.join(`
111
111
  `)}`)}return n.join(`
112
112
 
113
- `)}var Ac={name:"@runtypelabs/persona",version:"3.5.2",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./widget.css":{import:"./widget.css",default:"./dist/widget.css"}},files:["dist","widget.css","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Pr=Ac.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 zp(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 Ec=`({ text, message }: any) => {
113
+ `)}var Ac={name:"@runtypelabs/persona",version:"3.6.0",description:"Themeable, pluggable streaming agent widget for websites, in plain JS with support for voice input and reasoning / tool output.",type:"module",main:"dist/index.cjs",module:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",import:"./dist/index.js",require:"./dist/index.cjs"},"./theme-reference":{types:"./dist/theme-reference.d.ts",import:"./dist/theme-reference.js",require:"./dist/theme-reference.cjs"},"./theme-editor":{types:"./dist/theme-editor.d.ts",import:"./dist/theme-editor.js",require:"./dist/theme-editor.cjs"},"./widget.css":"./dist/widget.css"},files:["dist","src"],scripts:{build:"rimraf dist && pnpm run build:styles && pnpm run build:client && pnpm run build:installer && pnpm run build:theme-ref && pnpm run build:theme-editor","build:theme-editor":"tsup src/theme-editor.ts --format esm,cjs --dts --out-dir dist --no-splitting","build:theme-ref":"tsup src/theme-reference.ts --format esm,cjs --minify --dts","build:styles":`node -e "const fs=require('fs');fs.mkdirSync('dist',{recursive:true});fs.copyFileSync('src/styles/widget.css','dist/widget.css');"`,"build:client":'tsup src/index.ts --format esm,cjs,iife --global-name AgentWidget --minify --sourcemap --splitting false --dts --loader ".css=text"',"build:installer":"tsup src/install.ts --format iife --global-name SiteAgentInstaller --out-dir dist --minify --sourcemap --no-splitting",lint:"eslint . --ext .ts",typecheck:"tsc --noEmit",test:"vitest","test:ui":"vitest --ui","test:run":"vitest run"},dependencies:{dompurify:"^3.3.3",idiomorph:"^0.7.4",lucide:"^0.552.0",marked:"^12.0.2","partial-json":"^0.1.7",zod:"^3.22.4"},devDependencies:{"@types/node":"^20.12.7","@typescript-eslint/eslint-plugin":"^7.0.0","@typescript-eslint/parser":"^7.0.0","@vitest/ui":"^4.0.9",eslint:"^8.57.0","eslint-config-prettier":"^9.1.0","fake-indexeddb":"^6.2.5",rimraf:"^5.0.5",tsup:"^8.0.1",typescript:"^5.4.5",vitest:"^4.0.9"},engines:{node:">=20.0.0"},author:"Runtype",license:"MIT",keywords:["ai","chat","widget","streaming","typescript","persona","agent"],repository:{type:"git",url:"git+https://github.com/runtypelabs/persona.git",directory:"packages/widget"},bugs:{url:"https://github.com/runtypelabs/persona/issues"},homepage:"https://github.com/runtypelabs/persona/tree/main/packages/widget#readme",publishConfig:{access:"public"}};var Rr=Ac.version;function Nn(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(r=>r.toString()).join(", ")}]`:e.toString()}function zp(e){if(e)return{getHeaders:Nn(e.getHeaders),onFeedback:Nn(e.onFeedback),onCopy:Nn(e.onCopy),requestMiddleware:Nn(e.requestMiddleware),actionHandlers:Nn(e.actionHandlers),actionParsers:Nn(e.actionParsers),postprocessMessage:Nn(e.postprocessMessage),contextProviders:Nn(e.contextProviders),streamParser:Nn(e.streamParser)}}var Ec=`({ text, message }: any) => {
114
114
  const jsonSource = (message as any).rawContent || text || message.content;
115
115
  if (!jsonSource || typeof jsonSource !== 'string') return null;
116
116
  let cleanJson = jsonSource
@@ -176,19 +176,19 @@ ${a.join(`
176
176
  if (parsed.action === 'message') return parsed.text || '';
177
177
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
178
178
  return parsed.text || null;
179
- }`,Up=`function(parsed) {
179
+ }`,Vp=`function(parsed) {
180
180
  if (!parsed || typeof parsed !== 'object') return null;
181
181
  if (parsed.action === 'nav_then_click') return 'Navigating...';
182
182
  if (parsed.action === 'message') return parsed.text || '';
183
183
  if (parsed.action === 'message_and_click') return parsed.text || 'Processing...';
184
184
  return parsed.text || null;
185
- }`;function Vp(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 Zo(e){var r,t;return(t=(r=e.parserType)!=null?r:Vp(e.streamParser))!=null?t:"plain"}function Qo(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 es(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 ts(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 ns(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,p])=>{typeof p=="string"?t.push(`${r} ${i}: "${p}",`):typeof p=="boolean"&&t.push(`${r} ${i}: ${p},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"?t.push(`${r} ${p}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${p}: ${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 Vs(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 Lc(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}: {`),Lc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Vn(e,r,t,n){t&&(e.push(`${n}${r}: {`),Lc(e,t,`${n} `),e.push(`${n}},`))}function Jp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:zp(t.hooks)}:void 0;return r==="esm"?Kp(n,s):r==="script-installer"?Xp(n):r==="script-advanced"?Qp(n,s):r==="react-component"?Gp(n,s):r==="react-advanced"?Yp(n,s):Zp(n,s)}function Kp(e,r){let t=r==null?void 0:r.hooks,n=Zo(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&&Vn(o,"theme",e.theme," "),e.launcher&&Vn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Vs(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(`
186
- `)}function Gp(e,r){let t=r==null?void 0:r.hooks,n=Zo(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&&Vn(o,"theme",e.theme," "),e.launcher&&Vn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Vs(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(`
187
- `)}function Yp(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&&Vn(n,"theme",e.theme," "),e.launcher&&Vn(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(...Qo(e," ")),n.push(...es(e," ",t)),n.push(...ts(e," ")),n.push(...ns(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(${qp}),`)),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(` ${Ec}`),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(` ${Ec}`),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(` ${Mc}`),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(` ${Mc}`),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(`
188
- `)}function Ic(e){var s;let r=Zo(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,p])=>{i!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,p])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof p=="object"&&p!==null)a.avatar=p;else if(i==="timestamp"&&typeof p=="object"&&p!==null){let c={};Object.entries(p).forEach(([u,d])=>{u!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[u]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Xp(e){let r=Ic(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Pr}/dist/install.global.js" data-config='${t}'></script>`}function Zp(e,r){let t=r==null?void 0:r.hooks,n=Zo(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Pr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Pr}/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&&Vn(o,"theme",e.theme," "),e.launcher&&Vn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Vs(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(`
185
+ }`;function Up(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 Zo(e){var r,t;return(t=(r=e.parserType)!=null?r:Up(e.streamParser))!=null?t:"plain"}function Qo(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 es(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 ts(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 ns(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,p])=>{typeof p=="string"?t.push(`${r} ${i}: "${p}",`):typeof p=="boolean"&&t.push(`${r} ${i}: ${p},`)}),t.push(`${r} },`)):o==="timestamp"&&typeof a=="object"&&a!==null?Object.entries(a).some(([p])=>p!=="format")&&(t.push(`${r} timestamp: {`),Object.entries(a).forEach(([p,c])=>{p!=="format"&&(typeof c=="string"?t.push(`${r} ${p}: "${c}",`):typeof c=="boolean"&&t.push(`${r} ${p}: ${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 Us(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 Lc(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}: {`),Lc(e,s,`${t} `),e.push(`${t}},`);return}e.push(`${t}${n}: ${JSON.stringify(s)},`)}})}function Gn(e,r,t,n){t&&(e.push(`${n}${r}: {`),Lc(e,t,`${n} `),e.push(`${n}},`))}function Jp(e,r="esm",t){let n={...e};delete n.postprocessMessage,delete n.initialMessages;let s=t?{...t,hooks:zp(t.hooks)}:void 0;return r==="esm"?Kp(n,s):r==="script-installer"?Xp(n):r==="script-advanced"?Qp(n,s):r==="react-component"?Gp(n,s):r==="react-advanced"?Yp(n,s):Zp(n,s)}function Kp(e,r){let t=r==null?void 0:r.hooks,n=Zo(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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Us(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(`
186
+ `)}function Gp(e,r){let t=r==null?void 0:r.hooks,n=Zo(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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Us(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(`
187
+ `)}function Yp(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&&Gn(n,"theme",e.theme," "),e.launcher&&Gn(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(...Qo(e," ")),n.push(...es(e," ",t)),n.push(...ts(e," ")),n.push(...ns(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(${qp}),`)),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(` ${Ec}`),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(` ${Ec}`),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(` ${Mc}`),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(` ${Mc}`),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(`
188
+ `)}function Ic(e){var s;let r=Zo(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,p])=>{i!=="render"&&(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.header=a)}if(e.layout.messages){let a={};Object.entries(e.layout.messages).forEach(([i,p])=>{if(i!=="renderUserMessage"&&i!=="renderAssistantMessage")if(i==="avatar"&&typeof p=="object"&&p!==null)a.avatar=p;else if(i==="timestamp"&&typeof p=="object"&&p!==null){let c={};Object.entries(p).forEach(([u,d])=>{u!=="format"&&(typeof d=="string"||typeof d=="boolean")&&(c[u]=d)}),Object.keys(c).length>0&&(a.timestamp=c)}else(typeof p=="string"||typeof p=="boolean")&&(a[i]=p)}),Object.keys(a).length>0&&(o.messages=a)}Object.keys(o).length>0&&(n.layout=o)}return n}function Xp(e){let r=Ic(e),t=JSON.stringify(r,null,0).replace(/'/g,"&#39;");return`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Rr}/dist/install.global.js" data-config='${t}'></script>`}function Zp(e,r){let t=r==null?void 0:r.hooks,n=Zo(e),s=n!=="plain",o=["<!-- Load CSS -->",`<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Rr}/dist/widget.css" />`,"","<!-- Load JavaScript -->",`<script src="https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Rr}/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&&Gn(o,"theme",e.theme," "),e.launcher&&Gn(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(...Qo(e," ")),o.push(...es(e," ",t)),o.push(...ts(e," ")),o.push(...ns(e," ")),o.push(...Us(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(`
189
189
  `)}function Qp(e,r){let t=r==null?void 0:r.hooks,n=Ic(e),o=["<script>","(function() {"," 'use strict';",""," // Configuration",` var CONFIG = ${JSON.stringify(n,null,2).split(`
190
190
  `).map((a,i)=>i===0?a:" "+a).join(`
191
- `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Pr}/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(${Up});`),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(` ${Tc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Tc}`),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(` ${kc}`),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(` ${kc}`),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(`
191
+ `)};`,""," // Constants",` var CDN_BASE = 'https://cdn.jsdelivr.net/npm/@runtypelabs/persona@${Rr}/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(${Vp});`),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(` ${Tc}`),o.push(" ]);")):(o.push(" // Action parsers to detect JSON actions in responses"),o.push(" widgetConfig.actionParsers = ["),o.push(" agentWidget.defaultJsonActionParser,"),o.push(` ${Tc}`),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(` ${kc}`),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(` ${kc}`),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(`
192
192
  `)}var Pc={desktop:{w:1280,h:800},mobile:{w:390,h:844}},Wc=.1,Rc=.15,Hc=1.5,Js=24,Bc=40,eu=`
193
193
  /* \u2500\u2500 Root \u2500\u2500 */
194
194
  .persona-dc-root {
@@ -299,8 +299,8 @@ ${a.join(`
299
299
  background: #f3f4f6;
300
300
  }
301
301
  .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item[aria-current="true"] {
302
- background: #eff6ff;
303
- color: #2563eb;
302
+ background: #f5f5f5;
303
+ color: #0f0f0f;
304
304
  }
305
305
  .persona-dc-root .persona-dc-dropdown-desc {
306
306
  font-weight: 400;
@@ -310,7 +310,7 @@ ${a.join(`
310
310
  text-align: left;
311
311
  }
312
312
  .persona-dc-root .persona-dc-dropdown button.persona-dc-dropdown-item[aria-current="true"] .persona-dc-dropdown-desc {
313
- color: #60a5fa;
313
+ color: #737373;
314
314
  }
315
315
  .persona-dc-counter {
316
316
  font-size: 12px;
@@ -394,7 +394,7 @@ ${a.join(`
394
394
  background: #f3f4f6;
395
395
  }
396
396
  .persona-dc-root .persona-icon-btn:focus-visible {
397
- outline: 2px solid #3b82f6;
397
+ outline: 2px solid #171717;
398
398
  outline-offset: 2px;
399
399
  }
400
400
  .persona-dc-root .persona-icon-btn[aria-pressed="true"] {
@@ -430,5 +430,5 @@ ${a.join(`
430
430
  min-height: 300px;
431
431
  }
432
432
  }
433
- `;function tu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=eu,document.head.appendChild(e)}function nu(e,r){let t=e.clientWidth-Js*2-Bc,n=e.clientHeight-Js*2-Bc;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function ru(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function ou(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");tu();let u=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,m=null,v=1,A=!1,b=h("div","persona-dc-root"),x=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),F=h("div","persona-dc-toolbar-trail"),S=vt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>rt(-1)}),I=h("div");I.style.position="relative";let O=h("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let k=h("span","persona-dc-title-text"),V=h("span","persona-dc-title-chevron"),ge=fe("chevron-down",12,"currentColor",2);ge&&V.appendChild(ge),O.append(k,V);let ie=h("div","persona-dc-dropdown");ie.setAttribute("role","listbox"),ie.style.display="none";let _=!1;function ne(){ie.innerHTML="";for(let z=0;z<t.length;z++){let oe=t[z],Le=h("button","persona-dc-dropdown-item");Le.type="button",Le.setAttribute("role","option"),Le.setAttribute("aria-current",z===u?"true":"false");let Z=h("span");if(Z.textContent=oe.title,Le.appendChild(Z),oe.description){let J=h("span","persona-dc-dropdown-desc");J.textContent=oe.description,Le.appendChild(J)}Le.addEventListener("click",()=>{le(),Me(z)}),ie.appendChild(Le)}}function Te(){_=!_,ie.style.display=_?"":"none",O.setAttribute("aria-expanded",_?"true":"false"),_&&ne()}function le(){_&&(_=!1,ie.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",z=>{z.stopPropagation(),Te()});let ke=()=>le();document.addEventListener("click",ke),I.append(O,ie);let de=vt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>rt(1)}),Y=h("span","persona-dc-counter");M.append(S,I,de,Y);let ce=null;i&&(ce=zo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:z=>{d=z,Ke.dataset.device=d,m=null,D()}}),F.appendChild(ce.element));let q=null;if(a){let z=h("div","persona-dc-zoom-controls"),oe=vt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.max(Rc,J-Wc),D()}});q=h("span","persona-dc-zoom-level"),q.title="Reset to 100%",q.style.cursor="pointer",q.addEventListener("click",()=>{m=1,D()});let Le=vt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let J=m!=null?m:v;m=Math.min(Hc,J+Wc),D()}}),Z=vt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,D()}});z.append(oe,q,Le,Z),F.appendChild(z)}if(p){let z=h("div","persona-dc-separator");F.appendChild(z);let oe=zo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Le=>{f=Le,Ke.dataset.colorScheme=f,mt()}});F.appendChild(oe.element)}let G=h("div","persona-dc-separator");F.appendChild(G);let ve=vt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});F.appendChild(ve),x.append(M,F);let xe=h("div","persona-dc-stage"),Ke=h("div","persona-dc-iframe-wrapper");Ke.dataset.device=d,Ke.dataset.colorScheme=f;let Xe=h("iframe","persona-dc-iframe");Xe.setAttribute("sandbox","allow-scripts allow-same-origin"),Xe.setAttribute("loading","lazy"),Xe.title=t[u].title,Ke.appendChild(Xe),xe.appendChild(Ke),b.append(x,xe),e.appendChild(b);function mt(){var z;try{let oe=(z=Xe.contentDocument)==null?void 0:z.body;if(!oe)return;f==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}Xe.addEventListener("load",()=>mt());function Be(){let z=t[u];k.textContent=z.title,Y.textContent=`${u+1} / ${t.length}`,Xe.title=z.title}function rt(z){let oe=((u+z)%t.length+t.length)%t.length;Me(oe)}function Me(z){z<0||z>=t.length||(u=z,Xe.src=t[u].url,Be(),c==null||c(u,t[u]))}function D(){var Le;if(A)return;let z=(Le=Pc[d])!=null?Le:Pc.desktop;v=nu(xe,z);let oe=Math.max(Rc,Math.min(Hc,m!=null?m:v));ru(Ke,Xe,z,oe,d),q&&(q.textContent=`${Math.round(oe*100)}%`)}let se=new ResizeObserver(()=>D());se.observe(xe),Be(),Xe.src=t[u].url,requestAnimationFrame(()=>D());function te(){A||(A=!0,se.disconnect(),document.removeEventListener("click",ke),b.remove())}return{element:b,goTo:Me,next:()=>rt(1),prev:()=>rt(-1),getIndex:()=>u,setDevice(z){d=z,Ke.dataset.device=z,ce==null||ce.setSelected(z),m=null,D()},setColorScheme(z){f=z,Ke.dataset.colorScheme=z},setZoom(z){m=z,D()},destroy:te}}function su(){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 au(){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 iu(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:Tn(e.colors.primary,.95),100:Tn(e.colors.primary,.9),200:Tn(e.colors.primary,.8),300:Tn(e.colors.primary,.7),400:Tn(e.colors.primary,.6),500:e.colors.primary,600:Tn(e.colors.primary,.8),700:Tn(e.colors.primary,.7),800:Tn(e.colors.primary,.6),900:Tn(e.colors.primary,.5),950:Tn(e.colors.primary,.45)}}),{...r,palette:t}}}}function lu(){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 cu(){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 Tn(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 du(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var pu={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"}}},Dc={components:{panel:{borderRadius:"0",shadow:"none"}}},Nc={id:"shop",label:"Shopping Assistant",config:{theme:pu,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?"]}},Oc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Dc}},$c={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Dc}},Fc={shop:Nc,minimal:Oc,fullscreen:$c};function uu(e){return Fc[e]}var Vf=pc;export{vr as AgentWidgetClient,to as AgentWidgetSession,Sr as AttachmentManager,Sl as DEFAULT_COMPONENTS,Cl as DEFAULT_PALETTE,wl as DEFAULT_SEMANTIC,Ct as DEFAULT_WIDGET_CONFIG,Fc as PRESETS,$c as PRESET_FULLSCREEN,Oc as PRESET_MINIMAL,Nc as PRESET_SHOP,xd as THEME_ZONES,Pr as VERSION,su as accessibilityPlugin,au as animationsPlugin,ir as applyThemeVariables,Ar as attachHeaderToContainer,iu as brandPlugin,io as buildComposer,Bl as buildDefaultHeader,qn as buildHeader,ao as buildHeaderWithLayout,Dl as buildMinimalHeader,Fp as collectEnrichedPageContext,Un as componentRegistry,Ko as createActionManager,Ns as createAgentExperience,ms as createBestAvailableVoiceProvider,Hd as createBubbleWithLayout,Hs as createCSATFeedback,bs as createComboButton,lp as createComponentMiddleware,Is as createComponentStreamParser,pl as createDefaultSanitizer,ou as createDemoCarousel,Vc as createDirectivePostprocessor,lr as createDropdownMenu,ed as createFlexibleJsonStreamParser,vt as createIconButton,ld as createImagePart,cs as createJsonStreamParser,jo as createLabelButton,Ls as createLocalStorageAdapter,Io as createMarkdownProcessor,xr as createMarkdownProcessorFromConfig,jl as createMessageActions,Bs as createNPSFeedback,is as createPlainTextParser,du as createPlugin,ls as createRegexJsonParser,lo as createStandardBubble,gs as createTextPart,ro as createTheme,ys as createThemeObserver,zo as createToggleGroup,Er as createTypingIndicator,wr as createVoiceProvider,Yo as createWidgetHostLayout,ds as createXmlParser,Vf as default,Lr as defaultActionHandlers,Jo as defaultJsonActionParser,vc as defaultParseRules,$o as detectColorScheme,Jc as directivePostprocessor,Yr as escapeHtml,Rs as extractComponentDirectiveFromMessage,cd as fileToImagePart,_p as formatEnrichedContext,Cr as generateAssistantMessageId,Jp as generateCodeSnippet,rd as generateMessageId,wc as generateStableSelector,Qr as generateUserMessageId,Fo as getActiveTheme,kl as getColorScheme,sd as getDisplayText,Nl as getHeaderLayout,id as getImageParts,uu as getPreset,Ws as hasComponentDirective,ad as hasImages,xs as headerLayouts,cu as highContrastPlugin,pc as initAgentWidget,ip as isComponentDirectiveType,zt as isDockedMountMode,No as isVoiceSupported,ll as markdownPostprocessor,Ms as mergeWithDefaults,od as normalizeContent,Vo as pluginRegistry,lu as reducedMotionPlugin,Ps as renderComponentDirective,_l as renderLoadingIndicatorWithFallback,hn as resolveDockConfig,Xr as resolveSanitizer,fs as resolveTokens,hs as themeToCssVariables,dd as validateImageFile,Al as validateTheme};
433
+ `;function tu(){if(document.querySelector("style[data-persona-dc-styles]"))return;let e=document.createElement("style");e.setAttribute("data-persona-dc-styles",""),e.textContent=eu,document.head.appendChild(e)}function nu(e,r){let t=e.clientWidth-Js*2-Bc,n=e.clientHeight-Js*2-Bc;return t<=0||n<=0?1:Math.min(t/r.w,n/r.h,1)}function ru(e,r,t,n,s){e.style.width=`${t.w*n}px`,e.style.height=`${t.h*n}px`,e.style.borderRadius=s==="mobile"?`${32*n}px`:"10px",r.style.width=`${t.w}px`,r.style.height=`${t.h}px`,r.style.transformOrigin="top left",r.style.transform=`scale(${n})`}function ou(e,r){let{items:t,initialIndex:n=0,initialDevice:s="desktop",initialColorScheme:o="light",showZoomControls:a=!0,showDeviceToggle:i=!0,showColorSchemeToggle:p=!0,onChange:c}=r;if(t.length===0)throw new Error("createDemoCarousel: items array must not be empty");tu();let u=Math.max(0,Math.min(n,t.length-1)),d=s,f=o,m=null,v=1,A=!1,b=h("div","persona-dc-root"),x=h("div","persona-dc-toolbar"),M=h("div","persona-dc-toolbar-lead"),F=h("div","persona-dc-toolbar-trail"),S=vt({icon:"chevron-left",label:"Previous demo",size:14,onClick:()=>nt(-1)}),I=h("div");I.style.position="relative";let O=h("button","persona-dc-title-btn");O.type="button",O.setAttribute("aria-expanded","false"),O.setAttribute("aria-haspopup","listbox");let k=h("span","persona-dc-title-text"),U=h("span","persona-dc-title-chevron"),ue=me("chevron-down",12,"currentColor",2);ue&&U.appendChild(ue),O.append(k,U);let ie=h("div","persona-dc-dropdown");ie.setAttribute("role","listbox"),ie.style.display="none";let _=!1;function ne(){ie.innerHTML="";for(let z=0;z<t.length;z++){let oe=t[z],Ie=h("button","persona-dc-dropdown-item");Ie.type="button",Ie.setAttribute("role","option"),Ie.setAttribute("aria-current",z===u?"true":"false");let Z=h("span");if(Z.textContent=oe.title,Ie.appendChild(Z),oe.description){let G=h("span","persona-dc-dropdown-desc");G.textContent=oe.description,Ie.appendChild(G)}Ie.addEventListener("click",()=>{le(),ke(z)}),ie.appendChild(Ie)}}function Me(){_=!_,ie.style.display=_?"":"none",O.setAttribute("aria-expanded",_?"true":"false"),_&&ne()}function le(){_&&(_=!1,ie.style.display="none",O.setAttribute("aria-expanded","false"))}O.addEventListener("click",z=>{z.stopPropagation(),Me()});let Le=()=>le();document.addEventListener("click",Le),I.append(O,ie);let de=vt({icon:"chevron-right",label:"Next demo",size:14,onClick:()=>nt(1)}),Y=h("span","persona-dc-counter");M.append(S,I,de,Y);let ce=null;i&&(ce=zo({items:[{id:"desktop",icon:"monitor",label:"Desktop"},{id:"mobile",icon:"smartphone",label:"Mobile"}],selectedId:d,onSelect:z=>{d=z,Ge.dataset.device=d,m=null,D()}}),F.appendChild(ce.element));let q=null;if(a){let z=h("div","persona-dc-zoom-controls"),oe=vt({icon:"minus",label:"Zoom out",size:14,onClick:()=>{let G=m!=null?m:v;m=Math.max(Rc,G-Wc),D()}});q=h("span","persona-dc-zoom-level"),q.title="Reset to 100%",q.style.cursor="pointer",q.addEventListener("click",()=>{m=1,D()});let Ie=vt({icon:"plus",label:"Zoom in",size:14,onClick:()=>{let G=m!=null?m:v;m=Math.min(Hc,G+Wc),D()}}),Z=vt({icon:"maximize",label:"Fit to view",size:14,onClick:()=>{m=null,D()}});z.append(oe,q,Ie,Z),F.appendChild(z)}if(p){let z=h("div","persona-dc-separator");F.appendChild(z);let oe=zo({items:[{id:"light",icon:"sun",label:"Light"},{id:"dark",icon:"moon",label:"Dark"}],selectedId:f,onSelect:Ie=>{f=Ie,Ge.dataset.colorScheme=f,ft()}});F.appendChild(oe.element)}let K=h("div","persona-dc-separator");F.appendChild(K);let Ce=vt({icon:"external-link",label:"Open in new tab",size:14,onClick:()=>{window.open(t[u].url,"_blank")}});F.appendChild(Ce),x.append(M,F);let ve=h("div","persona-dc-stage"),Ge=h("div","persona-dc-iframe-wrapper");Ge.dataset.device=d,Ge.dataset.colorScheme=f;let Ze=h("iframe","persona-dc-iframe");Ze.setAttribute("sandbox","allow-scripts allow-same-origin"),Ze.setAttribute("loading","lazy"),Ze.title=t[u].title,Ge.appendChild(Ze),ve.appendChild(Ge),b.append(x,ve),e.appendChild(b);function ft(){var z;try{let oe=(z=Ze.contentDocument)==null?void 0:z.body;if(!oe)return;f==="dark"?oe.classList.add("theme-dark"):oe.classList.remove("theme-dark")}catch{}}Ze.addEventListener("load",()=>ft());function We(){let z=t[u];k.textContent=z.title,Y.textContent=`${u+1} / ${t.length}`,Ze.title=z.title}function nt(z){let oe=((u+z)%t.length+t.length)%t.length;ke(oe)}function ke(z){z<0||z>=t.length||(u=z,Ze.src=t[u].url,We(),c==null||c(u,t[u]))}function D(){var Ie;if(A)return;let z=(Ie=Pc[d])!=null?Ie:Pc.desktop;v=nu(ve,z);let oe=Math.max(Rc,Math.min(Hc,m!=null?m:v));ru(Ge,Ze,z,oe,d),q&&(q.textContent=`${Math.round(oe*100)}%`)}let se=new ResizeObserver(()=>D());se.observe(ve),We(),Ze.src=t[u].url,requestAnimationFrame(()=>D());function te(){A||(A=!0,se.disconnect(),document.removeEventListener("click",Le),b.remove())}return{element:b,goTo:ke,next:()=>nt(1),prev:()=>nt(-1),getIndex:()=>u,setDevice(z){d=z,Ge.dataset.device=z,ce==null||ce.setSelected(z),m=null,D()},setColorScheme(z){f=z,Ge.dataset.colorScheme=z},setZoom(z){m=z,D()},destroy:te}}function su(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function au(){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 iu(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:In(e.colors.primary,.95),100:In(e.colors.primary,.9),200:In(e.colors.primary,.8),300:In(e.colors.primary,.7),400:In(e.colors.primary,.6),500:e.colors.primary,600:In(e.colors.primary,.8),700:In(e.colors.primary,.7),800:In(e.colors.primary,.6),900:In(e.colors.primary,.5),950:In(e.colors.primary,.45)}}),{...r,palette:t}}}}function lu(){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 cu(){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 In(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 du(e){return{name:e.name,version:e.version,transform:e.transform||(r=>r),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var pu={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"}}},Dc={components:{panel:{borderRadius:"0",shadow:"none"}}},Nc={id:"shop",label:"Shopping Assistant",config:{theme:pu,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?"]}},Oc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Dc}},$c={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Dc}},Fc={shop:Nc,minimal:Oc,fullscreen:$c};function uu(e){return Fc[e]}var Uf=pc;export{wr as AgentWidgetClient,to as AgentWidgetSession,Er as AttachmentManager,Sl as DEFAULT_COMPONENTS,Cl as DEFAULT_PALETTE,wl as DEFAULT_SEMANTIC,Ct as DEFAULT_WIDGET_CONFIG,Fc as PRESETS,$c as PRESET_FULLSCREEN,Oc as PRESET_MINIMAL,Nc as PRESET_SHOP,xd as THEME_ZONES,Rr as VERSION,su as accessibilityPlugin,au as animationsPlugin,dr as applyThemeVariables,Tr as attachHeaderToContainer,iu as brandPlugin,io as buildComposer,Bl as buildDefaultHeader,Jn as buildHeader,ao as buildHeaderWithLayout,Dl as buildMinimalHeader,Fp as collectEnrichedPageContext,Kn as componentRegistry,Ko as createActionManager,Ns as createAgentExperience,ms as createBestAvailableVoiceProvider,Hd as createBubbleWithLayout,Hs as createCSATFeedback,bs as createComboButton,lp as createComponentMiddleware,Is as createComponentStreamParser,pl as createDefaultSanitizer,ou as createDemoCarousel,Uc as createDirectivePostprocessor,pr as createDropdownMenu,ed as createFlexibleJsonStreamParser,vt as createIconButton,ld as createImagePart,cs as createJsonStreamParser,jo as createLabelButton,Ls as createLocalStorageAdapter,Io as createMarkdownProcessor,Cr as createMarkdownProcessorFromConfig,jl as createMessageActions,Bs as createNPSFeedback,is as createPlainTextParser,du as createPlugin,ls as createRegexJsonParser,lo as createStandardBubble,gs as createTextPart,ro as createTheme,ys as createThemeObserver,zo as createToggleGroup,Mr as createTypingIndicator,Ar as createVoiceProvider,Yo as createWidgetHostLayout,ds as createXmlParser,Uf as default,Pr as defaultActionHandlers,Jo as defaultJsonActionParser,vc as defaultParseRules,$o as detectColorScheme,Jc as directivePostprocessor,Yr as escapeHtml,Rs as extractComponentDirectiveFromMessage,cd as fileToImagePart,_p as formatEnrichedContext,Sr as generateAssistantMessageId,Jp as generateCodeSnippet,rd as generateMessageId,wc as generateStableSelector,Qr as generateUserMessageId,Fo as getActiveTheme,kl as getColorScheme,sd as getDisplayText,Nl as getHeaderLayout,id as getImageParts,uu as getPreset,Ws as hasComponentDirective,ad as hasImages,xs as headerLayouts,cu as highContrastPlugin,pc as initAgentWidget,ip as isComponentDirectiveType,_t as isDockedMountMode,No as isVoiceSupported,ll as markdownPostprocessor,Ms as mergeWithDefaults,od as normalizeContent,Uo as pluginRegistry,lu as reducedMotionPlugin,Ps as renderComponentDirective,_l as renderLoadingIndicatorWithFallback,Cn as resolveDockConfig,Xr as resolveSanitizer,fs as resolveTokens,hs as themeToCssVariables,dd as validateImageFile,Al as validateTheme};
434
434
  //# sourceMappingURL=index.js.map