@runtypelabs/persona 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -8,7 +8,7 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},Xf=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},Qf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Yf=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Zf="agent_",eh="flow_";function Nu(e){return e.startsWith(Zf)?{kind:"agentId",agentId:e}:e.startsWith(eh)?{kind:"flowId",flowId:e}:null}function Ou(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let l=Nu(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Nu(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as th,ARR as nh,OBJ as rh,STR as oh}from"partial-json";var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Wr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Tt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},qs=(...e)=>e.filter(Boolean).join(" ");var Pa="ask_user_question",zs=8,ms="data-persona-ask-sheet-for",sh="Other",ah="Other\u2026",_u="Type your own answer here",$u="Send",ih="Next",lh="Back",ch="Submit all",dh="Skip",ph=3,$i="data-ask-current-index",ji="data-ask-question-count",ju="data-ask-answers",Ui="data-ask-grouped",Uu="data-ask-layout",uh=e=>e.layout==="pills"?"pills":"rows",mh=e=>e.getAttribute(Uu)==="pills"?"pills":"rows",Fu=!1,qu=e=>e.replace(/["\\]/g,"\\$&"),po=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Pa,Ia=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},uo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=th(o,oh|rh|nh);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!Fu&&(Fu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},gh=e=>{var t;return(t=Vs(e)[0])!=null?t:null},fh=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},zu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Vu=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},hh=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=y("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}s.appendChild(a);let d=Vu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},yh=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},bh=(e,t,n,r)=>{var p,u,g;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(d.length===0&&!n){for(let f=0;f<ph;f++)s.appendChild(yh(r));return s}if(d.forEach((f,v)=>{s.appendChild(hh(f,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let f=r==="rows"?sh:ah;if(r==="rows"){let v=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let x=y("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=t.freeTextPlaceholder)!=null?p:_u,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),x.appendChild(E),v.appendChild(x);let T=Vu(r,a,d.length);T&&v.appendChild(T),s.appendChild(v)}else{let v=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(g=t.freeTextLabel)!=null?g:f,s.appendChild(v)}}return s},Ku=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:_u,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:$u,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xh=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:$u,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},vh=(e,t,n)=>{var l,p,u,g;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:lh,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:dh,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:ch:(g=n.nextLabel)!=null?g:ih,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Fo=e=>{let t=e.getAttribute(ju);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Gu=(e,t)=>{e.setAttribute(ju,JSON.stringify(t))},or=e=>{var n;let t=Number((n=e.getAttribute($i))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},wh=(e,t)=>{e.setAttribute($i,String(Math.max(0,Math.floor(t))))},gs=e=>{var n;let t=Number((n=e.getAttribute(ji))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},mo=e=>e.getAttribute(Ui)==="true",Ch=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Ah=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Ra=(e,t)=>{let{payload:n}=uo(t),r=Vs(n),o=Fo(e),s={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(o,d)&&(s[l]=o[d]))}),s},Ju=e=>{let t=Fo(e),n=or(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Xu=e=>{if(!mo(e))return;let t=Fo(e),n=or(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},qi=(e,t,n)=>{let r=Ia(n),o=mh(e),{payload:s,complete:a}=uo(t),i=mo(e),d=or(e),l=gs(e),p=i?fh(s,d):gh(s),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${d+1}/${l}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let L=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=L,v.classList.toggle("persona-ask-question-skeleton",!L&&!a)}let x=e.querySelector('[data-ask-pill-list="true"]');if(x){let L=bh(p,r,a,o);x.replaceWith(L)}if(o!=="rows"){let L=e.querySelector('[data-ask-free-text-row="true"]');L&&L.replaceWith(Ku(r,o))}let E=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!E?e.appendChild(xh(r)):(!u||i)&&E&&E.remove(),e.setAttribute("data-multi-select",u?"true":"false");let T=e.querySelector('[data-ask-nav-row="true"]');if(i){let L=vh(d,l,r);T?T.replaceWith(L):e.appendChild(L)}else T&&T.remove();Ju(e),Xu(e)},Sh=(e,t,n)=>{let r=Ia(t),o=uh(r),s=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=Ch(e,a),p=d?Ah(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ms,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(ji,String(i)),u.setAttribute($i,String(p)),u.setAttribute(Ui,d?"true":"false"),u.setAttribute(Uu,o),Gu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),zu(u,r);let g=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=y("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let v=y("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",g.appendChild(v),u.appendChild(g);let E=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),u.appendChild(E),o!=="rows"&&u.appendChild(Ku(r,o)),qi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Th=(e,t,n)=>{let{payload:r}=uo(t),o=Math.max(1,Vs(r).length);o>gs(e)&&(e.setAttribute(ji,String(o)),o>1&&!mo(e)&&e.setAttribute(Ui,"true")),qi(e,t,n)},Eh=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Ia(t);zu(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=uo(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Ks=(e,t,n)=>{if(!n||!po(e)||Ia(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ms}]`).forEach(l=>{l.getAttribute(ms)!==o&&l.remove()});let a=n.querySelector(`[${ms}="${qu(o)}"]`);if(a){Th(a,e,t);return}let{payload:i}=uo(e),d=Sh(e,t,i);n.appendChild(d)},_o=(e,t)=>{if(!e)return;let n=t?`[${ms}="${qu(t)}"]`:`[${ms}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},zi=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),go=(e,t)=>{let n=Fo(e),r=or(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Gu(e,n),Ju(e),Xu(e)},Wa=(e,t,n,r)=>{let o=gs(e),s=Math.max(0,Math.min(o-1,r));wh(e,s),qi(e,t,n)};var Hr="suggest_replies";var Qu={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},Vi={name:Hr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:Qu,origin:"sdk",annotations:{readOnlyHint:!0}},Ki=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ha=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Hr},Yu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Gi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!Ha(r))continue;let o=Yu((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},Zu=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var em={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,description:"Questions to ask the user. Prefer a single question.",items:{type:"object",properties:{question:{type:"string",description:"The complete question, ending with a question mark."},header:{type:"string",maxLength:12,description:'Short topic label, e.g. "Auth method".'},options:{type:"array",minItems:2,maxItems:4,description:'2-4 distinct choices. Do NOT add an "Other" option: free text is automatic.',items:{type:"object",properties:{label:{type:"string",description:"Concise choice text (1-5 words)."},description:{type:"string",description:"What the option means or implies."}},required:["label"],additionalProperties:!1}},multiSelect:{type:"boolean",description:"Allow selecting multiple options. Default false."},allowFreeText:{type:"boolean",description:"Show a free-text input. Default true."}},required:["question","options"],additionalProperties:!1}}},required:["questions"],additionalProperties:!1},tm={name:Pa,description:"Ask the user multiple-choice questions and wait for their answers. Use only when blocked on a decision that is the user's to make: a preference, a choice between valid approaches, or information you cannot infer. Each question offers 2-4 options plus an automatic free-text input. The result maps each question to its answer (an array when multiSelect); a question absent from the result was skipped.",parametersSchema:em,origin:"sdk",annotations:{readOnlyHint:!0}},Ba=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(tm),Zu(e)&&t.push(Vi),t};import{parse as nm,STR as rm,OBJ as om}from"partial-json";var Da=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),fo=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)}},Mh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},sm=e=>e.status==="complete"?Mh(e):e.status==="pending"?"Waiting":"",kh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var am=e=>e.status==="complete"?kh(e):"Using tool...",Na=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Oa=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return Na(t)},Ji=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Fa=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&Gs(r,n.slice(s,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&Gs(r,n.slice(s),[]),r},Gs=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Lh=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Yi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var im="4.3.0";var hr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var el=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 Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":hr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new js(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Ou(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,Qt,Dr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Ee=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Be=A.tools?A.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Ee,tools:Be}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Ee=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Ee||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Ee,Be,Le,De;return W((De=(Le=(Be=(Ee=(te=A.stepId)!=null?te:A.step_id)!=null?Ee:A.step)!=null?Be:A.parentId)!=null?Le:A.flowStepId)!=null?De:A.flow_step_id)},N=A=>{var te,Ee,Be,Le,De,Ge,it;return W((it=(Ge=(De=(Le=(Be=(Ee=(te=A.callId)!=null?te:A.call_id)!=null?Ee:A.requestId)!=null?Be:A.request_id)!=null?Le:A.toolCallId)!=null?De:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Z=r,Te=!1,pe=()=>{if(f)return f;let A,te=T;return!Te&&Z?(A=Z,Te=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},xe=(A,te)=>{var De;let Ee=(De=A.reasoningId)!=null?De:A.id,Be=O(A);if(Ee){let Ge=String(Ee);return ee(Be,Ge),Ge}if(Be){let Ge=F.byStep.get(Be);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Le=`reason-${l()}`;return ee(Be,Le),Le},Me=A=>{let te=C.get(A);if(te)return te;let Ee={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Ee),g(Ee),Ee},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},be=new Set,de=new Map,ae=new Set,se=new Map,We=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Oe=(A,te)=>{var De;let Ee=(De=A.toolId)!=null?De:A.id,Be=N(A);if(Ee){let Ge=String(Ee);return oe(Be,Ge),Ge}if(Be){let Ge=j.byCall.get(Be);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Le=`tool-${l()}`;return oe(Be,Le),Le},V=A=>{let te=R.get(A);if(te)return te;let Ee={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Ee),g(Ee),Ee},K=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Ee=Date.parse(A);if(!Number.isNaN(Ee))return Ee}return Date.now()},ve=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},J=new Map,ce=new Map,Re=new Map,ge=(A,te,Ee)=>{var it;let Be=Re.get(A);Be||(Be=[],Re.set(A,Be));let Le=0,De=Be.length;for(;Le<De;){let Pt=Le+De>>>1;Be[Pt].seq<te?Le=Pt+1:De=Pt}((it=Be[Le])==null?void 0:it.seq)===te?Be[Le]={seq:te,text:Ee}:Be.splice(Le,0,{seq:te,text:Ee});let Ge="";for(let Pt=0;Pt<Be.length;Pt++)Ge+=Be[Pt].text;return Ge},Ke=(A,te)=>{let Ee=ve(te),Be=ce.get(A.id),Le=Bh(Be,Ee);A.rawContent=Le;let De=J.get(A.id),Ge=Q=>{var lt;let Se=(lt=A.content)!=null?lt:"";Q.trim()!==""&&(Se.trim().length===0||Q.startsWith(Se)||Q.trimStart().startsWith(Se.trim()))&&(A.content=Q)},it=()=>{var Q;if(De){let Se=(Q=De.close)==null?void 0:Q.call(De);Se instanceof Promise&&Se.catch(()=>{})}J.delete(A.id),ce.delete(A.id),A.streaming=!1,g(A)};if(!De){Ge(Ee),it();return}let Pt=Xs(Le);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),it();return}let bt=Q=>{var Qe;let Se=typeof Q=="string"?Q:(Qe=Q==null?void 0:Q.text)!=null?Qe:null;if(Se!==null&&Se.trim()!=="")return Se;let lt=De.getExtractedText();return lt!==null&&lt.trim()!==""?lt:Ee},H;try{H=De.processChunk(Le)}catch{Ge(Ee),it();return}if(H instanceof Promise){H.then(Q=>{Ge(bt(Q)),it()}).catch(()=>{Ge(Ee),it()});return}Ge(bt(H)),it()},tt=null,Lt=(A,te,Ee,Be)=>{var Pt;A.rawContent=te,J.has(A.id)||J.set(A.id,this.createStreamParser());let Le=J.get(A.id),De=te.trim().startsWith("{")||te.trim().startsWith("[");if(De&&ce.set(A.id,te),Le.__isPlainTextParser===!0){A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A);return}let it=Le.processChunk(te);if(it instanceof Promise)it.then(bt=>{var Q;let H=typeof bt=="string"?bt:(Q=bt==null?void 0:bt.text)!=null?Q:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof it=="string"?it:(Pt=it==null?void 0:it.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Ee=te!=null?te:A.content;if(Ee==null||Ee===""){A.streaming=!1,g(A);return}let Be=ce.get(A.id),Le=Be!=null?Be:ve(Ee);A.rawContent=Le;let De=J.get(A.id),Ge=null,it=!1;if(De&&(Ge=De.getExtractedText(),Ge===null&&(Ge=Xs(Le)),Ge===null)){let H=De.processChunk(Le);H instanceof Promise?(it=!0,H.then(Q=>{var lt;let Se=typeof Q=="string"?Q:(lt=Q==null?void 0:Q.text)!=null?lt:null;Se!==null&&(A.content=Se,A.streaming=!1,J.delete(A.id),ce.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:ce.has(A.id)||(A.content=ve(Ee));let H=J.get(A.id);if(H){let Q=(bt=H.close)==null?void 0:bt.call(H);Q instanceof Promise&&Q.catch(()=>{}),J.delete(A.id)}ce.delete(A.id),A.streaming=!1,g(A)}},_e=(A,te,Ee)=>{let Be=M.get(A);if(Be)return Be;let Le={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Le),g(Le),Le},G=[],ze,qe=new Map,we=0,Ae="agent",nt=!1,Ft=null,ne=null,$e=new Map,hn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ze=()=>{var A,te,Ee,Be,Le,De,Ge,it,Pt,bt,H,Q,Se,lt,Qe,jt,yn,xt,vt,It,wt,dn,_t,Nn,Sn,Tn,xn,En,lr,Ct,xr,vr,Nr,cr,ut,Co,wr,Ao,Rn,Xo,Qr,Or,Yr,Zr,So,To,eo,yt,On,Fn,Mn,At,Xn,Qn,_n,to,Fr,no,$n,Rt,kn,Yn,ro,_r,oo,he,Wn,Cr,mt,rn,on,Ar,ks,$r,Eo,Sr,$,Qo,Tr,Er,jr,Mr,dr,Yo,xa,jn,Un,pr,ur,Mo,Ur,vn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,Hn,Ca;for(let rs=0;rs<G.length;rs++){let et=G[rs].payloadType,w=G[rs].payload;if(!nt&&Ae!=="flow"&&typeof w.stepType=="string"&&(Ae="flow"),et==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),_e(z,U,"reasoning");continue}let X=(A=xe(w,!0))!=null?A:`reason-${l()}`,fe=Me(X);fe.reasoning=(te=fe.reasoning)!=null?te:{id:X,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:K((Ee=w.startedAt)!=null?Ee:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(et==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let Fe=M.get(z),gt=(Ge=(De=(Le=w.reasoningText)!=null?Le:w.text)!=null?De:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let U=(Pt=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?Pt:`reason-${l()}`,X=Me(U);X.reasoning=(bt=X.reasoning)!=null?bt:{id:U,status:"streaming",chunks:[]},X.reasoning.startedAt=(Q=X.reasoning.startedAt)!=null?Q:K((H=w.startedAt)!=null?H:w.timestamp);let fe=(Qe=(lt=(Se=w.reasoningText)!=null?Se:w.text)!=null?lt:w.delta)!=null?Qe:"";if(fe&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let gt=ge(U,Fe,String(fe));X.reasoning.chunks=[gt]}else X.reasoning.chunks.push(String(fe))}if(X.reasoning.status=w.done?"complete":"streaming",w.done){X.reasoning.completedAt=K((jt=w.completedAt)!=null?jt:w.timestamp);let Fe=(yn=X.reasoning.startedAt)!=null?yn:Date.now();X.reasoning.durationMs=Math.max(0,((xt=X.reasoning.completedAt)!=null?xt:Date.now())-Fe)}X.streaming=X.reasoning.status!=="complete",g(X)}else if(et==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(It=(vt=xe(w,!1))!=null?vt:xe(w,!0))!=null?It:`reason-${l()}`,X=typeof w.text=="string"?w.text:"";!C.get(U)&&(X||w.scope==="loop")&&Me(U);let fe=C.get(U);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),X&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(X),fe.reasoning.status="complete",fe.reasoning.completedAt=K((wt=w.completedAt)!=null?wt:w.timestamp);let gt=(dn=fe.reasoning.startedAt)!=null?dn:Date.now();fe.reasoning.durationMs=Math.max(0,((_t=fe.reasoning.completedAt)!=null?_t:Date.now())-gt),fe.streaming=!1,g(fe)}let Fe=O(w);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(Sn=(Nn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Nn:Oe(w,!0))!=null?Sn:`tool-${l()}`,U=(Tn=w.toolName)!=null?Tn:w.name;if(We(U)){be.add(z);continue}oe(N(w),z);let X=V(z),fe=(xn=X.toolCall)!=null?xn:{id:z,status:"pending"};fe.name=U!=null?U:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(lr=fe.startedAt)!=null?lr:K((En=w.startedAt)!=null?En:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,X.toolCall=fe,X.streaming=!0,w.executionId&&(X.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(X)}else if(et==="tool_output_delta"){let z=(xr=(Ct=Oe(w,!1))!=null?Ct:Oe(w,!0))!=null?xr:`tool-${l()}`;if(be.has(z))continue;let U=V(z),X=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};X.startedAt=(cr=X.startedAt)!=null?cr:K((Nr=w.startedAt)!=null?Nr:w.timestamp);let fe=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";fe&&(X.chunks=(Ao=X.chunks)!=null?Ao:[],X.chunks.push(String(fe))),X.status="running",U.toolCall=X,U.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Rn=Fe==null?void 0:Fe.executionId)!=null?Rn:w.executionId,iteration:(Xo=Fe==null?void 0:Fe.iteration)!=null?Xo:w.iteration}),g(U)}else if(et==="tool_complete"){let z=(Yr=(Or=Oe(w,!1))!=null?Or:Oe(w,!0))!=null?Yr:`tool-${l()}`;if(be.has(z)){be.delete(z);continue}let U=V(z),X=(Zr=U.toolCall)!=null?Zr:{id:z,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),typeof w.duration=="number"&&(X.duration=w.duration),X.completedAt=K((So=w.completedAt)!=null?So:w.timestamp);let fe=(To=w.duration)!=null?To:w.executionTime;if(typeof fe=="number")X.durationMs=fe;else{let st=(eo=X.startedAt)!=null?eo:Date.now();X.durationMs=Math.max(0,((yt=X.completedAt)!=null?yt:Date.now())-st)}U.toolCall=X,U.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Mn=U.agentMetadata)!=null?Mn:{executionId:(On=Fe==null?void 0:Fe.executionId)!=null?On:w.executionId,iteration:(Fn=Fe==null?void 0:Fe.iteration)!=null?Fn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(et==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(At=z!=null?z:w.toolId)!=null?At:`local-${l()}`,X=V(U),fe=w.toolName,Fe=w.origin==="webmcp"&&!Oo(fe)?`webmcp:${fe}`:fe,gt=Oo(Fe),st=(Xn=X.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=Fe,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Fr=st.startedAt)!=null?Fr:K((to=(_n=w.startedAt)!=null?_n:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,X.toolCall=st,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:($n=X.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(X)}else if(et==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let X=f;X&&(Ae==="flow"?(Ye(X),tt=X):(X.streaming=!1,g(X)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(et==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let fe=typeof w.delta=="string"?w.delta:"",Fe=((kn=P.get(z))!=null?kn:"")+fe;if(P.set(z,Fe),Fe.trim()==="")continue;let gt=_e(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},Lt(gt,Fe,fe,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Ae==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(L+=fe,L.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Lt(Fe,L,fe,void 0),v=Fe;continue}let X=pe();X.content+=(Yn=w.delta)!=null?Yn:"",X.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ft!=null?Ft:void 0,agentName:ne==null?void 0:ne.agentName},v=X,g(X)}else if(et==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let X=M.get(z);X&&Ye(X),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Ae==="flow"?(Ye(U),tt=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(et==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let X=w.error,fe=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((_r=X.message)!=null?_r:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let X=tt;tt=null;let fe=w.stopReason,Fe=(oo=w.result)==null?void 0:oo.response;if(X)fe&&(X.stopReason=fe),Fe!=null?Ke(X,Fe):X.streaming!==!1&&(J.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X));else{let gt=Fe!=null&&Fe!=="";if(gt||fe){let st=pe();fe&&(st.stopReason=fe),gt?Ye(st,Fe):(st.streaming=!1,g(st))}}continue}}else if(et==="execution_start")Ae=w.kind==="flow"?"flow":"agent",nt=!0,Ae==="agent"&&(ne={executionId:w.executionId,agentId:(he=w.agentId)!=null?he:"virtual",agentName:(Wn=w.agentName)!=null?Wn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:K(w.startedAt)});else if(et==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(ne&&(ne.currentIteration=z),hn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),$e.set(z-1,U),f=null)}we=z}Ft=typeof w.id=="string"?w.id:null,v=null}else if(et==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let X=w.id;(!X||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===X)&&(U.stopReason=z,g(U))}Ft===w.id&&(Ft=null)}else if(et==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(et==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let X=($r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?$r:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(fe)gt={type:"media",data:fe,mediaType:X};else if(Fe){let pn=X.toLowerCase();gt={type:pn==="image"||pn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:X}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Bn=[];for(let pn of Ps){if(!pn||typeof pn!="object")continue;let un=pn,Lo=typeof un.type=="string"?un.type:void 0,qr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",Ln=null,bn="";if(Lo==="media"){let qn=typeof un.data=="string"?un.data:void 0;if(!qn)continue;bn=qr.length>0?qr:"application/octet-stream",Ln=`data:${bn};base64,${qn}`}else if(Lo==="image-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else if(Lo==="file-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else continue;if(Ln)if(Lo==="image-url"||bn.startsWith("image/"))Bn.push({type:"image",image:Ln,...bn.includes("/")?{mimeType:bn}:{}});else if(bn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:bn});else if(bn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:bn});else{let qn=bn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Wh(qn)})}}if(Bn.length>0){let pn=l(),un=st,qr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${pn}`:String(pn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(qr);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,x.current=null}}else if(et==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Ae;z==="agent"&&ne&&(ne.status=w.success?"complete":"error",ne.completedAt=K(w.completedAt),ne.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Ye(U):(U.streaming=!1,g(U)),f=null),T=null,L="",tt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(et!=="ping"){if(et==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ne==null?void 0:ne.agentId)!=null?Er:"virtual",executionId:(Mr=(jr=w.executionId)!=null?jr:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(dr=w.toolName)!=null?dr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let z=(jn=w.approvalId)!=null?jn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Un=ne==null?void 0:ne.agentId)!=null?Un:"virtual",executionId:(ur=(pr=w.executionId)!=null?pr:ne==null?void 0:ne.executionId)!=null?ur:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(vn=w.description)!=null?vn:`Execute ${(Ur=w.toolName)!=null?Ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="approval_complete"){let z=w.approvalId;if(z){let X={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ne==null?void 0:ne.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ne==null?void 0:ne.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(X)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=w.artifactType,U=String(w.id),X=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:X,component:typeof w.component=="string"?w.component:void 0}),se.set(U,{markdown:"",title:X}),!ae.has(U)){ae.add(U);let fe={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:X,artifactType:z,status:"streaming"}})};de.set(U,fe),g(fe)}}else if(et==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let X=se.get(z);X&&(X.markdown+=U)}else if(et==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=de.get(z);if(U){U.streaming=!1;try{let X=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(X.props){X.props.status="complete";let fe=se.get(z);fe!=null&&fe.markdown&&(X.props.markdown=fe.markdown)}U.rawContent=JSON.stringify(X)}catch{}se.delete(z),g(U),de.delete(z)}}}else if(et==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),X=z.role,Fe={id:U,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&ae.add(st)}catch{}f=null,x.current=null,J.delete(U),ce.delete(U)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(et==="dispatch_error"){let U=(Hn=w.message)!=null?Hn:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}G.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Ee=a.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Xs=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},Xi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},Qi=()=>{var t;let e=Lh();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},Yi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=nm(n,rm|om);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?Da(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=Da(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Ph=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?Da(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?Da(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=nm(s,rm|om),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},Zi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var im="4.4.0";var hr=im;var Rh="https://api.runtype.com/v1/dispatch",_a="https://api.runtype.com";function Wh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var el=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 Hh(e){switch(e){case"json":return Yi;case"regex-json":return Qi;case"xml":return Zi;default:return Xi}}var lm=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Bh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lm(n);if(!lm(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Xs(e);return Xs(t)!==null&&a===null?t:e}var fs=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:Rh,this.headers={"Content-Type":"application/json","X-Persona-Version":hr,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Hh(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new js(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Ou(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,l;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(l=n.agentId)!=null?l:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(el).map(M=>{var P,C,R;return{id:M.id,role:M.role,content:(R=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},g=l.clientTools,f=!!(g&&g.length>0),v=f?Du(g):void 0,x=this.clientToolsFingerprintSessionId===d.sessionId,E=f&&x&&this.lastSentClientToolsFingerprint===v,T=!1,L=null,k;for(let M=0;;M++){let C={...u,...f&&(T||!E)&&g?{clientTools:g}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":hr},body:JSON.stringify(C),signal:r.signal}),k.status===409&&M===0&&f){let R=await k.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){T=!0,this.lastSentClientToolsFingerprint=null;continue}L=R!=null?R:{error:"Chat request failed"}}break}if(!k.ok){let M=L!=null?L:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:C}),C}if(k.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw n({type:"error",error:P}),P}if(!k.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||_a}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||_a}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(el).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let u=new Date(l.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(l=>{var p,u,g;return{role:l.role,content:(g=(u=(p=l.contentParts)!=null?p:l.llmContent)!=null?u:l.rawContent)!=null?g:l.content,createdAt:l.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(l,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(l).length&&(o.context=l)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(el).sort((d,l)=>{let p=new Date(d.createdAt).getTime(),u=new Date(l.createdAt).getTime();return p-u}).map(d=>{var l,p,u;return{role:d.role,content:(u=(p=(l=d.contentParts)!=null?l:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,l]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=l);let s=[...Ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let l=d;return o.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=o.clientTools),l}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,Qt,Dr,br;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=A=>{let te=A.reasoning?{...A.reasoning,chunks:[...A.reasoning.chunks]}:void 0,Ee=A.toolCall?{...A.toolCall,chunks:A.toolCall.chunks?[...A.toolCall.chunks]:void 0}:void 0,Be=A.tools?A.tools.map(Le=>({...Le,chunks:Le.chunks?[...Le.chunks]:void 0})):void 0;return{...A,reasoning:te,toolCall:Ee,tools:Be}},u=A=>{if(A.role!=="assistant"||A.variant)return!0;let te=Array.isArray(A.contentParts)&&A.contentParts.length>0,Ee=typeof A.rawContent=="string"&&A.rawContent.trim()!=="";return typeof A.content=="string"&&A.content.trim()!==""||te||Ee||!!A.stopReason},g=A=>{u(A)&&n({type:"message",message:p(A)})},f=null,v=null,x={current:null},E={current:null},T=null,L="",k=new Map,M=new Map,P=new Map,C=new Map,R=new Map,F={lastId:null,byStep:new Map},j={lastId:null,byCall:new Map},W=A=>{if(A==null)return null;try{return String(A)}catch{return null}},O=A=>{var te,Ee,Be,Le,De;return W((De=(Le=(Be=(Ee=(te=A.stepId)!=null?te:A.step_id)!=null?Ee:A.step)!=null?Be:A.parentId)!=null?Le:A.flowStepId)!=null?De:A.flow_step_id)},N=A=>{var te,Ee,Be,Le,De,Ge,it;return W((it=(Ge=(De=(Le=(Be=(Ee=(te=A.callId)!=null?te:A.call_id)!=null?Ee:A.requestId)!=null?Be:A.request_id)!=null?Le:A.toolCallId)!=null?De:A.tool_call_id)!=null?Ge:A.stepId)!=null?it:A.step_id)},Z=r,Te=!1,pe=()=>{if(f)return f;let A,te=T;return!Te&&Z?(A=Z,Te=!0):Z&&te?A=`${Z}_${te}`:A=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,f={id:A,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},g(f),f},ee=(A,te)=>{F.lastId=te,A&&F.byStep.set(A,te)},xe=(A,te)=>{var De;let Ee=(De=A.reasoningId)!=null?De:A.id,Be=O(A);if(Ee){let Ge=String(Ee);return ee(Be,Ge),Ge}if(Be){let Ge=F.byStep.get(Be);if(Ge)return F.lastId=Ge,Ge}if(F.lastId&&!te)return F.lastId;if(!te)return null;let Le=`reason-${l()}`;return ee(Be,Le),Le},Me=A=>{let te=C.get(A);if(te)return te;let Ee={id:`reason-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:A,status:"streaming",chunks:[]}};return C.set(A,Ee),g(Ee),Ee},oe=(A,te)=>{j.lastId=te,A&&j.byCall.set(A,te)},be=new Set,de=new Map,ae=new Set,se=new Map,We=A=>{if(!A)return!1;let te=A.replace(/_+/g,"_").replace(/^_|_$/g,"");return te==="emit_artifact_markdown"||te==="emit_artifact_component"},Oe=(A,te)=>{var De;let Ee=(De=A.toolId)!=null?De:A.id,Be=N(A);if(Ee){let Ge=String(Ee);return oe(Be,Ge),Ge}if(Be){let Ge=j.byCall.get(Be);if(Ge)return j.lastId=Ge,Ge}if(j.lastId&&!te)return j.lastId;if(!te)return null;let Le=`tool-${l()}`;return oe(Be,Le),Le},V=A=>{let te=R.get(A);if(te)return te;let Ee={id:`tool-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:A,status:"pending"}};return R.set(A,Ee),g(Ee),Ee},K=A=>{if(typeof A=="number"&&Number.isFinite(A))return A;if(typeof A=="string"){let te=Number(A);if(!Number.isNaN(te)&&Number.isFinite(te))return te;let Ee=Date.parse(A);if(!Number.isNaN(Ee))return Ee}return Date.now()},ve=A=>{if(typeof A=="string")return A;if(A==null)return"";try{return JSON.stringify(A)}catch{return String(A)}},J=new Map,ce=new Map,Re=new Map,ge=(A,te,Ee)=>{var it;let Be=Re.get(A);Be||(Be=[],Re.set(A,Be));let Le=0,De=Be.length;for(;Le<De;){let Pt=Le+De>>>1;Be[Pt].seq<te?Le=Pt+1:De=Pt}((it=Be[Le])==null?void 0:it.seq)===te?Be[Le]={seq:te,text:Ee}:Be.splice(Le,0,{seq:te,text:Ee});let Ge="";for(let Pt=0;Pt<Be.length;Pt++)Ge+=Be[Pt].text;return Ge},Ke=(A,te)=>{let Ee=ve(te),Be=ce.get(A.id),Le=Bh(Be,Ee);A.rawContent=Le;let De=J.get(A.id),Ge=Q=>{var lt;let Se=(lt=A.content)!=null?lt:"";Q.trim()!==""&&(Se.trim().length===0||Q.startsWith(Se)||Q.trimStart().startsWith(Se.trim()))&&(A.content=Q)},it=()=>{var Q;if(De){let Se=(Q=De.close)==null?void 0:Q.call(De);Se instanceof Promise&&Se.catch(()=>{})}J.delete(A.id),ce.delete(A.id),A.streaming=!1,g(A)};if(!De){Ge(Ee),it();return}let Pt=Xs(Le);if(Pt!==null&&Pt.trim()!==""){Ge(Pt),it();return}let bt=Q=>{var Qe;let Se=typeof Q=="string"?Q:(Qe=Q==null?void 0:Q.text)!=null?Qe:null;if(Se!==null&&Se.trim()!=="")return Se;let lt=De.getExtractedText();return lt!==null&&lt.trim()!==""?lt:Ee},H;try{H=De.processChunk(Le)}catch{Ge(Ee),it();return}if(H instanceof Promise){H.then(Q=>{Ge(bt(Q)),it()}).catch(()=>{Ge(Ee),it()});return}Ge(bt(H)),it()},tt=null,Lt=(A,te,Ee,Be)=>{var Pt;A.rawContent=te,J.has(A.id)||J.set(A.id,this.createStreamParser());let Le=J.get(A.id),De=te.trim().startsWith("{")||te.trim().startsWith("[");if(De&&ce.set(A.id,te),Le.__isPlainTextParser===!0){A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A);return}let it=Le.processChunk(te);if(it instanceof Promise)it.then(bt=>{var Q;let H=typeof bt=="string"?bt:(Q=bt==null?void 0:bt.text)!=null?Q:null;H!==null&&H.trim()!==""?(A.content=H,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}).catch(()=>{A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A)});else{let bt=typeof it=="string"?it:(Pt=it==null?void 0:it.text)!=null?Pt:null;bt!==null&&bt.trim()!==""?(A.content=bt,g(A)):!De&&!te.trim().startsWith("<")&&(A.content=Be!==void 0?te:A.content+Ee,ce.delete(A.id),J.delete(A.id),A.rawContent=void 0,g(A))}},Ye=(A,te)=>{var Pt,bt;let Ee=te!=null?te:A.content;if(Ee==null||Ee===""){A.streaming=!1,g(A);return}let Be=ce.get(A.id),Le=Be!=null?Be:ve(Ee);A.rawContent=Le;let De=J.get(A.id),Ge=null,it=!1;if(De&&(Ge=De.getExtractedText(),Ge===null&&(Ge=Xs(Le)),Ge===null)){let H=De.processChunk(Le);H instanceof Promise?(it=!0,H.then(Q=>{var lt;let Se=typeof Q=="string"?Q:(lt=Q==null?void 0:Q.text)!=null?lt:null;Se!==null&&(A.content=Se,A.streaming=!1,J.delete(A.id),ce.delete(A.id),g(A))}).catch(()=>{})):Ge=typeof H=="string"?H:(Pt=H==null?void 0:H.text)!=null?Pt:null}if(!it){Ge!==null&&Ge.trim()!==""?A.content=Ge:ce.has(A.id)||(A.content=ve(Ee));let H=J.get(A.id);if(H){let Q=(bt=H.close)==null?void 0:bt.call(H);Q instanceof Promise&&Q.catch(()=>{}),J.delete(A.id)}ce.delete(A.id),A.streaming=!1,g(A)}},_e=(A,te,Ee)=>{let Be=M.get(A);if(Be)return Be;let Le={id:`nested-${te}-${A}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:A,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:te}};return M.set(A,Le),g(Le),Le},G=[],ze,qe=new Map,we=0,Ae="agent",nt=!1,Ft=null,ne=null,$e=new Map,hn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ze=()=>{var A,te,Ee,Be,Le,De,Ge,it,Pt,bt,H,Q,Se,lt,Qe,jt,yn,xt,vt,It,wt,dn,_t,Nn,Sn,Tn,xn,En,lr,Ct,xr,vr,Nr,cr,ut,Co,wr,Ao,Rn,Xo,Qr,Or,Yr,Zr,So,To,eo,yt,On,Fn,Mn,At,Xn,Qn,_n,to,Fr,no,$n,Rt,kn,Yn,ro,_r,oo,he,Wn,Cr,mt,rn,on,Ar,ks,$r,Eo,Sr,$,Qo,Tr,Er,jr,Mr,dr,Yo,xa,jn,Un,pr,ur,Mo,Ur,vn,kr,Zo,ko,es,va,ts,wa,ns,pt,Ls,Zn,Hn,Ca;for(let rs=0;rs<G.length;rs++){let et=G[rs].payloadType,w=G[rs].payload;if(!nt&&Ae!=="flow"&&typeof w.stepType=="string"&&(Ae="flow"),et==="reasoning_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U),_e(z,U,"reasoning");continue}let X=(A=xe(w,!0))!=null?A:`reason-${l()}`,fe=Me(X);fe.reasoning=(te=fe.reasoning)!=null?te:{id:X,status:"streaming",chunks:[]},fe.reasoning.startedAt=(Be=fe.reasoning.startedAt)!=null?Be:K((Ee=w.startedAt)!=null?Ee:w.timestamp),fe.reasoning.completedAt=void 0,fe.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),fe.streaming=!0,fe.reasoning.status="streaming",g(fe)}else if(et==="reasoning_delta"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let Fe=M.get(z),gt=(Ge=(De=(Le=w.reasoningText)!=null?Le:w.text)!=null?De:w.delta)!=null?Ge:"";gt&&w.hidden!==!0&&Fe.reasoning&&(Fe.reasoning.chunks.push(String(gt)),g(Fe));continue}let U=(Pt=(it=xe(w,!1))!=null?it:xe(w,!0))!=null?Pt:`reason-${l()}`,X=Me(U);X.reasoning=(bt=X.reasoning)!=null?bt:{id:U,status:"streaming",chunks:[]},X.reasoning.startedAt=(Q=X.reasoning.startedAt)!=null?Q:K((H=w.startedAt)!=null?H:w.timestamp);let fe=(Qe=(lt=(Se=w.reasoningText)!=null?Se:w.text)!=null?lt:w.delta)!=null?Qe:"";if(fe&&w.hidden!==!0){let Fe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Fe!==void 0){let gt=ge(U,Fe,String(fe));X.reasoning.chunks=[gt]}else X.reasoning.chunks.push(String(fe))}if(X.reasoning.status=w.done?"complete":"streaming",w.done){X.reasoning.completedAt=K((jt=w.completedAt)!=null?jt:w.timestamp);let Fe=(yn=X.reasoning.startedAt)!=null?yn:Date.now();X.reasoning.durationMs=Math.max(0,((xt=X.reasoning.completedAt)!=null?xt:Date.now())-Fe)}X.streaming=X.reasoning.status!=="complete",g(X)}else if(et==="reasoning_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)&&M.has(z)){let gt=M.get(z);if(gt.reasoning){let st=typeof w.text=="string"?w.text:"";st&&gt.reasoning.chunks.length===0&&gt.reasoning.chunks.push(st),gt.reasoning.status="complete",gt.streaming=!1,g(gt)}k.delete(z),M.delete(z);continue}let U=(It=(vt=xe(w,!1))!=null?vt:xe(w,!0))!=null?It:`reason-${l()}`,X=typeof w.text=="string"?w.text:"";!C.get(U)&&(X||w.scope==="loop")&&Me(U);let fe=C.get(U);if(fe!=null&&fe.reasoning){(w.scope==="loop"||w.scope==="turn")&&(fe.reasoning.scope=w.scope),X&&fe.reasoning.chunks.length===0&&fe.reasoning.chunks.push(X),fe.reasoning.status="complete",fe.reasoning.completedAt=K((wt=w.completedAt)!=null?wt:w.timestamp);let gt=(dn=fe.reasoning.startedAt)!=null?dn:Date.now();fe.reasoning.durationMs=Math.max(0,((_t=fe.reasoning.completedAt)!=null?_t:Date.now())-gt),fe.streaming=!1,g(fe)}let Fe=O(w);Fe&&F.byStep.delete(Fe)}else if(et==="tool_start"){f&&(f.streaming=!1,g(f),f=null),typeof w.iteration=="number"&&(we=w.iteration);let z=(Sn=(Nn=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?Nn:Oe(w,!0))!=null?Sn:`tool-${l()}`,U=(Tn=w.toolName)!=null?Tn:w.name;if(We(U)){be.add(z);continue}oe(N(w),z);let X=V(z),fe=(xn=X.toolCall)!=null?xn:{id:z,status:"pending"};fe.name=U!=null?U:fe.name,fe.status="running",w.parameters!==void 0?fe.args=w.parameters:w.args!==void 0&&(fe.args=w.args),fe.startedAt=(lr=fe.startedAt)!=null?lr:K((En=w.startedAt)!=null?En:w.timestamp),fe.completedAt=void 0,fe.durationMs=void 0,X.toolCall=fe,X.streaming=!0,w.executionId&&(X.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(X)}else if(et==="tool_output_delta"){let z=(xr=(Ct=Oe(w,!1))!=null?Ct:Oe(w,!0))!=null?xr:`tool-${l()}`;if(be.has(z))continue;let U=V(z),X=(vr=U.toolCall)!=null?vr:{id:z,status:"running"};X.startedAt=(cr=X.startedAt)!=null?cr:K((Nr=w.startedAt)!=null?Nr:w.timestamp);let fe=(wr=(Co=(ut=w.text)!=null?ut:w.delta)!=null?Co:w.message)!=null?wr:"";fe&&(X.chunks=(Ao=X.chunks)!=null?Ao:[],X.chunks.push(String(fe))),X.status="running",U.toolCall=X,U.streaming=!0;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Qr=U.agentMetadata)!=null?Qr:{executionId:(Rn=Fe==null?void 0:Fe.executionId)!=null?Rn:w.executionId,iteration:(Xo=Fe==null?void 0:Fe.iteration)!=null?Xo:w.iteration}),g(U)}else if(et==="tool_complete"){let z=(Yr=(Or=Oe(w,!1))!=null?Or:Oe(w,!0))!=null?Yr:`tool-${l()}`;if(be.has(z)){be.delete(z);continue}let U=V(z),X=(Zr=U.toolCall)!=null?Zr:{id:z,status:"running"};X.status="complete",w.result!==void 0&&(X.result=w.result),typeof w.duration=="number"&&(X.duration=w.duration),X.completedAt=K((So=w.completedAt)!=null?So:w.timestamp);let fe=(To=w.duration)!=null?To:w.executionTime;if(typeof fe=="number")X.durationMs=fe;else{let st=(eo=X.startedAt)!=null?eo:Date.now();X.durationMs=Math.max(0,((yt=X.completedAt)!=null?yt:Date.now())-st)}U.toolCall=X,U.streaming=!1;let Fe=w.agentContext;(Fe||w.executionId)&&(U.agentMetadata=(Mn=U.agentMetadata)!=null?Mn:{executionId:(On=Fe==null?void 0:Fe.executionId)!=null?On:w.executionId,iteration:(Fn=Fe==null?void 0:Fe.iteration)!=null?Fn:w.iteration}),g(U);let gt=N(w);gt&&j.byCall.delete(gt)}else if(et==="await"&&w.toolName){let z=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,U=(At=z!=null?z:w.toolId)!=null?At:`local-${l()}`,X=V(U),fe=w.toolName,Fe=w.origin==="webmcp"&&!Oo(fe)?`webmcp:${fe}`:fe,gt=Oo(Fe),st=(Xn=X.toolCall)!=null?Xn:{id:U,status:"pending"};st.name=Fe,st.args=w.parameters,st.status=gt?"running":"complete",st.chunks=(Qn=st.chunks)!=null?Qn:[],st.startedAt=(Fr=st.startedAt)!=null?Fr:K((to=(_n=w.startedAt)!=null?_n:w.timestamp)!=null?to:w.awaitedAt),gt?(st.completedAt=void 0,st.duration=void 0,st.durationMs=void 0):st.completedAt=(no=st.completedAt)!=null?no:st.startedAt,X.toolCall=st,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=w.executionId)!=null?Rt:($n=X.agentMetadata)==null?void 0:$n.executionId,awaitingLocalTool:!0,...z?{webMcpToolCallId:z}:{}},g(X)}else if(et==="text_start"){let z=typeof w.id=="string"?w.id:null,U=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(z&&U){k.set(z,U);continue}let X=f;X&&(Ae==="flow"?(Ye(X),tt=X):(X.streaming=!1,g(X)),f=null),T=typeof w.id=="string"?w.id:T,L=""}else if(et==="text_delta"){let z=typeof w.id=="string"?w.id:null,U=z?k.get(z):void 0;if(z&&U){let fe=typeof w.delta=="string"?w.delta:"",Fe=((kn=P.get(z))!=null?kn:"")+fe;if(P.set(z,Fe),Fe.trim()==="")continue;let gt=_e(z,U);gt.agentMetadata={...gt.agentMetadata,executionId:w.executionId,parentToolId:U},Lt(gt,Fe,fe,void 0);continue}if(T=typeof w.id=="string"?w.id:T,Ae==="flow"){let fe=typeof w.delta=="string"?w.delta:"";if(L+=fe,L.trim()==="")continue;let Fe=pe();Fe.agentMetadata={executionId:w.executionId,iteration:w.iteration},Lt(Fe,L,fe,void 0),v=Fe;continue}let X=pe();X.content+=(Yn=w.delta)!=null?Yn:"",X.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:Ft!=null?Ft:void 0,agentName:ne==null?void 0:ne.agentName},v=X,g(X)}else if(et==="text_complete"){let z=typeof w.id=="string"?w.id:null;if(z&&k.has(z)){let X=M.get(z);X&&Ye(X),k.delete(z),P.delete(z),M.delete(z);continue}let U=f;U&&(Ae==="flow"?(Ye(U),tt=U):(((ro=U.content)!=null?ro:"")===""&&typeof w.text=="string"&&(U.content=w.text),U.streaming=!1,g(U)),f=null),T=null,L=""}else if(et==="step_complete"){let z=w.stepType,U=w.executionType;if(z==="tool"||U==="context")continue;if(w.success===!1){let X=w.error,fe=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((_r=X.message)!=null?_r:"Step failed"):"Step failed";n({type:"error",error:new Error(fe)});let Fe=f;Fe&&Fe.streaming&&(Fe.streaming=!1,g(Fe)),n({type:"status",status:"idle"});continue}{let X=tt;tt=null;let fe=w.stopReason,Fe=(oo=w.result)==null?void 0:oo.response;if(X)fe&&(X.stopReason=fe),Fe!=null?Ke(X,Fe):X.streaming!==!1&&(J.delete(X.id),ce.delete(X.id),X.streaming=!1,g(X));else{let gt=Fe!=null&&Fe!=="";if(gt||fe){let st=pe();fe&&(st.stopReason=fe),gt?Ye(st,Fe):(st.streaming=!1,g(st))}}continue}}else if(et==="execution_start")Ae=w.kind==="flow"?"flow":"agent",nt=!0,Ae==="agent"&&(ne={executionId:w.executionId,agentId:(he=w.agentId)!=null?he:"virtual",agentName:(Wn=w.agentName)!=null?Wn:"",status:"running",currentIteration:0,maxTurns:(Cr=w.maxTurns)!=null?Cr:1,startedAt:K(w.startedAt)});else if(et==="turn_start"){let z=typeof w.iteration=="number"?w.iteration:we;if(z!==we){if(ne&&(ne.currentIteration=z),hn==="separate"&&z>1){let U=f;U&&(U.streaming=!1,g(U),$e.set(z-1,U),f=null)}we=z}Ft=typeof w.id=="string"?w.id:null,v=null}else if(et==="tool_input_delta"){let z=(mt=w.toolCallId)!=null?mt:j.lastId;if(z){let U=R.get(z);U!=null&&U.toolCall&&(U.toolCall.chunks=(rn=U.toolCall.chunks)!=null?rn:[],U.toolCall.chunks.push((on=w.delta)!=null?on:""),g(U))}}else{if(et==="tool_input_complete")continue;if(et==="turn_complete"){let z=w.stopReason,U=f!=null?f:v;if(z&&U!==null){let X=w.id;(!X||((Ar=U.agentMetadata)==null?void 0:Ar.turnId)===X)&&(U.stopReason=z,g(U))}Ft===w.id&&(Ft=null)}else if(et==="media_start"){let z=String(w.id);qe.set(z,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(et==="media_delta"){let z=qe.get(String(w.id));z&&typeof w.delta=="string"&&z.parts.push(w.delta)}else if(et==="media_complete"){let z=String(w.id),U=qe.get(z);qe.delete(z);let X=($r=(ks=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?ks:U==null?void 0:U.mediaType)!=null?$r:"application/octet-stream",fe=typeof w.data=="string"?w.data:void 0,Fe=typeof w.url=="string"?w.url:U&&U.parts.length>0?U.parts.join(""):void 0,gt=null;if(fe)gt={type:"media",data:fe,mediaType:X};else if(Fe){let pn=X.toLowerCase();gt={type:pn==="image"||pn.startsWith("image/")?"image-url":"file-url",url:Fe,mediaType:X}}let st=(Eo=w.toolCallId)!=null?Eo:U==null?void 0:U.toolCallId,Ps=gt?[gt]:[],Bn=[];for(let pn of Ps){if(!pn||typeof pn!="object")continue;let un=pn,Lo=typeof un.type=="string"?un.type:void 0,qr=typeof un.mediaType=="string"?un.mediaType.toLowerCase():"",Ln=null,bn="";if(Lo==="media"){let qn=typeof un.data=="string"?un.data:void 0;if(!qn)continue;bn=qr.length>0?qr:"application/octet-stream",Ln=`data:${bn};base64,${qn}`}else if(Lo==="image-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else if(Lo==="file-url"){let qn=typeof un.url=="string"?un.url:void 0;if(!qn)continue;bn=qr,Ln=qn}else continue;if(Ln)if(Lo==="image-url"||bn.startsWith("image/"))Bn.push({type:"image",image:Ln,...bn.includes("/")?{mimeType:bn}:{}});else if(bn.startsWith("audio/"))Bn.push({type:"audio",audio:Ln,mimeType:bn});else if(bn.startsWith("video/"))Bn.push({type:"video",video:Ln,mimeType:bn});else{let qn=bn||"application/octet-stream";Bn.push({type:"file",data:Ln,mimeType:qn,filename:Wh(qn)})}}if(Bn.length>0){let pn=l(),un=st,qr={id:`agent-media-${typeof un=="string"&&un.length>0?`${un}-${pn}`:String(pn)}`,role:"assistant",content:"",contentParts:Bn,createdAt:new Date().toISOString(),streaming:!1,sequence:pn,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:we}};g(qr);let Ln=f;Ln&&(Ln.streaming=!1,g(Ln)),f=null,x.current=null}}else if(et==="execution_complete"){let z=(Sr=w.kind)!=null?Sr:Ae;z==="agent"&&ne&&(ne.status=w.success?"complete":"error",ne.completedAt=K(w.completedAt),ne.stopReason=w.stopReason);let U=f;U&&(z==="flow"&&U.streaming!==!1?Ye(U):(U.streaming=!1,g(U)),f=null),T=null,L="",tt=null,n({type:"status",status:"idle"})}else if(et==="execution_error"){let z=typeof w.error=="string"?w.error:(Qo=($=w.error)==null?void 0:$.message)!=null?Qo:"Execution error";n({type:"error",error:new Error(z)})}else if(et!=="ping"){if(et==="approval_start"){let z=(Tr=w.approvalId)!=null?Tr:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Er=ne==null?void 0:ne.agentId)!=null?Er:"virtual",executionId:(Mr=(jr=w.executionId)!=null?jr:ne==null?void 0:ne.executionId)!=null?Mr:"",toolName:(dr=w.toolName)!=null?dr:"",toolType:w.toolType,description:(xa=w.description)!=null?xa:`Execute ${(Yo=w.toolName)!=null?Yo:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="step_await"&&w.awaitReason==="approval_required"){let z=(jn=w.approvalId)!=null?jn:`approval-${l()}`,U={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:"pending",agentId:(Un=ne==null?void 0:ne.agentId)!=null?Un:"virtual",executionId:(ur=(pr=w.executionId)!=null?pr:ne==null?void 0:ne.executionId)!=null?ur:"",toolName:(Mo=w.toolName)!=null?Mo:"",toolType:w.toolType,description:(vn=w.description)!=null?vn:`Execute ${(Ur=w.toolName)!=null?Ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(U)}else if(et==="approval_complete"){let z=w.approvalId;if(z){let X={id:`approval-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:z,status:(kr=w.decision)!=null?kr:"approved",agentId:(Zo=ne==null?void 0:ne.agentId)!=null?Zo:"virtual",executionId:(es=(ko=w.executionId)!=null?ko:ne==null?void 0:ne.executionId)!=null?es:"",toolName:(va=w.toolName)!=null?va:"",description:(ts=w.description)!=null?ts:"",resolvedAt:Date.now()}};g(X)}}else if(et==="artifact_start"||et==="artifact_delta"||et==="artifact_update"||et==="artifact_complete"){if(et==="artifact_start"){let z=w.artifactType,U=String(w.id),X=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:U,artifactType:z,title:X,component:typeof w.component=="string"?w.component:void 0}),se.set(U,{markdown:"",title:X}),!ae.has(U)){ae.add(U);let fe={id:`artifact-ref-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:U,title:X,artifactType:z,status:"streaming"}})};de.set(U,fe),g(fe)}}else if(et==="artifact_delta"){let z=String(w.id),U=typeof w.delta=="string"?w.delta:String((wa=w.delta)!=null?wa:"");n({type:"artifact_delta",id:z,artDelta:U});let X=se.get(z);X&&(X.markdown+=U)}else if(et==="artifact_update"){let z=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:z,component:typeof w.component=="string"?w.component:void 0})}else if(et==="artifact_complete"){let z=String(w.id);n({type:"artifact_complete",id:z});let U=de.get(z);if(U){U.streaming=!1;try{let X=JSON.parse((ns=U.rawContent)!=null?ns:"{}");if(X.props){X.props.status="complete";let fe=se.get(z);fe!=null&&fe.markdown&&(X.props.markdown=fe.markdown)}U.rawContent=JSON.stringify(X)}catch{}se.delete(z),g(U),de.delete(z)}}}else if(et==="transcript_insert"){let z=w.message;if(!z||typeof z!="object")continue;let U=String((pt=z.id)!=null?pt:`msg-${l()}`),X=z.role,Fe={id:U,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof z.content=="string"?z.content:"",rawContent:typeof z.rawContent=="string"?z.rawContent:void 0,createdAt:typeof z.createdAt=="string"?z.createdAt:new Date().toISOString(),streaming:z.streaming===!0,...typeof z.variant=="string"?{variant:z.variant}:{},sequence:l()};if(g(Fe),Fe.rawContent)try{let gt=JSON.parse(Fe.rawContent),st=(Ls=gt==null?void 0:gt.props)==null?void 0:Ls.artifactId;typeof st=="string"&&ae.add(st)}catch{}f=null,x.current=null,J.delete(U),ce.delete(U)}else if(et==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let z=typeof w.error=="string"?w.error:((Zn=w.error)==null?void 0:Zn.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(z)});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}else if(et==="step_error"||et==="dispatch_error"||et==="flow_error"){let z=null;if(w.error instanceof Error)z=w.error;else if(et==="dispatch_error"){let U=(Hn=w.message)!=null?Hn:w.error;U!=null&&U!==""&&(z=new Error(String(U)))}else{let U=w.error;typeof U=="string"&&U!==""?z=new Error(U):U!=null&&typeof U=="object"&&"message"in U&&(z=new Error(String((Ca=U.message)!=null?Ca:U)))}if(z){n({type:"error",error:z});let U=f;U&&U.streaming&&(U.streaming=!1,g(U)),n({type:"status",status:"idle"})}}}}}G.length=0};;){let{done:A,value:te}=await o.read();if(A)break;a+=s.decode(te,{stream:!0});let Ee=a.split(`
12
12
 
13
13
  `);a=(Qt=Ee.pop())!=null?Qt:"";for(let Be of Ee){let Le=Be.split(`
14
14
  `),De="message",Ge="";for(let bt of Le)bt.startsWith("event:")?De=bt.replace("event:","").trim():bt.startsWith("data:")&&(Ge+=bt.replace("data:","").trim());if(!Ge)continue;let it;try{it=JSON.parse(Ge)}catch(bt){n({type:"error",error:bt instanceof Error?bt:new Error("Failed to parse chat stream payload")});continue}let Pt=De!=="message"?De:(Dr=it.type)!=null?Dr:"message";if((br=this.onSSEEvent)==null||br.call(this,Pt,it),this.parseSSEEvent){x.current=f;let bt=await this.handleCustomSSEEvent(it,n,x,g,l,E);if(x.current&&x.current!==f&&(f=x.current),bt)continue}G.push({payloadType:Pt,payload:it}),ze()}}ze()}};function Dh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function hs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var $a="[Image]";function Nh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Oh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Fh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function _h(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function ja(e){return{type:"text",text:e}}function $h(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function jh(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Uh(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var cm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],qh=["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"],Gr=[...cm,...qh];function zh(e){return cm.includes(e)||e.startsWith("image/")}function Ua(e){return zh(e.type)}async function dm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Ua(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function pm(e,t=Gr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Vh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function um(e,t){let n=Vh(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}tl();var mm=16e3,Kh=24e3,Gh=4096,Jh=1380533830;function Xh(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Jh?new Uint8Array(e,44):new Uint8Array(e)}function Qh(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ys=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:mm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){l.getTracks().forEach(x=>x.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:mm});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new ys(Kh);if(o!==this.callGeneration){g.destroy(),l.getTracks().forEach(x=>x.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Qh(r)}/ws/agents/${encodeURIComponent(t)}/voice`,v=new WebSocket(f,["runtype.bearer",n]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,l,v,o))},v.onmessage=x=>this.handleMessage(x,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=x=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(x.code!==1e3){let E=x.code?` (code ${x.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Gh,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),l=new Int16Array(d.length);for(let p=0;p<d.length;p++){let u=Math.max(-1,Math.min(1,d[p]));l[p]=u<0?u*32768:u*32767}r.send(l.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Xh(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var $o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function jo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(e.runtype);case"browser":if(!$o.isSupported())throw new Error("Browser speech recognition not supported");return new $o(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function nl(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return jo({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return jo({type:"runtype",runtype:e.runtype});if($o.isSupported())return jo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qa(e){try{return nl(e),!0}catch{return!1}}function Zs(e){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 r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Uo=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Zs(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var l,p;let d=i.error;d==="canceled"||d==="interrupted"?(l=n.onEnd)==null||l.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var bs=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function rl(e){if(!e)return"";let t=Yh(e);return gm(t!==null?t:e)}function Yh(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function gm(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
@@ -16,7 +16,7 @@ ${e.description}`:"");return window.confirm(n)},Xf=e=>{if(e==null)return"";try{l
16
16
  `),t.trim()}var xm=null;var ol=()=>xm?xm():Promise.resolve().then(()=>(bm(),ym));var ty=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function ny(e,t){return ty.some(n=>e[n]!==t[n])}function vm(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
17
17
 
18
18
  _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]}),wm=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Cm=e=>Oo(e)||e===Hr,ta=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new bs(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,l,p,u;if(t.type==="message"){this.upsertMessage(t.message);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(Oo(g.name)||g.name===Hr&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new fs(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,l;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(l=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?l:this.config.agentId;!n||!r||!this.config.clientToken||ol().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return qa((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Uo.isSupported()?new Uo({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(l&&p&&u)return ol().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:v})=>{let x=new f({host:l,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&n?new v(x,n,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):x});if(g&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=jo(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,l;(l=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||l.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(d=this.callbacks).onVoiceStatusChanged)==null||l.call(d,i)}),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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,l,p,u,g,f;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(l=(d=t.runtype)==null?void 0:d.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!ny(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new fs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:l=!1,voiceProcessing:p,rawContent:u}=t,f={id:a!=null?a:n==="user"?Qs():n==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:l,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:l,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=r,x={id:d!=null?d:o==="user"?Qs():o==="assistant"?hs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};n.push(x)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,l={text:o,component:n,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(l),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(t,n){var l,p,u,g,f;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let o=Qs(),s=hs(),a={id:o,role:"user",content:r||$a,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){let x=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!x){let E=vm(v,this.config.errorMessage);if(E){let T={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(T)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,x||(v instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,v):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort();let t=hs();this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let u=vm(l,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,l):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(l))))}}async connectStream(t,n){var o,s,a;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(o=this.abortController)==null||o.abort();let r=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,r=!0);r&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,n==null?void 0:n.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(a=(s=this.callbacks).onError)==null||a.call(s,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,g,f,v;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(x=>x.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,l=d&&typeof d=="object"?d.onDecision:void 0;try{let x;if(l?x=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):x=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),x){let E=null;if(x instanceof Response){if(!x.ok){let T=await x.json().catch(()=>null);throw new Error((g=T==null?void 0:T.error)!=null?g:`Approval request failed: ${x.status}`)}E=x.body}else x instanceof ReadableStream&&(E=x);E?await this.connectStream(E,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(x){let E=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(v=(f=this.callbacks).onError)==null||v.call(f,x instanceof Error?x:new Error(String(x)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,g,f,v,x,E,T,L,k,M,P;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(g=t.toolCall)==null?void 0:g.name;if(!o||!s){(v=(f=this.callbacks).onError)==null||v.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(x=t.toolCall)==null?void 0:x.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let F=typeof((E=R[0])==null?void 0:E.question)=="string"?R[0].question:"";F&&(a={[F]:n})}}this.markAskUserQuestionResolved(t,a),(T=this.abortController)==null||T.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(L=t.toolCall)==null?void 0:L.args,l=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(l.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,F])=>`${R}: ${Array.isArray(F)?F.join(", "):F}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};l.forEach((R,F)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${F}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${F}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((k=R==null?void 0:R.error)!=null?k:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==Hr)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,l,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async g=>{var P,C,R,F,j,W,O;let f=(P=g.toolCall)==null?void 0:P.name,v=(C=g.toolCall)==null?void 0:C.id;if(!f||!v)return null;let x=`${t}:${v}`;if(this.webMcpInflightKeys.has(x)||this.webMcpResolvedKeys.has(x)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(x),r.push(x);let E=this.markWebMcpToolRunning(g),T=(F=(R=g.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?F:f;if(f===Hr)return{dedupeKey:x,resumeKey:T,output:Ki(),toolMessage:g,startedAt:E,completedAt:Date.now()};let L=new AbortController;this.webMcpResolveControllers.add(L),o.push(L);let k=this.client.executeWebMcpToolCall(f,(j=g.toolCall)==null?void 0:j.args,L.signal),M;if(!k)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await k}catch(N){let Z=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return Z||(O=(W=this.callbacks).onError)==null||O.call(W,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(g,ea(Z?"Aborted by cancel()":wm(N)),E),this.webMcpInflightKeys.delete(x),null}return L.signal.aborted?(this.markWebMcpToolComplete(g,ea("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(x),null):{dedupeKey:x,resumeKey:T,output:M,toolMessage:g,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let g={};for(let v of i)g[v.resumeKey]=v.output;let f=await this.client.resumeFlow(t,g,{signal:s.signal});if(!f.ok){let v=await f.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${f.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((l=v.toolMessage.toolCall)==null?void 0:l.name)===Hr?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,ea("Aborted by cancel()"),v.startedAt)}finally{for(let g of r)this.webMcpInflightKeys.delete(g);for(let g of o)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var v,x,E,T,L,k,M,P,C,R,F,j;let n=(v=t.agentMetadata)==null?void 0:v.executionId,r=(x=t.toolCall)==null?void 0:x.name,o=(E=t.toolCall)==null?void 0:E.id;if(!n){(L=(T=this.callbacks).onError)==null||L.call(T,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(W)}catch(O){(M=(k=this.callbacks).onError)==null||M.call(k,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let l=r===Hr,p=(P=t.toolCall)==null?void 0:P.args,u=l?null:this.client.executeWebMcpToolCall(r,p,d),g="execute",f=a;try{let W;if(l?W=Ki():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),d.aborted){this.markWebMcpToolComplete(t,ea("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;g="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,f,l?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(g==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,ea(O||d.aborted?"Aborted by cancel()":wm(W)),a),O||(j=(F=this.callbacks).onError)==null||j.call(F,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=rl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Zs(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=rl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(g=a.agentMetadata)!=null?g:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(f=W.toolType)!=null?f:j.toolType,reason:(v=W.reason)!=null?v:j.reason,parameters:(x=W.parameters)!=null?x:j.parameters}}let i=(E=n.toolCall)==null?void 0:E.name,d=(T=n.agentMetadata)==null?void 0:T.executionId,l=(L=n.toolCall)==null?void 0:L.id;if(i&&Cm(i)&&d&&l&&((k=n.agentMetadata)==null?void 0:k.awaitingLocalTool)===!0){let j=`${d}:${l}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),N=(M=o.toolCall)==null?void 0:M.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===l&&N!==void 0&&Cm(N)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||Z)&&(a.agentMetadata={...(F=a.agentMetadata)!=null?F:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,l;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(l=r.sequence)!=null?l:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};import{Activity as ry,ArrowDown as oy,ArrowUp as sy,ArrowUpRight as ay,Bot as iy,ChevronDown as ly,ChevronUp as cy,ChevronRight as dy,ChevronLeft as py,Check as uy,Clipboard as my,ClipboardCopy as gy,Copy as fy,File as hy,FileCode as yy,FileSpreadsheet as by,FileText as xy,ImagePlus as vy,Loader as wy,LoaderCircle as Cy,Mic as Ay,Paperclip as Sy,RefreshCw as Ty,Search as Ey,Send as My,ShieldAlert as ky,ShieldCheck as Ly,ShieldX as Py,Square as Iy,ThumbsDown as Ry,ThumbsUp as Wy,Upload as Hy,Volume2 as By,X as Dy,User as Ny,Mail as Oy,Phone as Fy,Calendar as _y,Clock as $y,Building as jy,MapPin as Uy,Lock as qy,Key as zy,CreditCard as Vy,AtSign as Ky,Hash as Gy,Globe as Jy,Link as Xy,CircleCheck as Qy,CircleX as Yy,TriangleAlert as Zy,Info as eb,Ban as tb,Shield as nb,ArrowLeft as rb,ArrowRight as ob,ExternalLink as sb,Ellipsis as ab,EllipsisVertical as ib,Menu as lb,House as cb,Plus as db,Minus as pb,Pencil as ub,Trash as mb,Trash2 as gb,Save as fb,Download as hb,Share as yb,Funnel as bb,Settings as xb,RotateCw as vb,Maximize as wb,Minimize as Cb,ShoppingCart as Ab,ShoppingBag as Sb,Package as Tb,Truck as Eb,Tag as Mb,Gift as kb,Receipt as Lb,Wallet as Pb,Store as Ib,DollarSign as Rb,Percent as Wb,Play as Hb,Pause as Bb,VolumeX as Db,Camera as Nb,Image as Ob,Film as Fb,Headphones as _b,MessageCircle as $b,MessageSquare as jb,Bell as Ub,Heart as qb,Star as zb,Eye as Vb,EyeOff as Kb,Bookmark as Gb,CalendarDays as Jb,History as Xb,Timer as Qb,Folder as Yb,FolderOpen as Zb,Files as ex,Sparkles as tx,Zap as nx,Sun as rx,Moon as ox,Flag as sx,Monitor as ax,Smartphone as ix}from"lucide";var lx={activity:ry,"arrow-down":oy,"arrow-up":sy,"arrow-up-right":ay,bot:iy,"chevron-down":ly,"chevron-up":cy,"chevron-right":dy,"chevron-left":py,check:uy,clipboard:my,"clipboard-copy":gy,copy:fy,file:hy,"file-code":yy,"file-spreadsheet":by,"file-text":xy,"image-plus":vy,loader:wy,"loader-circle":Cy,mic:Ay,paperclip:Sy,"refresh-cw":Ty,search:Ey,send:My,"shield-alert":ky,"shield-check":Ly,"shield-x":Py,square:Iy,"thumbs-down":Ry,"thumbs-up":Wy,upload:Hy,"volume-2":By,x:Dy,user:Ny,mail:Oy,phone:Fy,calendar:_y,clock:$y,building:jy,"map-pin":Uy,lock:qy,key:zy,"credit-card":Vy,"at-sign":Ky,hash:Gy,globe:Jy,link:Xy,"circle-check":Qy,"circle-x":Yy,"triangle-alert":Zy,info:eb,ban:tb,shield:nb,"arrow-left":rb,"arrow-right":ob,"external-link":sb,ellipsis:ab,"ellipsis-vertical":ib,menu:lb,house:cb,plus:db,minus:pb,pencil:ub,trash:mb,"trash-2":gb,save:fb,download:hb,share:yb,funnel:bb,settings:xb,"rotate-cw":vb,maximize:wb,minimize:Cb,"shopping-cart":Ab,"shopping-bag":Sb,package:Tb,truck:Eb,tag:Mb,gift:kb,receipt:Lb,wallet:Pb,store:Ib,"dollar-sign":Rb,percent:Wb,play:Hb,pause:Bb,"volume-x":Db,camera:Nb,image:Ob,film:Fb,headphones:_b,"message-circle":$b,"message-square":jb,bell:Ub,heart:qb,star:zb,eye:Vb,"eye-off":Kb,bookmark:Gb,"calendar-days":Jb,history:Xb,timer:Qb,folder:Yb,"folder-open":Zb,files:ex,sparkles:tx,zap:nx,sun:rx,moon:ox,flag:sx,monitor:ax,smartphone:ix},me=(e,t=24,n="currentColor",r=2)=>{let o=lx[e];return o?cx(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function cx(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&d.setAttribute(l,String(p))}),o.appendChild(d)}),o}var Ka={allowedTypes:Gr,maxFileSize:10*1024*1024,maxFiles:4};function dx(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function px(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-code":"file"}var xs=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:Ka.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:Ka.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:Ka.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ka.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,l,"count");continue}let p=pm(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,l,u);continue}try{let u=await dm(l),g=Ua(l)?URL.createObjectURL(l):null,f={id:dx(),file:l,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=Ua(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("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=px(t.file.type),d=me(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let l=y("span");l.textContent=um(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",a.appendChild(l),r.appendChild(a)}let o=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=me("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Am=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function na(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Am(s)&&Am(o)?n[r]=na(s,o):n[r]=o}return n}var sr="min(440px, calc(100vw - 24px))",sl="440px",ux={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:sr,heightOffset:0,autoExpand:!1,callToActionIconHidden:!1,agentIconSize:"40px",headerIconSize:"40px",closeButtonSize:"32px",closeButtonPaddingX:"0px",closeButtonPaddingY:"0px",callToActionIconName:"arrow-up-right",callToActionIconText:"",callToActionIconSize:"32px",callToActionIconPadding:"5px",callToActionIconColor:void 0,callToActionIconBackgroundColor:void 0,closeButtonBackgroundColor:"transparent",clearChat:{backgroundColor:"transparent",borderColor:"transparent",enabled:!0,placement:"inline",iconName:"refresh-cw",size:"32px",showTooltip:!0,tooltipText:"Clear chat",paddingX:"0px",paddingY:"0px"},headerIconHidden:!1,border:void 0,shadow:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)"},Ot={apiUrl:"https://api.runtype.com/api/chat/dispatch",clientToken:void 0,agentId:void 0,target:void 0,theme:void 0,darkTheme:void 0,colorScheme:"light",launcher:ux,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},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 Sm(e,t){if(!(!e&&!t))return e?t?na(e,t):e:t}function al(e){var t,n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P;return e?{...Ot,...e,theme:Sm(Ot.theme,e.theme),darkTheme:Sm(Ot.darkTheme,e.darkTheme),launcher:{...Ot.launcher,...e.launcher,dock:{...(t=Ot.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Ot.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Ot.copy,...e.copy},sendButton:{...Ot.sendButton,...e.sendButton},statusIndicator:{...Ot.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ot.voiceRecognition,...e.voiceRecognition},features:(()=>{var de,ae,se,We,Oe,V,K,ve,J,ce;let C=(de=Ot.features)==null?void 0:de.artifacts,R=(ae=e.features)==null?void 0:ae.artifacts,F=(se=Ot.features)==null?void 0:se.scrollToBottom,j=(We=e.features)==null?void 0:We.scrollToBottom,W=(Oe=Ot.features)==null?void 0:Oe.scrollBehavior,O=(V=e.features)==null?void 0:V.scrollBehavior,N=(K=Ot.features)==null?void 0:K.streamAnimation,Z=(ve=e.features)==null?void 0:ve.streamAnimation,Te=(J=Ot.features)==null?void 0:J.askUserQuestion,pe=(ce=e.features)==null?void 0:ce.askUserQuestion,ee=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},xe=F===void 0&&j===void 0?void 0:{...F,...j},Me=W===void 0&&O===void 0?void 0:{...W,...O},oe=N===void 0&&Z===void 0?void 0:{...N,...Z},be=Te===void 0&&pe===void 0?void 0:{...Te,...pe,styles:{...Te==null?void 0:Te.styles,...pe==null?void 0:pe.styles}};return{...Ot.features,...e.features,...xe!==void 0?{scrollToBottom:xe}:{},...Me!==void 0?{scrollBehavior:Me}:{},...ee!==void 0?{artifacts:ee}:{},...oe!==void 0?{streamAnimation:oe}:{},...be!==void 0?{askUserQuestion:be}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Ot.suggestionChips,suggestionChipsConfig:{...Ot.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ot.layout,...e.layout,header:{...(a=Ot.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Ot.layout)==null?void 0:d.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(u=(p=Ot.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(x=(v=Ot.layout)==null?void 0:v.messages)==null?void 0:x.timestamp,...(T=(E=e.layout)==null?void 0:E.messages)==null?void 0:T.timestamp}},slots:{...(L=Ot.layout)==null?void 0:L.slots,...(k=e.layout)==null?void 0:k.slots}},markdown:{...Ot.markdown,...e.markdown,options:{...(M=Ot.markdown)==null?void 0:M.options,...(P=e.markdown)==null?void 0:P.options}},messageActions:{...Ot.messageActions,...e.messageActions}}:Ot}var Tm={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"}},Em={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"}},Mm={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:sr,maxWidth:sl,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(e,r):r}function il(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function km(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Lm(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Lm(s,o):n[r]=o}return n}function mx(e,t){return t?Lm(e,t):e}function ra(e,t={}){var o,s,a,i,d,l,p,u,g,f,v,x,E;let n={palette:Tm,semantic:Em,components:Mm},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...n.semantic.colors.feedback,...(v=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:v.feedback}},spacing:{...n.semantic.spacing,...(x=e==null?void 0:e.semantic)==null?void 0:x.spacing},typography:{...n.semantic.typography,...(E=e==null?void 0:e.semantic)==null?void 0:E.typography}},components:mx(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let T=km(r);if(!T.valid)throw new Error(`Theme validation failed: ${T.errors.map(L=>L.message).join(", ")}`)}if(t.plugins)for(let T of t.plugins)r=T.transform(r);return r}function ll(e){var x,E,T,L,k,M,P,C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me,oe,be,de,ae,se,We,Oe,V,K,ve,J,ce,Re,ge,Ke,tt,Lt,Ye,_e,G,ze,qe,we,Ae,nt,Ft,ne,$e,hn,Ht,Qt,Dr,br,A,te,Ee,Be,Le,De,Ge,it,Pt,bt,H,Q,Se,lt,Qe,jt,yn,xt,vt,It,wt,dn,_t,Nn,Sn,Tn,xn,En,lr,Ct,xr,vr,Nr,cr,ut,Co,wr,Ao,Rn,Xo,Qr,Or,Yr,Zr,So,To,eo,yt,On,Fn,Mn,At,Xn,Qn,_n,to,Fr,no,$n,Rt,kn,Yn,ro,_r,oo;let t=il(e),n={};for(let[he,Wn]of Object.entries(t)){let Cr=he.replace(/\./g,"-");n[`--persona-${Cr}`]=Wn.value}n["--persona-primary"]=(x=n["--persona-semantic-colors-primary"])!=null?x:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(E=n["--persona-semantic-colors-secondary"])!=null?E:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(T=n["--persona-semantic-colors-accent"])!=null?T:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(L=n["--persona-semantic-colors-surface"])!=null?L:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(k=n["--persona-semantic-colors-background"])!=null?k:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(P=n["--persona-semantic-colors-text"])!=null?P:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(F=n["--persona-semantic-colors-border"])!=null?F:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(N=n["--persona-components-voice-processing-icon"])!=null?N:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(Z=n["--persona-components-voice-speaking-icon"])!=null?Z:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Te=n["--persona-components-approval-requested-background"])!=null?Te:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(ee=n["--persona-components-approval-requested-text"])!=null?ee:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(xe=n["--persona-components-approval-requested-shadow"])!=null?xe:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",n["--persona-approval-approve-bg"]=(Me=n["--persona-components-approval-approve-background"])!=null?Me:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(oe=n["--persona-components-approval-deny-background"])!=null?oe:n["--persona-container"],n["--persona-attachment-image-bg"]=(be=n["--persona-components-attachment-image-background"])!=null?be:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(de=n["--persona-components-attachment-image-border"])!=null?de:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ae=n["--persona-semantic-typography-fontFamily"])!=null?ae:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(se=n["--persona-semantic-typography-fontSize"])!=null?se:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(We=n["--persona-semantic-typography-fontWeight"])!=null?We:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(Oe=n["--persona-semantic-typography-lineHeight"])!=null?Oe:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(V=n["--persona-palette-radius-sm"])!=null?V:"0.125rem",n["--persona-radius-md"]=(K=n["--persona-palette-radius-md"])!=null?K:"0.375rem",n["--persona-radius-lg"]=(ve=n["--persona-palette-radius-lg"])!=null?ve:"0.5rem",n["--persona-radius-xl"]=(J=n["--persona-palette-radius-xl"])!=null?J:"0.75rem",n["--persona-radius-full"]=(ce=n["--persona-palette-radius-full"])!=null?ce:"9999px",n["--persona-launcher-radius"]=(ge=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?ge:"9999px",n["--persona-launcher-bg"]=(Ke=n["--persona-components-launcher-background"])!=null?Ke:n["--persona-primary"],n["--persona-launcher-fg"]=(tt=n["--persona-components-launcher-foreground"])!=null?tt:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Lt=n["--persona-components-launcher-border"])!=null?Lt:n["--persona-border"],n["--persona-button-primary-bg"]=(Ye=n["--persona-components-button-primary-background"])!=null?Ye:n["--persona-primary"],n["--persona-button-primary-fg"]=(_e=n["--persona-components-button-primary-foreground"])!=null?_e:n["--persona-text-inverse"],n["--persona-button-radius"]=(ze=(G=n["--persona-components-button-primary-borderRadius"])!=null?G:n["--persona-palette-radius-full"])!=null?ze:"9999px",n["--persona-panel-radius"]=(we=(qe=n["--persona-components-panel-borderRadius"])!=null?qe:n["--persona-radius-xl"])!=null?we:"0.75rem",n["--persona-panel-border"]=(Ae=n["--persona-components-panel-border"])!=null?Ae:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(Ft=(nt=n["--persona-components-panel-shadow"])!=null?nt:n["--persona-palette-shadows-xl"])!=null?Ft:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(ne=n["--persona-components-launcher-shadow"])!=null?ne:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(hn=($e=n["--persona-components-input-borderRadius"])!=null?$e:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-user-radius"]=(Qt=(Ht=n["--persona-components-message-user-borderRadius"])!=null?Ht:n["--persona-radius-lg"])!=null?Qt:"0.5rem",n["--persona-message-assistant-radius"]=(br=(Dr=n["--persona-components-message-assistant-borderRadius"])!=null?Dr:n["--persona-radius-lg"])!=null?br:"0.5rem",n["--persona-header-bg"]=(A=n["--persona-components-header-background"])!=null?A:n["--persona-surface"],n["--persona-header-border"]=(te=n["--persona-components-header-border"])!=null?te:n["--persona-divider"],n["--persona-header-icon-bg"]=(Ee=n["--persona-components-header-iconBackground"])!=null?Ee:n["--persona-primary"],n["--persona-header-icon-fg"]=(Be=n["--persona-components-header-iconForeground"])!=null?Be:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Le=n["--persona-components-header-titleForeground"])!=null?Le:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(De=n["--persona-components-header-subtitleForeground"])!=null?De:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(Ge=n["--persona-components-header-actionIconForeground"])!=null?Ge:n["--persona-muted"];let r=(it=e.components)==null?void 0:it.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(Pt=e.components)==null?void 0:Pt.introCard;n["--persona-intro-card-bg"]=(bt=n["--persona-components-introCard-background"])!=null?bt:n["--persona-surface"],n["--persona-intro-card-radius"]=(H=n["--persona-components-introCard-borderRadius"])!=null?H:"1rem",n["--persona-intro-card-padding"]=(Q=n["--persona-components-introCard-padding"])!=null?Q:"1.5rem",n["--persona-intro-card-shadow"]=(lt=(Se=o==null?void 0:o.shadow)!=null?Se:n["--persona-components-introCard-shadow"])!=null?lt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Qe=n["--persona-components-input-background"])!=null?Qe:n["--persona-surface"],n["--persona-input-placeholder"]=(jt=n["--persona-components-input-placeholder"])!=null?jt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(yn=n["--persona-components-message-user-background"])!=null?yn:n["--persona-accent"],n["--persona-message-user-text"]=(xt=n["--persona-components-message-user-text"])!=null?xt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(vt=n["--persona-components-message-user-shadow"])!=null?vt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(It=n["--persona-components-message-assistant-background"])!=null?It:n["--persona-surface"],n["--persona-message-assistant-text"]=(wt=n["--persona-components-message-assistant-text"])!=null?wt:n["--persona-text"],n["--persona-message-assistant-border"]=(dn=n["--persona-components-message-assistant-border"])!=null?dn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(_t=n["--persona-components-message-assistant-shadow"])!=null?_t:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(Sn=(Nn=n["--persona-components-scrollToBottom-background"])!=null?Nn:n["--persona-button-primary-bg"])!=null?Sn:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(xn=(Tn=n["--persona-components-scrollToBottom-foreground"])!=null?Tn:n["--persona-button-primary-fg"])!=null?xn:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(En=n["--persona-components-scrollToBottom-border"])!=null?En:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(vr=(xr=(Ct=n["--persona-components-scrollToBottom-borderRadius"])!=null?Ct:n["--persona-button-radius"])!=null?xr:n["--persona-radius-full"])!=null?vr:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Nr=n["--persona-components-scrollToBottom-shadow"])!=null?Nr:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(ut=n["--persona-components-scrollToBottom-padding"])!=null?ut:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(Co=n["--persona-components-scrollToBottom-gap"])!=null?Co:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(Ao=(wr=n["--persona-components-scrollToBottom-fontSize"])!=null?wr:n["--persona-palette-typography-fontSize-sm"])!=null?Ao:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(Rn=n["--persona-components-scrollToBottom-iconSize"])!=null?Rn:"14px",n["--persona-tool-bubble-shadow"]=(Xo=n["--persona-components-toolBubble-shadow"])!=null?Xo:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Qr=n["--persona-components-reasoningBubble-shadow"])!=null?Qr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=(Or=n["--persona-components-composer-shadow"])!=null?Or:"none",n["--persona-md-inline-code-bg"]=(Yr=n["--persona-components-markdown-inlineCode-background"])!=null?Yr:n["--persona-container"],n["--persona-md-inline-code-color"]=(Zr=n["--persona-components-markdown-inlineCode-foreground"])!=null?Zr:n["--persona-text"],n["--persona-md-link-color"]=(To=(So=n["--persona-components-markdown-link-foreground"])!=null?So:n["--persona-accent"])!=null?To:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let l=n["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(n["--persona-md-prose-font-family"]=l),n["--persona-md-code-block-bg"]=(eo=n["--persona-components-markdown-codeBlock-background"])!=null?eo:n["--persona-container"],n["--persona-md-code-block-border-color"]=(yt=n["--persona-components-markdown-codeBlock-borderColor"])!=null?yt:n["--persona-border"],n["--persona-md-code-block-text-color"]=(On=n["--persona-components-markdown-codeBlock-textColor"])!=null?On:"inherit",n["--persona-md-table-header-bg"]=(Fn=n["--persona-components-markdown-table-headerBackground"])!=null?Fn:n["--persona-container"],n["--persona-md-table-border-color"]=(Mn=n["--persona-components-markdown-table-borderColor"])!=null?Mn:n["--persona-border"],n["--persona-md-hr-color"]=(At=n["--persona-components-markdown-hr-color"])!=null?At:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(Xn=n["--persona-components-markdown-blockquote-borderColor"])!=null?Xn:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=(Qn=n["--persona-components-markdown-blockquote-background"])!=null?Qn:"transparent",n["--persona-md-blockquote-text-color"]=(_n=n["--persona-components-markdown-blockquote-textColor"])!=null?_n:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(to=n["--persona-components-collapsibleWidget-container"])!=null?to:n["--persona-surface"],n["--cw-surface"]=(Fr=n["--persona-components-collapsibleWidget-surface"])!=null?Fr:n["--persona-surface"],n["--cw-border"]=(no=n["--persona-components-collapsibleWidget-border"])!=null?no:n["--persona-border"],n["--persona-message-border"]=($n=n["--persona-components-message-border"])!=null?$n:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(n["--persona-label-btn-bg"]=g.background),g.border&&(n["--persona-label-btn-border"]=g.border),g.color&&(n["--persona-label-btn-color"]=g.color),g.padding&&(n["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(n["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(n["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(n["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(n["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(n["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(n["--persona-toggle-group-radius"]=f.borderRadius));let v=p==null?void 0:p.artifact;if(v!=null&&v.toolbar){let he=v.toolbar;he.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,n["--persona-dropdown-bg"]=(Rt=n["--persona-dropdown-bg"])!=null?Rt:he.copyMenuBackground),he.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,n["--persona-dropdown-border"]=(kn=n["--persona-dropdown-border"])!=null?kn:he.copyMenuBorder),he.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,n["--persona-dropdown-shadow"]=(Yn=n["--persona-dropdown-shadow"])!=null?Yn:he.copyMenuShadow),he.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(ro=n["--persona-dropdown-radius"])!=null?ro:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(_r=n["--persona-dropdown-item-hover-bg"])!=null?_r:he.copyMenuItemHoverBackground),he.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(v!=null&&v.tab){let he=v.tab;he.background&&(n["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(n["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(n["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(n["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(n["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(n["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(n["--persona-artifact-tab-list-padding"]=he.listPadding)}if(v!=null&&v.pane){let he=v.pane;if(he.toolbarBackground){let Wn=(oo=vs(e,he.toolbarBackground))!=null?oo:he.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Wn}}return n}var gx={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 fx={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"}}},Pm=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ga=()=>{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"},hx=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ga()},Im=e=>hx(e),yx=e=>ra(e),bx=e=>{var n;let t=ra(void 0,{validate:!1});return ra({...e,palette:{...t.palette,colors:{...fx.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},oa=e=>{let t=Im(e),n=Pm(e==null?void 0:e.theme),r=Pm(e==null?void 0:e.darkTheme);return t==="dark"?bx(na(n!=null?n:{},r!=null?r:{})):yx(n)},xx=e=>ll(e),qo=(e,t)=>{let n=oa(t),r=xx(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},cl=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ga())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ga());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};import{Idiomorph as vx}from"idiomorph";var Ja=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;vx.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",l=(i=s.textContent)!=null?i:"";if(d!==l)return}return!1}}}}})};var Rm=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Xa={index:-1,draft:""};function Wm(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Xa}}}function Hm(e,t){var n,r,o,s,a,i,d,l,p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me,oe,be,de,ae,se;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(v=(f=e.toolCall)==null?void 0:f.status)!=null?v:"",(E=(x=e.toolCall)==null?void 0:x.name)!=null?E:"",(k=(L=(T=e.toolCall)==null?void 0:T.chunks)==null?void 0:L.length)!=null?k:0,(R=(C=(P=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:P[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((F=e.toolCall)==null?void 0:F.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(N=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?N:0,(ee=(pe=(Te=(Z=e.reasoning)==null?void 0:Z.chunks)==null?void 0:Te[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(be=(oe=(Me=(xe=e.reasoning)==null?void 0:xe.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:oe.slice(-32))!=null?be:"",(ae=(de=e.contentParts)==null?void 0:de.length)!=null?ae:0,(se=e.stopReason)!=null?se:"",t].join("\0")}function Bm(){return new Map}function Dm(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Nm(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function Om(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Qa(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Jr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function zo(e,t){return Jr(e)-e.scrollTop<=t}function Ya(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:l=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Za(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function Fm(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function _m(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function $m(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Cn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},An=1e5,ho=An+1;var sa={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},wx=["pre","code","a","script","style"],ei=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:sa.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:sa.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:sa.speed,duration:(o=e==null?void 0:e.duration)!=null?o:sa.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:sa.buffer}},Um=[{name:"typewriter",containerClass:"persona-stream-typewriter",wrap:"char",useCaret:!0},{name:"pop-bubble",bubbleClass:"persona-stream-pop",wrap:"none"},{name:"letter-rise",containerClass:"persona-stream-letter-rise",wrap:"char"},{name:"word-fade",containerClass:"persona-stream-word-fade",wrap:"word"}],aa=new Map;for(let e of Um)aa.set(e.name,e);var Cx=e=>{aa.set(e.name,e)},Ax=e=>{Um.some(t=>t.name===e)||aa.delete(e)},Sx=()=>Array.from(aa.keys()),ia=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=aa.get(e))!=null?r:null},ti=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
- `);return s<0?"":e.slice(0,s)}return e},Tx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Ex=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},dl=/\s/,Mx=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},kx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(dl.test(s[i])){let l=i;for(;l<s.length&&dl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!dl.test(s[p]);)l.appendChild(Tx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Lx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Ex(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},la=(e,t,n,r)=>{var u,g;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:wx).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mx(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?kx:Lx;for(let f of i)p(f,n,l);return o.innerHTML},ni=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ca=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},jm=new WeakMap,Px=(e,t)=>{var s;if(!e.styles)return;let n=jm.get(t);if(n||(n=new Set,jm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},pl=new WeakMap,Ix=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},qm=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{Px(e,t),Ix(e,t)};function ml(e,t=An){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var da=0,yo=null;function gl(e=document){var n;if(da++,da===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;yo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,da=Math.max(0,da-1),da===0&&yo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=yo.originalOverflow,o.style.position=yo.originalPosition,o.style.top=yo.originalTop,o.style.width=yo.originalWidth,s.scrollTo(0,yo.scrollY),yo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},cn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},bo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ar=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:pa.side,width:(o=t==null?void 0:t.width)!=null?o:pa.width,animate:(s=t==null?void 0:t.animate)!=null?s:pa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:pa.maxHeight}};var yr={"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 Rx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ri=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Rx,buttonSize:o,iconSize:s="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),l=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0,u=(M=a.closeButtonIconName)!=null?M:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Tt("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||In.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=me(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,W=j.body;if(!W)return;C=Wr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Wr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(ho),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",W.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",F),v.addEventListener("focus",R),v.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",F),v.removeEventListener("focus",R),v.removeEventListener("blur",F)}}return{button:v,wrapper:d}},Wx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oi=(e,t={})=>{var C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me;let{wrapperClassName:n=Wx,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Z=a.borderColor)!=null?Z:"",f=(Te=a.borderRadius)!=null?Te:"",v=(pe=a.paddingX)!=null?pe:"",x=(ee=a.paddingY)!=null?ee:"",E=(xe=a.tooltipText)!=null?xe:"Clear chat",T=(Me=a.showTooltip)!=null?Me:!0,L=y("div",n),k=!!(u||g),M=Tt("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:l||In.actionIconColor,backgroundColor:p||void 0,border:k?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),P=me(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let oe=null,be=()=>{if(oe)return;let ae=M.ownerDocument,se=ae.body;if(!se)return;oe=Wr(ae,"div","persona-clear-chat-tooltip"),oe.textContent=E;let We=Wr(ae,"div");We.className="persona-clear-chat-tooltip-arrow",oe.appendChild(We);let Oe=M.getBoundingClientRect();oe.style.position="fixed",oe.style.zIndex=String(ho),oe.style.left=`${Oe.left+Oe.width/2}px`,oe.style.top=`${Oe.top-8}px`,oe.style.transform="translate(-50%, -100%)",se.appendChild(oe)},de=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};L.addEventListener("mouseenter",be),L.addEventListener("mouseleave",de),M.addEventListener("focus",be),M.addEventListener("blur",de),L._cleanupTooltip=()=>{de(),L.removeEventListener("mouseenter",be),L.removeEventListener("mouseleave",de),M.removeEventListener("focus",be),M.removeEventListener("blur",de)}}return{button:M,wrapper:L}};var In={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))"},xo=e=>{var P,C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me,oe,be;let{config:t,showClose:n=!0}=e,r=Tt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,l=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let de=parseFloat(s)||24,ae=me(d,de*.6,"currentColor",1);ae?l.replaceChildren(ae):l.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let de=y("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=s,de.style.width=s,l.replaceChildren(de)}else l.textContent=(Z=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Tt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Te=t==null?void 0:t.launcher)==null?void 0:Te.title)!=null?pe:"Chat Assistant",style:{color:In.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(xe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?xe:"Here to help you get answers fast",style:{color:In.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(Me=o.clearChat)!=null?Me:{},v=(oe=f.enabled)!=null?oe:!0,x=(be=f.placement)!=null?be:"inline",E=null,T=null;if(v){let ae=oi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=ae.button,T=ae.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:M}=ri(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:k,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:T}},ws=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Vo(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ho)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let E=me(f.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=me(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function si(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=me(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function ai(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function fl(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=me(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Vo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var zm=e=>{var r;let t=xo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Hx(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let l=Vo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Vm=e=>{var L,k,M,P,C,R,F,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=fl({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=In.titleColor,p=(M=l.querySelector(".persona-combo-btn-label"))!=null?M:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=In.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(p),Hx(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let N=o.onTitleClick;l.addEventListener("click",Z=>{Z.target.closest("button")||N()}),l.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),N())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var N,Z;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Z=O.border)!=null?Z:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||In.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=me(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let E=y("div");E.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},hl={default:zm,minimal:Vm},Km=e=>{var t;return(t=hl[e])!=null?t:hl.default},ua=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Km(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ii=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},li=e=>{var P,C,R,F,j,W,O,N,Z,Te,pe,ee;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(F=t.stopIconName)!=null?F:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(Te=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Te:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(ee=t.size)!=null?ee:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=Tt("button",{className:qs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,T=null;if(n){let xe=parseFloat(u)||24,Me=(f==null?void 0:f.trim())||"currentColor";o?(E=me(o,xe,Me,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=me(s,xe,Me,2)}else x.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:xe=>{if(xe===k)return;k=xe;let Me=xe==="stop"?i:a;if(x.setAttribute("aria-label",Me),L&&(L.textContent=Me),n){if(E&&T){let oe=xe==="stop"?T:E;x.replaceChildren(oe)}}else x.textContent=xe==="stop"?l:d}}},ci=e=>{var L,k,M,P,C,R,F,j,W,O,N,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,l=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(O=t.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,g=y("div","persona-send-button-wrapper"),f=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=me(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let E=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&E){let Te=y("div","persona-send-button-tooltip");Te.textContent=E,g.appendChild(Te)}return{button:f,wrapper:g}},di=e=>{var v,x,E,T,L,k,M,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=t.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(M=t.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=me(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},pi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},ui=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ma=e=>{var v,x,E,T,L,k;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ui(),o=Tt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ii(t);a();let i=li(t),d=ci(t),l=di(t),p=pi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Gm=()=>{let e=Tt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=me("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=me("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Jm=e=>{var v,x,E,T,L,k;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ui();r.style.display="none";let o=pi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ii(t);s.style.maxHeight="100px",a();let i=li(t),d=ci(t),l=di(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Xm=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=cn(e);if(bo(e)){let O=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",N.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:An);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Te=y("div","persona-widget-pill-root");return Te.setAttribute("data-persona-composer-bar",""),Te.dataset.state="collapsed",Te.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",Te.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:An),{wrapper:N,panel:Z,pillRoot:Te}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(N),{wrapper:O,panel:N}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Z,N.style.width="100%",O.appendChild(N),{wrapper:O,panel:N}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&yr[o.position]?yr[o.position]:yr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:An);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Bx=(e,t)=>{var M,P,C,R,F,j,W,O,N;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ri(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=oi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),u=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let E=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=Jm({config:e}),{root:L,textNode:k}=Gm();return n.append(d,o,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:k}},Qm=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(bo(e))return Bx(e,t);let n=Tt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(E=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?ua(e,r,{showClose:t}):xo({config:e,showClose:t}),a=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),l=Tt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:cn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=ma({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let x=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var yl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
19
+ `);return s<0?"":e.slice(0,s)}return e},Tx=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},Ex=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},dl=/\s/,Mx=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},kx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(dl.test(s[i])){let l=i;for(;l<s.length&&dl.test(s[l]);)l+=1;a.appendChild(r.createTextNode(s.slice(i,l))),i=l}else{let l=r.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<s.length&&!dl.test(s[p]);)l.appendChild(Tx(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(l),i=p}o.replaceChild(a,e)},Lx=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?a.appendChild(r.createTextNode(l)):(a.appendChild(Ex(r,l,t,n.value)),n.value+=1));o.replaceChild(a,e)},la=(e,t,n,r)=>{var u,g;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:wx).map(f=>f.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mx(d,s)||i.push(d),d=a.nextNode();let l={value:(g=r==null?void 0:r.startIndex)!=null?g:0},p=t==="char"?kx:Lx;for(let f of i)p(f,n,l);return o.innerHTML},ni=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},ca=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},jm=new WeakMap,Px=(e,t)=>{var s;if(!e.styles)return;let n=jm.get(t);if(n||(n=new Set,jm.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},pl=new WeakMap,Ix=(e,t)=>{if(!e.onAttach)return;let n=pl.get(t);if(n||(n=new Map,pl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},qm=e=>{let t=pl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},ul=(e,t)=>{Px(e,t),Ix(e,t)};function ml(e,t=An){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var da=0,yo=null;function gl(e=document){var n;if(da++,da===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;yo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,da=Math.max(0,da-1),da===0&&yo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=yo.originalOverflow,o.style.position=yo.originalPosition,o.style.top=yo.originalTop,o.style.width=yo.originalWidth,s.scrollTo(0,yo.scrollY),yo=null}}}var pa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},cn=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},bo=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},ar=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:pa.side,width:(o=t==null?void 0:t.width)!=null?o:pa.width,animate:(s=t==null?void 0:t.animate)!=null?s:pa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:pa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:pa.maxHeight}};var yr={"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 Rx="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",ri=(e,t={})=>{var E,T,L,k,M,P;let{showClose:n=!0,wrapperClassName:r=Rx,buttonSize:o,iconSize:s="28px"}=t,a=(E=e==null?void 0:e.launcher)!=null?E:{},i=(T=o!=null?o:a.closeButtonSize)!=null?T:"32px",d=y("div",r),l=(L=a.closeButtonTooltipText)!=null?L:"Close chat",p=(k=a.closeButtonShowTooltip)!=null?k:!0,u=(M=a.closeButtonIconName)!=null?M:"x",g=(P=a.closeButtonIconText)!=null?P:"\xD7",f=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Tt("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||In.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:f?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),x=me(u,s,"currentColor",1);if(x?(x.style.display="block",v.appendChild(x)):v.textContent=g,d.appendChild(v),p&&l){let C=null,R=()=>{if(C)return;let j=v.ownerDocument,W=j.body;if(!W)return;C=Wr(j,"div","persona-clear-chat-tooltip"),C.textContent=l;let O=Wr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(ho),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",W.appendChild(C)},F=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",F),v.addEventListener("focus",R),v.addEventListener("blur",F),d._cleanupTooltip=()=>{F(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",F),v.removeEventListener("focus",R),v.removeEventListener("blur",F)}}return{button:v,wrapper:d}},Wx="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",oi=(e,t={})=>{var C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me;let{wrapperClassName:n=Wx,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(F=r!=null?r:a.size)!=null?F:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",l=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(N=a.borderWidth)!=null?N:"",g=(Z=a.borderColor)!=null?Z:"",f=(Te=a.borderRadius)!=null?Te:"",v=(pe=a.paddingX)!=null?pe:"",x=(ee=a.paddingY)!=null?ee:"",E=(xe=a.tooltipText)!=null?xe:"Clear chat",T=(Me=a.showTooltip)!=null?Me:!0,L=y("div",n),k=!!(u||g),M=Tt("button",{className:qs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!k&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:l||In.actionIconColor,backgroundColor:p||void 0,border:k?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:x||void 0,paddingBottom:x||void 0}}),P=me(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),L.appendChild(M),T&&E){let oe=null,be=()=>{if(oe)return;let ae=M.ownerDocument,se=ae.body;if(!se)return;oe=Wr(ae,"div","persona-clear-chat-tooltip"),oe.textContent=E;let We=Wr(ae,"div");We.className="persona-clear-chat-tooltip-arrow",oe.appendChild(We);let Oe=M.getBoundingClientRect();oe.style.position="fixed",oe.style.zIndex=String(ho),oe.style.left=`${Oe.left+Oe.width/2}px`,oe.style.top=`${Oe.top-8}px`,oe.style.transform="translate(-50%, -100%)",se.appendChild(oe)},de=()=>{oe&&oe.parentNode&&(oe.parentNode.removeChild(oe),oe=null)};L.addEventListener("mouseenter",be),L.addEventListener("mouseleave",de),M.addEventListener("focus",be),M.addEventListener("blur",de),L._cleanupTooltip=()=>{de(),L.removeEventListener("mouseenter",be),L.removeEventListener("mouseleave",de),M.removeEventListener("focus",be),M.removeEventListener("blur",de)}}return{button:M,wrapper:L}};var In={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))"},xo=e=>{var P,C,R,F,j,W,O,N,Z,Te,pe,ee,xe,Me,oe,be;let{config:t,showClose:n=!0}=e,r=Tt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=t==null?void 0:t.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(F=o.headerIconHidden)!=null?F:!1,d=o.headerIconName,l=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let de=parseFloat(s)||24,ae=me(d,de*.6,"currentColor",1);ae?l.replaceChildren(ae):l.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let de=y("img");de.src=t.launcher.iconUrl,de.alt="",de.className="persona-rounded-xl persona-object-cover",de.style.height=s,de.style.width=s,l.replaceChildren(de)}else l.textContent=(Z=(N=t==null?void 0:t.launcher)==null?void 0:N.agentIconText)!=null?Z:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Tt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Te=t==null?void 0:t.launcher)==null?void 0:Te.title)!=null?pe:"Chat Assistant",style:{color:In.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(xe=(ee=t==null?void 0:t.launcher)==null?void 0:ee.subtitle)!=null?xe:"Here to help you get answers fast",style:{color:In.subtitleColor}});p.append(u,g),i?r.append(p):r.append(l,p);let f=(Me=o.clearChat)!=null?Me:{},v=(oe=f.enabled)!=null?oe:!0,x=(be=f.placement)!=null?be:"inline",E=null,T=null;if(v){let ae=oi(t,{wrapperClassName:x==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=ae.button,T=ae.wrapper,x==="top-right"&&(T.style.right="48px"),x==="inline"&&r.appendChild(T)}let L=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&x==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:k,wrapper:M}=ri(t,{showClose:n,wrapperClassName:L});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:l,headerTitle:u,headerSubtitle:g,closeButton:k,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:T}},ws=(e,t,n)=>{var a,i,d,l;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(l=(d=r.clearChat)==null?void 0:d.placement)!=null?l:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Vo(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(ho)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let f of t){if(f.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",f.id),f.destructive&&v.setAttribute("data-destructive",""),f.icon){let E=me(f.icon,16,"currentColor",1.5);E&&v.appendChild(E)}let x=document.createElement("span");x.textContent=f.label,v.appendChild(x),v.addEventListener("click",E=>{E.stopPropagation(),p(),n(f.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let f=r.getBoundingClientRect();a.style.top=`${f.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-f.right}px`,a.style.left="auto"):(a.style.left=`${f.left}px`,a.style.right="auto")}function l(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=v=>{!a.contains(v.target)&&!r.contains(v.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?l():p()}function g(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:l,hide:p,toggle:u,destroy:g}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let l=me(t,r!=null?r:16,"currentColor",o!=null?o:2);if(l&&d.appendChild(l),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function si(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,l="persona-label-btn";r!=="default"&&(l+=" persona-label-btn--"+r),l+=" persona-label-btn--"+o,a&&(l+=" "+a);let p=y("button",l);if(p.type="button",p.setAttribute("aria-label",n),t){let g=me(t,s!=null?s:14,"currentColor",2);g&&p.appendChild(g)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[g,f]of Object.entries(d))p.setAttribute(g,f);return p}function ai(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function l(p){a=p,d()}return{element:s,setSelected:l}}function fl(e){var f,v;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,l=y("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=y("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let u=me(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",l.appendChild(u)),d&&(l.style.borderRadius=(f=d.borderRadius)!=null?f:"10px",l.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var x,E;l.style.backgroundColor=(x=d.background)!=null?x:"",l.style.borderColor=(E=d.border)!=null?E:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let g=Vo({items:r,onSelect:x=>{l.setAttribute("aria-expanded","false"),o(x)},anchor:l,position:s,portal:a});return a||l.appendChild(g.element),l.addEventListener("click",x=>{x.stopPropagation();let E=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",E?"false":"true"),g.toggle()}),l.addEventListener("keydown",x=>{(x.key==="Enter"||x.key===" ")&&(x.preventDefault(),l.click())}),{element:l,setLabel:x=>{p.textContent=x,l.setAttribute("aria-label",x)},open:()=>{l.setAttribute("aria-expanded","true"),g.show()},close:()=>{l.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let x=!g.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",x?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),l.remove()}}}var zm=e=>{var r;let t=xo({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Hx(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("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",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=me(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let l=Vo({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Vm=e=>{var L,k,M,P,C,R,F,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(L=t==null?void 0:t.launcher)!=null?L:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,l,p;if(d)l=fl({label:(k=a.title)!=null?k:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,l.style.color=In.titleColor,p=(M=l.querySelector(".persona-combo-btn-label"))!=null?M:l;else{if(l=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=In.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",l.appendChild(p),Hx(l,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let N=o.onTitleClick;l.addEventListener("click",Z=>{Z.target.closest("button")||N()}),l.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),N())})}let O=o==null?void 0:o.titleRowHover;O&&(l.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",l.style.padding=(F=O.padding)!=null?F:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var N,Z;l.style.backgroundColor=(N=O.background)!=null?N:"",l.style.borderColor=(Z=O.border)!=null?Z:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let u=(j=a.closeButtonSize)!=null?j:"32px",g=y("div",""),f=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=n?"":"none",f.style.color=a.closeButtonColor||In.actionIconColor;let v=(W=a.closeButtonIconName)!=null?W:"x",x=me(v,"28px","currentColor",1);x?f.appendChild(x):f.textContent="\xD7",r&&f.addEventListener("click",r),g.appendChild(f),i.appendChild(g);let E=y("div");E.style.display="none";let T=y("span");return T.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:T,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},hl={default:zm,minimal:Vm},Km=e=>{var t;return(t=hl[e])!=null?t:hl.default},ua=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let l=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),g=y("span"),f=y("button");f.style.display="none";let v=y("div");return v.style.display="none",{header:l,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Km(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ii=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.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",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},li=e=>{var P,C,R,F,j,W,O,N,Z,Te,pe,ee;let t=(P=e==null?void 0:e.sendButton)!=null?P:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(F=t.stopIconName)!=null?F:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(N=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?N:"Send",l=(Te=(Z=e==null?void 0:e.copy)==null?void 0:Z.stopButtonLabel)!=null?Te:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(ee=t.size)!=null?ee:"40px",g=t.backgroundColor,f=t.textColor,v=y("div","persona-send-button-wrapper"),x=Tt("button",{className:qs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!g&&"persona-bg-persona-primary",!n&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:n&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),E=null,T=null;if(n){let xe=parseFloat(u)||24,Me=(f==null?void 0:f.trim())||"currentColor";o?(E=me(o,xe,Me,2),E?x.appendChild(E):x.textContent=r):x.textContent=r,T=me(s,xe,Me,2)}else x.textContent=d;let L=null;p&&a&&(L=y("div","persona-send-button-tooltip"),L.textContent=a,v.appendChild(L)),x.setAttribute("aria-label",a),v.appendChild(x);let k="send";return{button:x,wrapper:v,setMode:xe=>{if(xe===k)return;k=xe;let Me=xe==="stop"?i:a;if(x.setAttribute("aria-label",Me),L&&(L.textContent=Me),n){if(E&&T){let oe=xe==="stop"?T:E;x.replaceChildren(oe)}}else x.textContent=xe==="stop"?l:d}}},ci=e=>{var L,k,M,P,C,R,F,j,W,O,N,Z;let t=(L=e==null?void 0:e.voiceRecognition)!=null?L:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((k=t.provider)==null?void 0:k.type)==="runtype";if(!(r||o))return null;let a=(P=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,l=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(F=e==null?void 0:e.sendButton)==null?void 0:F.backgroundColor,u=(O=t.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,g=y("div","persona-send-button-wrapper"),f=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),x=me(i,l,u||"currentColor",1.5);x?f.appendChild(x):f.textContent="\u{1F3A4}",g.appendChild(f);let E=(N=t.tooltipText)!=null?N:"Start voice recognition";if(((Z=t.showTooltip)!=null?Z:!1)&&E){let Te=y("div","persona-send-button-tooltip");Te.textContent=E,g.appendChild(Te)}return{button:f,wrapper:g}},di=e=>{var v,x,E,T,L,k,M,P;let t=(v=e==null?void 0:e.attachments)!=null?v:{};if(t.enabled!==!0)return null;let n=(E=(x=e==null?void 0:e.sendButton)==null?void 0:x.size)!=null?E:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((T=t.allowedTypes)!=null?T:Gr).join(","),o.multiple=((L=t.maxFiles)!=null?L:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(k=t.buttonIconName)!=null?k:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),l=y("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(M=t.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=me(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),l.appendChild(p);let g=(P=t.buttonTooltipText)!=null?P:"Attach file",f=y("div","persona-send-button-tooltip");return f.textContent=g,l.appendChild(f),{button:p,wrapper:l,input:o,previewsContainer:r}},pi=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let l=y("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=s,l.style.color="inherit",l.style.textDecoration="none",r.appendChild(l)}else r.textContent=s;return r},ui=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var ma=e=>{var v,x,E,T,L,k;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ui(),o=Tt("form",{className:"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",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ii(t);a();let i=li(t),d=ci(t),l=di(t),p=pi(t);l&&(l.previewsContainer.style.gap="8px",o.append(l.previewsContainer,l.input)),o.append(s);let u=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&g.append(l.wrapper),d&&f.append(d.wrapper),f.append(i.wrapper),u.append(g,f),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:p,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Gm=()=>{let e=Tt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=me("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=me("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},Jm=e=>{var v,x,E,T,L,k;let{config:t}=e,n=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ui();r.style.display="none";let o=pi(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=ii(t);s.style.maxHeight="100px",a();let i=li(t),d=ci(t),l=di(t);l&&l.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&u.append(l.wrapper);let g=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&g.append(d.wrapper),g.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(l==null?void 0:l.button)&&M.target!==(l==null?void 0:l.wrapper)&&s.focus()}),l&&p.append(l.input),p.append(u,s,g),l&&n.append(l.previewsContainer),n.append(p,r,o);let f=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(x=d==null?void 0:d.wrapper)!=null?x:null,statusText:o,attachmentButton:(E=l==null?void 0:l.button)!=null?E:null,attachmentButtonWrapper:(T=l==null?void 0:l.wrapper)!=null?T:null,attachmentInput:(L=l==null?void 0:l.input)!=null?L:null,attachmentPreviewsContainer:(k=l==null?void 0:l.previewsContainer)!=null?k:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Xm=e=>{var p,u,g,f,v,x,E,T,L,k,M,P,C,R,F,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=cn(e);if(bo(e)){let O=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},N=y("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=O.expandedSize)!=null?v:"anchored",N.style.zIndex=String((E=(x=e==null?void 0:e.launcher)==null?void 0:x.zIndex)!=null?E:An);let Z=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",N.appendChild(Z);let Te=y("div","persona-widget-pill-root");return Te.setAttribute("data-persona-composer-bar",""),Te.dataset.state="collapsed",Te.dataset.expandedSize=(T=O.expandedSize)!=null?T:"anchored",Te.style.zIndex=String((k=(L=e==null?void 0:e.launcher)==null?void 0:L.zIndex)!=null?k:An),{wrapper:N,panel:Z,pillRoot:Te}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(N),{wrapper:O,panel:N}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Z,N.style.width="100%",O.appendChild(N),{wrapper:O,panel:N}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&yr[o.position]?yr[o.position]:yr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((F=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?F:An);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,l=d!=null?d:sr;return i.style.width=l,i.style.maxWidth=l,a.appendChild(i),{wrapper:a,panel:i}},Bx=(e,t)=>{var M,P,C,R,F,j,W,O,N;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=ri(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=oi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});l.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(F=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?F:"Hello \u{1F44B}"}),u=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=y("div","persona-flex persona-flex-col persona-gap-3"),v=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;v&&(f.style.maxWidth=v,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((N=e==null?void 0:e.copy)==null?void 0:N.showWelcomeCard)!==!1||(g.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(g,f);let E=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),T=Jm({config:e}),{root:L,textNode:k}=Gm();return n.append(d,o,l,E),i&&n.appendChild(i),{container:n,body:l,messagesWrapper:f,composerOverlay:E,suggestions:T.suggestions,textarea:T.textarea,sendButton:T.sendButton,sendButtonWrapper:T.sendButtonWrapper,micButton:T.micButton,micButtonWrapper:T.micButtonWrapper,composerForm:T.composerForm,statusText:T.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:T.footer,attachmentButton:T.attachmentButton,attachmentButtonWrapper:T.attachmentButtonWrapper,attachmentInput:T.attachmentInput,attachmentPreviewsContainer:T.attachmentPreviewsContainer,actionsRow:T.actionsRow,leftActions:T.leftActions,rightActions:T.rightActions,setSendButtonMode:T.setSendButtonMode,peekBanner:L,peekTextNode:k}},Qm=(e,t=!0)=>{var E,T,L,k,M,P,C,R,F;if(bo(e))return Bx(e,t);let n=Tt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(E=e==null?void 0:e.layout)==null?void 0:E.header,o=((T=e==null?void 0:e.layout)==null?void 0:T.showHeader)!==!1,s=r?ua(e,r,{showClose:t}):xo({config:e,showClose:t}),a=Tt("div",{className:"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",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(k=(L=e==null?void 0:e.copy)==null?void 0:L.welcomeTitle)!=null?k:"Hello \u{1F44B}"}),d=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),l=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:cn(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(l.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(l,p);let f=ma({config:e}),v=((F=e==null?void 0:e.layout)==null?void 0:F.showFooter)!==!1;o?ws(n,s,e):(s.header.style.display="none",ws(n,s,e)),n.append(a);let x=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return v||(f.footer.style.display="none"),n.append(f.footer),n.append(x),{container:n,body:a,messagesWrapper:p,composerOverlay:x,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var yl=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
20
20
  <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>
21
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
22
22
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -24,7 +24,7 @@ _Details: ${n.message}_`:r}var ea=e=>({isError:!0,content:[{type:"text",text:e}]
24
24
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
25
25
  </span>
26
26
  <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>
27
- `,n.addEventListener("click",t);let r=s=>{var k,M,P,C,R,F,j,W,O,N,Z,Te,pe;let a=(k=s.launcher)!=null?k:{},i=cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(M=a.title)!=null?M:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";l.textContent=ee,l.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,u.innerHTML="",a.agentIconName){let xe=parseFloat(ee)||24,Me=me(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(u.appendChild(Me),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(j=a.agentIconSize)!=null?j:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(W=a.callToActionIconSize)!=null?W:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Me=parseFloat(ee)||24,oe=Math.max(Me-xe,8),be=me(a.callToActionIconName,oe,"currentColor",2);be?f.appendChild(be):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&yr[a.position]?yr[a.position]:yr["bottom-right"],x="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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:An));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Te=a.border)!=null?Te:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Ym=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Xm(e),s=Qm(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},l={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},bl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>yl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=yl(e,n);return{instance:o,element:o.element}};var Dx=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Nx=(e,t)=>{if(!e)return null;let n=Dx(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Ox=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Fx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},xl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},vl=320,eg=320,_x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),qx=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${vl}px`,l.style.maxHeight=`${eg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),Fx(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},zx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!xl(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${vl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Vx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!xl(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${vl}px`,o.style.maxHeight=`${eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Kx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!xl(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-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="0ms";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="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},tg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Cs};if(t){let o=t(r);if(o!==null)return o}return Cs()},Gx=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Zm=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Jx=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},ng=(e,t,n)=>{var v,x,E,T,L,k,M;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(k=t.align)!=null?k:"right",l=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(P,C,R)=>{let F=Gt({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},ga=(e,t,n,r,o,s)=>{var de,ae,se,We,Oe,V,K,ve,J,ce,Re,ge,Ke,tt,Lt,Ye,_e;let a=n!=null?n:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,l=a.timestamp,p=(ae=d==null?void 0:d.show)!=null?ae:!1,u=(se=l==null?void 0:l.show)!=null?se:!1,g=(We=d==null?void 0:d.position)!=null?We:"left",f=(Oe=l==null?void 0:l.position)!=null?Oe:"below",v=Jx(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=_x(e),T=(K=(V=e.content)==null?void 0:V.trim())!=null?K:"",k=E.length>0&&T===$a,M=ei((J=(ve=s==null?void 0:s.widgetConfig)==null?void 0:ve.features)==null?void 0:J.streamAnimation),P=(ge=(Re=(ce=s==null?void 0:s.widgetConfig)==null?void 0:ce.features)==null?void 0:Re.streamAnimation)==null?void 0:ge.plugins,C=e.role==="assistant"&&M.type!=="none"?ia(M.type,P):null,R=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,F=e.role==="assistant"&&C!==null&&(!!e.streaming||R);F&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let W=F?ti((tt=e.content)!=null?tt:"",M.buffer,C,e,!!e.streaming):(Lt=e.content)!=null?Lt:"",O=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=la(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=la(O,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(k?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",j.appendChild(Z)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&T){let G=ni(),ze=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=ze[ze.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(G,qe.nextSibling);else{let we=j.lastElementChild;we?we.appendChild(G):j.appendChild(G)}}if(u&&f==="inline"&&e.createdAt){let G=Zm(e,l,"span");G.classList.add("persona-timestamp-inline");let ze=j.lastElementChild;ze?ze.appendChild(G):j.appendChild(G)}if(E.length>0){let G=qx(E,!k&&!!T,()=>{k&&Z&&(Z.style.display="")});G?x.appendChild(G):k&&Z&&(Z.style.display="")}let Te=$x(e);if(Te.length>0){let G=zx(Te);G&&x.appendChild(G)}let pe=jx(e);if(pe.length>0){let G=Vx(pe);G&&x.appendChild(G)}let ee=Ux(e);if(ee.length>0){let G=Kx(ee);G&&x.appendChild(G)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let G=Zm(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let xe=e.role==="assistant"?Nx(e.stopReason,(_e=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:_e.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(W&&W.trim()),ze=M.placeholder==="skeleton",qe=ze&&M.buffer==="line"&&G;if(G)qe&&x.appendChild(ca());else if(ze)x.appendChild(ca());else{let we=tg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&x.appendChild(we)}}if(xe&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(Ox(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=ng(e,r,o);x.appendChild(G)}if(!p||e.role==="system")return x;let oe=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),be=Gx(d,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(x,be):oe.append(be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),oe},Xx=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ga(e,t,n,r,o,s)};var As=new Set,Qx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Yx=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
27
+ `,n.addEventListener("click",t);let r=s=>{var k,M,P,C,R,F,j,W,O,N,Z,Te,pe;let a=(k=s.launcher)!=null?k:{},i=cn(s),d=n.querySelector("[data-role='launcher-title']");if(d){let ee=(M=a.title)!=null?M:"Chat Assistant";d.textContent=ee,d.setAttribute("title",ee)}let l=n.querySelector("[data-role='launcher-subtitle']");if(l){let ee=(P=a.subtitle)!=null?P:"Here to help you get answers fast";l.textContent=ee,l.setAttribute("title",ee)}let p=n.querySelector(".persona-flex-col");p&&(a.textHidden||i?p.style.display="none":p.style.display="");let u=n.querySelector("[data-role='launcher-icon']");if(u)if(a.agentIconHidden)u.style.display="none";else{let ee=(C=a.agentIconSize)!=null?C:"40px";if(u.style.height=ee,u.style.width=ee,a.agentIconBackgroundColor?(u.style.backgroundColor=a.agentIconBackgroundColor,u.classList.remove("persona-bg-persona-primary")):(u.style.backgroundColor="",u.classList.add("persona-bg-persona-primary")),u.innerHTML="",a.agentIconName){let xe=parseFloat(ee)||24,Me=me(a.agentIconName,xe*.6,"var(--persona-text-inverse, #ffffff)",2);Me?(u.appendChild(Me),u.style.display=""):(u.textContent=(R=a.agentIconText)!=null?R:"\u{1F4AC}",u.style.display="")}else a.iconUrl?u.style.display="none":(u.textContent=(F=a.agentIconText)!=null?F:"\u{1F4AC}",u.style.display="")}let g=n.querySelector("[data-role='launcher-image']");if(g){let ee=(j=a.agentIconSize)!=null?j:"40px";g.style.height=ee,g.style.width=ee,a.iconUrl&&!a.agentIconName&&!a.agentIconHidden?(g.src=a.iconUrl,g.style.display="block"):g.style.display="none"}let f=n.querySelector("[data-role='launcher-call-to-action-icon']");if(f){let ee=(W=a.callToActionIconSize)!=null?W:"32px";f.style.height=ee,f.style.width=ee,a.callToActionIconBackgroundColor?(f.style.backgroundColor=a.callToActionIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),a.callToActionIconColor?(f.style.color=a.callToActionIconColor,f.classList.remove("persona-text-persona-call-to-action")):(f.style.color="",f.classList.add("persona-text-persona-call-to-action"));let xe=0;if(a.callToActionIconPadding?(f.style.boxSizing="border-box",f.style.padding=a.callToActionIconPadding,xe=(parseFloat(a.callToActionIconPadding)||0)*2):(f.style.boxSizing="",f.style.padding=""),a.callToActionIconHidden)f.style.display="none";else if(f.style.display=i?"none":"",f.innerHTML="",a.callToActionIconName){let Me=parseFloat(ee)||24,oe=Math.max(Me-xe,8),be=me(a.callToActionIconName,oe,"currentColor",2);be?f.appendChild(be):f.textContent=(O=a.callToActionIconText)!=null?O:"\u2197"}else f.textContent=(N=a.callToActionIconText)!=null?N:"\u2197"}let v=a.position&&yr[a.position]?yr[a.position]:yr["bottom-right"],x="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",E="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";n.className=i?E:`${x} ${v}`,i||(n.style.zIndex=String((Z=a.zIndex)!=null?Z:An));let T="1px solid var(--persona-border, #e5e7eb)",L="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";n.style.border=(Te=a.border)!=null?Te:T,n.style.boxShadow=a.shadow!==void 0?a.shadow.trim()===""?"none":a.shadow:L,i?(n.style.width="0",n.style.minWidth="0",n.style.maxWidth="0",n.style.padding="0",n.style.overflow="hidden",n.style.border="none",n.style.boxShadow="none"):(n.style.width="",n.style.minWidth="",n.style.maxWidth=(pe=a.collapsedMaxWidth)!=null?pe:"",n.style.justifyContent="",n.style.padding="",n.style.overflow="")},o=()=>{n.removeEventListener("click",t),n.remove()};return e&&r(e),{element:n,update:r,destroy:o}};var Ym=({config:e,showClose:t})=>{let{wrapper:n,panel:r,pillRoot:o}=Xm(e),s=Qm(e,t),a={wrapper:n,panel:r,pillRoot:o},i={container:s.container,body:s.body,messagesWrapper:s.messagesWrapper,composerOverlay:s.composerOverlay,introTitle:s.introTitle,introSubtitle:s.introSubtitle},d={element:s.header,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper},l={footer:s.footer,form:s.composerForm,textarea:s.textarea,sendButton:s.sendButton,sendButtonWrapper:s.sendButtonWrapper,micButton:s.micButton,micButtonWrapper:s.micButtonWrapper,statusText:s.statusText,suggestions:s.suggestions,attachmentButton:s.attachmentButton,attachmentButtonWrapper:s.attachmentButtonWrapper,attachmentInput:s.attachmentInput,attachmentPreviewsContainer:s.attachmentPreviewsContainer,actionsRow:s.actionsRow,leftActions:s.leftActions,rightActions:s.rightActions,setSendButtonMode:s.setSendButtonMode,peekBanner:s.peekBanner,peekTextNode:s.peekTextNode};return{shell:a,panelElements:s,transcript:i,header:d,composer:l,replaceHeader:g=>(d.element.replaceWith(g.header),d.element=g.header,d.iconHolder=g.iconHolder,d.headerTitle=g.headerTitle,d.headerSubtitle=g.headerSubtitle,d.closeButton=g.closeButton,d.closeButtonWrapper=g.closeButtonWrapper,d.clearChatButton=g.clearChatButton,d.clearChatButtonWrapper=g.clearChatButtonWrapper,g),replaceComposer:g=>{l.footer.replaceWith(g),l.footer=g}}},bl=({config:e,plugins:t,onToggle:n})=>{let r=t.find(s=>s.renderLauncher);if(r!=null&&r.renderLauncher){let s=r.renderLauncher({config:e,defaultRenderer:()=>yl(e,n).element,onToggle:n});if(s)return{instance:null,element:s}}let o=yl(e,n);return{instance:o,element:o.element}};var Dx=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Nx=(e,t)=>{if(!e)return null;let n=Dx(e);if(n===null)return null;let r=t==null?void 0:t[e],o=r!==void 0?r:n;return o||null},Ox=(e,t)=>{let n=y("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return n.setAttribute("data-stop-reason",e),n.setAttribute("role","note"),n.style.opacity="0.75",n.textContent=t,n},Fx=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},xl=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},vl=320,eg=320,_x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),$x=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),jx=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),Ux=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),qx=(e,t,n)=>{if(e.length===0)return null;try{let r=y("div","persona-flex persona-flex-col persona-gap-2");r.setAttribute("data-message-attachments","images"),t&&(r.style.marginBottom="8px");let o=0,s=!1,a=()=>{s||(s=!0,r.remove(),n==null||n())};return e.forEach((i,d)=>{var u;let l=y("img");l.alt=((u=i.alt)==null?void 0:u.trim())||`Attached image ${d+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${vl}px`,l.style.maxHeight=`${eg}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;o+=1,l.addEventListener("error",()=>{p||(p=!0,o=Math.max(0,o-1),l.remove(),o===0&&a())}),l.addEventListener("load",()=>{p=!0}),Fx(i.image)?(l.src=i.image,r.appendChild(l)):(p=!0,o=Math.max(0,o-1),l.remove())}),o===0?(a(),null):r}catch{return n==null||n(),null}},zx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let n=0;return e.forEach(r=>{if(!xl(r.audio))return;let o=y("audio");o.controls=!0,o.preload="metadata",o.src=r.audio,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${vl}px`,t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Vx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let n=0;return e.forEach(r=>{if(!xl(r.video))return;let o=y("video");o.controls=!0,o.preload="metadata",o.src=r.video,o.style.display="block",o.style.width="100%",o.style.maxWidth=`${vl}px`,o.style.maxHeight=`${eg}px`,o.style.borderRadius="10px",o.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Kx=e=>{if(e.length===0)return null;try{let t=y("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let n=0;return e.forEach(r=>{if(!xl(r.data))return;let o=y("a");o.href=r.data,o.download=r.filename,o.target="_blank",o.rel="noopener noreferrer",o.textContent=r.filename,o.className="persona-message-file-attachment",o.style.display="inline-flex",o.style.alignItems="center",o.style.gap="6px",o.style.padding="6px 10px",o.style.borderRadius="8px",o.style.fontSize="0.875rem",o.style.textDecoration="underline",o.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",o.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",o.style.color="inherit",t.appendChild(o),n+=1}),n===0?(t.remove(),null):t}catch{return null}},Cs=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-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="0ms";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="250ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="500ms";let o=document.createElement("span");return o.className="persona-sr-only",o.textContent="Loading",e.appendChild(t),e.appendChild(n),e.appendChild(r),e.appendChild(o),e},tg=(e,t,n)=>{let r={config:n!=null?n:{},streaming:!0,location:e,defaultRenderer:Cs};if(t){let o=t(r);if(o!==null)return o}return Cs()},Gx=(e,t)=>{let n=y("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),r=t==="user"?e.userAvatar:e.assistantAvatar;if(r)if(r.startsWith("http")||r.startsWith("/")||r.startsWith("data:")){let o=y("img");o.src=r,o.alt=t==="user"?"User":"Assistant",o.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",n.appendChild(o)}else n.textContent=r,n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else n.textContent=t==="user"?"U":"A",n.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return n},Zm=(e,t,n="div")=>{let r=y(n,"persona-text-xs persona-text-persona-muted"),o=new Date(e.createdAt);return t.format?r.textContent=t.format(o):r.textContent=o.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),r},Jx=(e,t="bubble")=>{let n=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):n.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":n.push("persona-text-sm","persona-leading-relaxed"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:n.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?n.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):n.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return n},ng=(e,t,n)=>{var v,x,E,T,L,k,M;let r=(v=t.showCopy)!=null?v:!0,o=(x=t.showUpvote)!=null?x:!0,s=(E=t.showDownvote)!=null?E:!0,a=(T=t.showReadAloud)!=null?T:!1;if(!r&&!o&&!s&&!a){let P=y("div");return P.style.display="none",P.id=`actions-${e.id}`,P.setAttribute("data-actions-for",e.id),P}let i=(L=t.visibility)!=null?L:"hover",d=(k=t.align)!=null?k:"right",l=(M=t.layout)!=null?M:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[d],u={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],g=y("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${u} ${i==="hover"?"persona-message-actions-hover":""}`);g.id=`actions-${e.id}`,g.setAttribute("data-actions-for",e.id);let f=(P,C,R)=>{let F=Gt({icon:P,label:C,size:14,className:"persona-message-action-btn"});return F.setAttribute("data-action",R),F};return r&&g.appendChild(f("copy","Copy message","copy")),a&&g.appendChild(f("volume-2","Read aloud","read-aloud")),o&&g.appendChild(f("thumbs-up","Upvote","upvote")),s&&g.appendChild(f("thumbs-down","Downvote","downvote")),g},ga=(e,t,n,r,o,s)=>{var de,ae,se,We,Oe,V,K,ve,J,ce,Re,ge,Ke,tt,Lt,Ye,_e;let a=n!=null?n:{},i=(de=a.layout)!=null?de:"bubble",d=a.avatar,l=a.timestamp,p=(ae=d==null?void 0:d.show)!=null?ae:!1,u=(se=l==null?void 0:l.show)!=null?se:!1,g=(We=d==null?void 0:d.position)!=null?We:"left",f=(Oe=l==null?void 0:l.position)!=null?Oe:"below",v=Jx(e.role,i),x=y("div",v.join(" "));x.id=`bubble-${e.id}`,x.setAttribute("data-message-id",e.id),x.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(x.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",x.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(x.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",x.style.color="var(--persona-message-assistant-text, var(--persona-text))");let E=_x(e),T=(K=(V=e.content)==null?void 0:V.trim())!=null?K:"",k=E.length>0&&T===$a,M=ei((J=(ve=s==null?void 0:s.widgetConfig)==null?void 0:ve.features)==null?void 0:J.streamAnimation),P=(ge=(Re=(ce=s==null?void 0:s.widgetConfig)==null?void 0:ce.features)==null?void 0:Re.streamAnimation)==null?void 0:ge.plugins,C=e.role==="assistant"&&M.type!=="none"?ia(M.type,P):null,R=e.role==="assistant"&&((Ke=C==null?void 0:C.isAnimating)==null?void 0:Ke.call(C,e))===!0,F=e.role==="assistant"&&C!==null&&(!!e.streaming||R);F&&(C!=null&&C.bubbleClass)&&x.classList.add(C.bubbleClass);let j=document.createElement("div");j.classList.add("persona-message-content"),e.streaming&&j.classList.add("persona-content-streaming"),F&&C&&(C.containerClass&&j.classList.add(C.containerClass),j.style.setProperty("--persona-stream-step",`${M.speed}ms`),j.style.setProperty("--persona-stream-duration",`${M.duration}ms`));let W=F?ti((tt=e.content)!=null?tt:"",M.buffer,C,e,!!e.streaming):(Lt=e.content)!=null?Lt:"",O=t({text:W,message:e,streaming:!!e.streaming,raw:e.rawContent}),N=O;F&&(C==null?void 0:C.wrap)==="char"?N=la(O,"char",e.id,{skipTags:C.skipTags}):F&&(C==null?void 0:C.wrap)==="word"&&(N=la(O,"word",e.id,{skipTags:C.skipTags}));let Z=null;if(k?(Z=document.createElement("div"),Z.innerHTML=N,Z.style.display="none",j.appendChild(Z)):j.innerHTML=N,F&&(C!=null&&C.useCaret)&&!k&&T){let G=ni(),ze=j.querySelectorAll(".persona-stream-char, .persona-stream-word"),qe=ze[ze.length-1];if(qe!=null&&qe.parentNode)qe.parentNode.insertBefore(G,qe.nextSibling);else{let we=j.lastElementChild;we?we.appendChild(G):j.appendChild(G)}}if(u&&f==="inline"&&e.createdAt){let G=Zm(e,l,"span");G.classList.add("persona-timestamp-inline");let ze=j.lastElementChild;ze?ze.appendChild(G):j.appendChild(G)}if(E.length>0){let G=qx(E,!k&&!!T,()=>{k&&Z&&(Z.style.display="")});G?x.appendChild(G):k&&Z&&(Z.style.display="")}let Te=$x(e);if(Te.length>0){let G=zx(Te);G&&x.appendChild(G)}let pe=jx(e);if(pe.length>0){let G=Vx(pe);G&&x.appendChild(G)}let ee=Ux(e);if(ee.length>0){let G=Kx(ee);G&&x.appendChild(G)}if(x.appendChild(j),u&&f==="below"&&e.createdAt){let G=Zm(e,l);G.classList.add("persona-mt-1"),x.appendChild(G)}let xe=e.role==="assistant"?Nx(e.stopReason,(_e=(Ye=s==null?void 0:s.widgetConfig)==null?void 0:Ye.copy)==null?void 0:_e.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let G=!!(W&&W.trim()),ze=M.placeholder==="skeleton",qe=ze&&M.buffer==="line"&&G;if(G)qe&&x.appendChild(ca());else if(ze)x.appendChild(ca());else{let we=tg("inline",s==null?void 0:s.loadingIndicatorRenderer,s==null?void 0:s.widgetConfig);we&&x.appendChild(we)}}if(xe&&e.stopReason&&!e.streaming&&(T||(j.style.display="none"),x.appendChild(Ox(e.stopReason,xe))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(r==null?void 0:r.enabled)!==!1&&r){let G=ng(e,r,o);x.appendChild(G)}if(!p||e.role==="system")return x;let oe=y("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),be=Gx(d,e.role);return g==="right"||g==="left"&&e.role==="user"?oe.append(x,be):oe.append(be,x),x.classList.remove("persona-max-w-[85%]"),x.classList.add("persona-max-w-[calc(85%-2.5rem)]"),oe},Xx=(e,t,n,r,o,s)=>{let a=n!=null?n:{};return e.role==="user"&&a.renderUserMessage?a.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&a.renderAssistantMessage?a.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):ga(e,t,n,r,o,s)};var As=new Set,Qx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),Yx=(e,t)=>{var r,o;let n=(o=(r=e.reasoning)==null?void 0:r.chunks.join("").trim())!=null?o:"";return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
28
28
  `):""},rg=(e,t)=>{let n=As.has(e),r=t.querySelector('button[data-expand-header="true"]'),o=t.querySelector(".persona-border-t"),s=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!r||!o)return;r.setAttribute("aria-expanded",n?"true":"false");let a=r.querySelector(".persona-ml-auto"),i=a==null?void 0:a.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=me(n?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=n?"Hide":"Show"}o.style.display=n?"":"none",s&&(s.style.display=n?"none":s.textContent||s.childNodes.length?"":"none")},wl=(e,t)=>{var pe,ee,xe,Me,oe,be,de,ae,se,We,Oe;let n=e.reasoning,r=y("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),!n)return r;let o=(ee=(pe=t==null?void 0:t.features)==null?void 0:pe.reasoningDisplay)!=null?ee:{},s=o.expandable!==!1,a=s&&As.has(e.id),i=n.status!=="complete",d=Yx(e,(xe=o.previewMaxLines)!=null?xe:3),l=y("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",s&&(l.setAttribute("aria-expanded",a?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=y("div","persona-flex persona-flex-col persona-text-left"),u=y("span","persona-text-xs persona-text-persona-primary"),g="Thinking...",f=(Me=t==null?void 0:t.reasoning)!=null?Me:{},v=String((oe=n.startedAt)!=null?oe:Date.now()),x=()=>{let V=y("span","");return V.setAttribute("data-tool-elapsed",v),V.textContent=Oa(n),V},E=(be=f.renderCollapsedSummary)==null?void 0:be.call(f,{message:e,reasoning:n,defaultSummary:g,previewText:d,isActive:i,config:t!=null?t:{},elapsed:Oa(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(u.textContent=E,p.appendChild(u)):E instanceof HTMLElement?p.appendChild(E):(u.textContent=g,p.appendChild(u));let T=y("span","persona-text-xs persona-text-persona-primary");T.textContent=sm(n),p.appendChild(T);let L=(de=o.loadingAnimation)!=null?de:"none",k=f.activeTextTemplate,M=f.completeTextTemplate,P=i?k:M,C=E instanceof HTMLElement,R=(V,K,ve)=>{let J=ve;for(let ce of K){let Re=y("span","persona-tool-char");Re.style.setProperty("--char-index",String(J)),Re.textContent=ce===" "?"\xA0":ce,V.appendChild(Re),J++}return J},F=(V,K)=>{u.textContent="";let ve=Fa(V,""),J=0;for(let ce of ve){let Re=ce.styles.length>0?(()=>{let ge=y("span",ce.styles.map(Ke=>`persona-tool-text-${Ke}`).join(" "));return u.appendChild(ge),ge})():u;if(ce.isDuration&&i)Re.appendChild(x());else{let ge=ce.isDuration?Oa(n):ce.text;K?J=R(Re,ge,J):Re.appendChild(document.createTextNode(ge))}}};if(!C&&P)if(T.style.display="none",u.style.display="",i&&L!=="none"){let V=(ae=f.loadingAnimationDuration)!=null?ae:2e3;u.setAttribute("data-preserve-animation","true"),L==="pulse"?(u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),F(P,!1)):(u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor)),F(P,!0))}else F(P,!1);else if(!C&&i&&L!=="none"){u.style.display="";let V=(se=f.loadingAnimationDuration)!=null?se:2e3;if(u.setAttribute("data-preserve-animation","true"),L==="pulse")u.classList.add("persona-tool-loading-pulse"),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`);else{u.classList.add(`persona-tool-loading-${L}`),u.style.setProperty("--persona-tool-anim-duration",`${V}ms`),L==="shimmer-color"&&(f.loadingAnimationColor&&u.style.setProperty("--persona-tool-anim-color",f.loadingAnimationColor),f.loadingAnimationSecondaryColor&&u.style.setProperty("--persona-tool-anim-secondary-color",f.loadingAnimationSecondaryColor));let K=u.textContent||g;u.textContent="",R(u,K,0)}n.status==="complete"&&(u.style.display="none")}else C||(n.status==="complete"?u.style.display="none":u.style.display="");let j=null;if(s){j=y("div","persona-flex persona-items-center");let K=me(a?"chevron-up":"chevron-down",16,"currentColor",2);K?j.appendChild(K):j.textContent=a?"Hide":"Show";let ve=y("div","persona-flex persona-items-center persona-ml-auto");ve.append(j),l.append(p,ve)}else l.append(p);let W=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(W.setAttribute("data-persona-collapsed-preview","reasoning"),W.style.display="none",W.style.whiteSpace="pre-wrap",!a&&i&&o.activePreview&&d){let V=(Oe=(We=t==null?void 0:t.reasoning)==null?void 0:We.renderCollapsedPreview)==null?void 0:Oe.call(We,{message:e,reasoning:n,defaultPreview:d,isActive:i,config:t!=null?t:{}});Qx(W,V)||(W.textContent=d),W.style.display=""}if(!a&&i&&o.activeMinHeight&&(r.style.minHeight=o.activeMinHeight),!s)return r.append(l,W),r;let O=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");O.style.display=a?"":"none";let N=n.chunks.join(""),Z=y("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return Z.textContent=N||(n.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),O.appendChild(Z),(()=>{if(l.setAttribute("aria-expanded",a?"true":"false"),j){j.innerHTML="";let K=me(a?"chevron-up":"chevron-down",16,"currentColor",2);K?j.appendChild(K):j.textContent=a?"Hide":"Show"}O.style.display=a?"":"none",W.style.display=a?"none":W.textContent||W.childNodes.length?"":"none"})(),r.append(l,W,O),r};var Ss=new Set,Zx=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),ev=(e,t)=>{var s;let n=e.toolCall;if(!n)return"";let r=((s=n.chunks)!=null?s:[]).join("").trim();if(r)return r.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
29
29
  `);let o=fo(n.args).trim();return o?o.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
30
30
  `):""},Cl=(e,t)=>{var n,r,o;e.style.backgroundColor=(n=t.codeBlockBackgroundColor)!=null?n:"var(--persona-container, #f3f4f6)",e.style.borderColor=(r=t.codeBlockBorderColor)!=null?r:"var(--persona-border, #e5e7eb)",e.style.color=(o=t.codeBlockTextColor)!=null?o:"var(--persona-text, #171717)"},tv=(e,t)=>{var p,u,g,f,v;let n=e.toolCall,r=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,o=(u=r==null?void 0:r.collapsedMode)!=null?u:"tool-call",s=ev(e,(g=r==null?void 0:r.previewMaxLines)!=null?g:3),a=n?am(n):"";if(!n)return{summary:a,previewText:s,isActive:!1};let i=n.status!=="complete",d=(f=t==null?void 0:t.toolCall)!=null?f:{},l=a;return o==="tool-name"?l=((v=n.name)==null?void 0:v.trim())||a:o==="tool-preview"&&s&&(l=s),i&&d.activeTextTemplate?l=Ji(n,d.activeTextTemplate,l):!i&&d.completeTextTemplate&&(l=Ji(n,d.completeTextTemplate,l)),{summary:l,previewText:s,isActive:i}},og=(e,t,n)=>{var p;let r=Ss.has(e),o=(p=n==null?void 0:n.toolCall)!=null?p:{},s=t.querySelector('button[data-expand-header="true"]'),a=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!s||!a)return;s.setAttribute("aria-expanded",r?"true":"false");let d=s.querySelector(".persona-ml-auto"),l=d==null?void 0:d.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let u=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",g=me(r?"chevron-up":"chevron-down",16,u,2);g?l.appendChild(g):l.textContent=r?"Hide":"Show"}a.style.display=r?"":"none",i&&(i.style.display=r?"none":i.textContent||i.childNodes.length?"":"none")},Al=(e,t)=>{var N,Z,Te,pe,ee,xe,Me,oe,be;let n=e.toolCall,r=(N=t==null?void 0:t.toolCall)!=null?N:{},o=y("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),r.backgroundColor&&(o.style.backgroundColor=r.backgroundColor),r.borderColor&&(o.style.borderColor=r.borderColor),r.borderWidth&&(o.style.borderWidth=r.borderWidth),r.borderRadius&&(o.style.borderRadius=r.borderRadius),o.style.boxShadow=r.shadow!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return o;let s=(Te=(Z=t==null?void 0:t.features)==null?void 0:Z.toolCallDisplay)!=null?Te:{},a=s.expandable!==!1,i=a&&Ss.has(e.id),{summary:d,previewText:l,isActive:p}=tv(e,t),u=y("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");u.type="button",a&&(u.setAttribute("aria-expanded",i?"true":"false"),u.setAttribute("data-expand-header","true")),u.setAttribute("data-bubble-type","tool"),r.headerBackgroundColor&&(u.style.backgroundColor=r.headerBackgroundColor),r.headerPaddingX&&(u.style.paddingLeft=r.headerPaddingX,u.style.paddingRight=r.headerPaddingX),r.headerPaddingY&&(u.style.paddingTop=r.headerPaddingY,u.style.paddingBottom=r.headerPaddingY);let g=y("div","persona-flex persona-flex-col persona-text-left"),f=y("span","persona-text-xs persona-text-persona-primary");r.headerTextColor&&(f.style.color=r.headerTextColor);let v=String((pe=n.startedAt)!=null?pe:Date.now()),x=()=>{let de=y("span","");return de.setAttribute("data-tool-elapsed",v),de.textContent=Js(n),de},E=(xe=r.renderCollapsedSummary)==null?void 0:xe.call(r,{message:e,toolCall:n,defaultSummary:d,previewText:l,collapsedMode:(ee=s.collapsedMode)!=null?ee:"tool-call",isActive:p,config:t!=null?t:{},elapsed:Js(n),createElapsedElement:x});typeof E=="string"&&E.trim()?(f.textContent=E,g.appendChild(f)):E instanceof HTMLElement?g.appendChild(E):(f.textContent=d,g.appendChild(f));let T=(Me=s.loadingAnimation)!=null?Me:"none",L=r.activeTextTemplate,k=r.completeTextTemplate,M=p?L:k,P=E instanceof HTMLElement,C=(de,ae,se)=>{let We=se;for(let Oe of ae){let V=y("span","persona-tool-char");V.style.setProperty("--char-index",String(We)),V.textContent=Oe===" "?"\xA0":Oe,de.appendChild(V),We++}return We},R=(de,ae)=>{var V;f.textContent="";let se=((V=n.name)==null?void 0:V.trim())||"tool",We=Fa(de,se),Oe=0;for(let K of We){let ve=K.styles.length>0?(()=>{let J=y("span",K.styles.map(ce=>`persona-tool-text-${ce}`).join(" "));return f.appendChild(J),J})():f;if(K.isDuration&&p)ve.appendChild(x());else{let J=K.isDuration?Js(n):K.text;ae?Oe=C(ve,J,Oe):ve.appendChild(document.createTextNode(J))}}};if(!P)if(p&&T!=="none"){let de=(oe=r.loadingAnimationDuration)!=null?oe:2e3;if(f.setAttribute("data-preserve-animation","true"),T==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${de}ms`),M&&R(M,!1);else if(f.classList.add(`persona-tool-loading-${T}`),f.style.setProperty("--persona-tool-anim-duration",`${de}ms`),T==="shimmer-color"&&(r.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",r.loadingAnimationColor),r.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",r.loadingAnimationSecondaryColor)),M)R(M,!0);else{let ae=f.textContent||d;f.textContent="",C(f,ae,0)}}else M&&R(M,!1);let F=null;if(a){F=y("div","persona-flex persona-items-center");let de=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=me(i?"chevron-up":"chevron-down",16,de,2);ae?F.appendChild(ae):F.textContent=i?"Hide":"Show";let se=y("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");se.append(F),u.append(g,se)}else u.append(g);let j=y("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(j.setAttribute("data-persona-collapsed-preview","tool"),j.style.display="none",j.style.whiteSpace="pre-wrap",!i&&p&&s.activePreview&&l){let de=(be=r.renderCollapsedPreview)==null?void 0:be.call(r,{message:e,toolCall:n,defaultPreview:l,isActive:p,config:t!=null?t:{}});Zx(j,de)||(j.textContent=l),j.style.display=""}if(!i&&p&&s.activeMinHeight&&(o.style.minHeight=s.activeMinHeight),!a)return o.append(u,j),o;let W=y("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(W.style.display=i?"":"none",r.contentBackgroundColor&&(W.style.backgroundColor=r.contentBackgroundColor),r.contentTextColor&&(W.style.color=r.contentTextColor),r.contentPaddingX&&(W.style.paddingLeft=r.contentPaddingX,W.style.paddingRight=r.contentPaddingX),r.contentPaddingY&&(W.style.paddingTop=r.contentPaddingY,W.style.paddingBottom=r.contentPaddingY),n.name){let de=y("div","persona-text-xs persona-text-persona-muted persona-italic");r.contentTextColor?de.style.color=r.contentTextColor:r.headerTextColor&&(de.style.color=r.headerTextColor),de.textContent=n.name,W.appendChild(de)}if(n.args!==void 0){let de=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Arguments";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Cl(se,r),se.textContent=fo(n.args),de.append(ae,se),W.appendChild(de)}if(n.chunks&&n.chunks.length){let de=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Activity";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Cl(se,r),se.textContent=n.chunks.join(""),de.append(ae,se),W.appendChild(de)}if(n.status==="complete"&&n.result!==void 0){let de=y("div","persona-space-y-1"),ae=y("div","persona-text-xs persona-text-persona-muted");r.labelTextColor&&(ae.style.color=r.labelTextColor),ae.textContent="Result";let se=y("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");se.style.fontSize="0.75rem",se.style.lineHeight="1rem",Cl(se,r),se.textContent=fo(n.result),de.append(ae,se),W.appendChild(de)}if(n.status==="complete"&&typeof n.duration=="number"){let de=y("div","persona-text-xs persona-text-persona-muted");r.contentTextColor&&(de.style.color=r.contentTextColor),de.textContent=`Duration: ${n.duration}ms`,W.appendChild(de)}return(()=>{if(u.setAttribute("aria-expanded",i?"true":"false"),F){F.innerHTML="";let de=r.toggleTextColor||r.headerTextColor||"var(--persona-primary, #171717)",ae=me(i?"chevron-up":"chevron-down",16,de,2);ae?F.appendChild(ae):F.textContent=i?"Hide":"Show"}W.style.display=i?"":"none",j.style.display=i?"none":j.textContent||j.childNodes.length?"":"none"})(),o.append(u,j,W),o};var Ko=new Map,mi=e=>{let n=(e.startsWith(Rr)?e.slice(Rr.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(n.length===0)return e;let r=n.join(" ").toLowerCase();return r.charAt(0).toUpperCase()+r.slice(1)},sg=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,ag=(e,t)=>{var r,o,s;let n=(o=(r=sg(t))==null?void 0:r.detailsDisplay)!=null?o:"collapsed";return(s=Ko.get(e))!=null?s:n==="expanded"},ig=(e,t,n)=>{var a,i;let r=sg(n);e.setAttribute("aria-expanded",t?"true":"false");let o=e.querySelector("[data-approval-details-label]");o&&(o.textContent=t?(a=r==null?void 0:r.hideDetailsLabel)!=null?a:"Hide details":(i=r==null?void 0:r.showDetailsLabel)!=null?i:"Show details");let s=e.querySelector("[data-approval-details-chevron]");if(s){s.innerHTML="";let d=me(t?"chevron-up":"chevron-down",14,"currentColor",2);d&&s.appendChild(d)}},lg=(e,t,n)=>{let r=t.querySelector('button[data-bubble-type="approval"]'),o=t.querySelector("[data-approval-details]");if(!r||!o)return;let s=ag(e,n);ig(r,s,n),o.style.display=s?"":"none"};var gi=(e,t)=>{var R,F,j,W,O,N,Z,Te,pe,ee,xe,Me,oe,be,de;let n=e.approval,r=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,o=(n==null?void 0:n.status)==="pending",s=y("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(s.id=`bubble-${e.id}`,s.setAttribute("data-message-id",e.id),s.style.backgroundColor=(R=r==null?void 0:r.backgroundColor)!=null?R:"var(--persona-approval-bg, #fefce8)",s.style.borderColor=(F=r==null?void 0:r.borderColor)!=null?F:"var(--persona-approval-border, #fef08a)",s.style.boxShadow=(r==null?void 0:r.shadow)!==void 0?r.shadow.trim()===""?"none":r.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!n)return s;let a=y("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=y("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let d=n.status==="denied"?"shield-x":n.status==="timeout"?"shield-alert":"shield-check",l=n.status==="approved"?"var(--persona-feedback-success, #16a34a)":n.status==="denied"?"var(--persona-feedback-error, #dc2626)":n.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(j=r==null?void 0:r.titleColor)!=null?j:"currentColor",p=me(d,20,l,2);p&&i.appendChild(p);let u=y("div","persona-flex-1 persona-min-w-0"),g=y("div","persona-flex persona-items-center persona-gap-2"),f=y("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(r!=null&&r.titleColor&&(f.style.color=r.titleColor),f.textContent=(W=r==null?void 0:r.title)!=null?W:"Approval Required",g.appendChild(f),!o){let ae=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ae.setAttribute("data-approval-status",n.status),n.status==="approved"?(ae.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ae.style.color="var(--persona-palette-colors-success-700, #15803d)",ae.textContent="Approved"):n.status==="denied"?(ae.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ae.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ae.textContent="Denied"):n.status==="timeout"&&(ae.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ae.style.color="var(--persona-palette-colors-warning-700, #b45309)",ae.textContent="Timeout"),g.appendChild(ae)}u.appendChild(g);let x=n.toolType==="webmcp"||n.toolName.startsWith(Rr)?Us(n.toolName):void 0,E=(O=r==null?void 0:r.formatDescription)==null?void 0:O.call(r,{toolName:n.toolName,toolType:n.toolType,description:n.description,parameters:n.parameters,...x?{displayTitle:x}:{},...n.reason?{reason:n.reason}:{}}),T=!n.toolName,L=E||(T?n.description:`The assistant wants to use \u201C${x!=null?x:mi(n.toolName)}\u201D.`),k=y("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(k.setAttribute("data-approval-summary","true"),r!=null&&r.descriptionColor&&(k.style.color=r.descriptionColor),k.textContent=L,u.appendChild(k),n.reason){let ae=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ae.setAttribute("data-approval-reason","true"),r!=null&&r.reasonColor?ae.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(ae.style.color=r.descriptionColor);let se=y("span","persona-font-medium");se.textContent=`${(N=r==null?void 0:r.reasonLabel)!=null?N:"Agent's stated reason:"} `,ae.appendChild(se),ae.appendChild(document.createTextNode(n.reason)),u.appendChild(ae)}let M=(Z=r==null?void 0:r.detailsDisplay)!=null?Z:"collapsed",P=!!n.description&&!T,C=P||!!n.parameters;if(M!=="hidden"&&C){let ae=ag(e.id,t),se=y("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");se.type="button",se.setAttribute("data-expand-header","true"),se.setAttribute("data-bubble-type","approval"),r!=null&&r.descriptionColor&&(se.style.color=r.descriptionColor);let We=y("span");We.setAttribute("data-approval-details-label","true");let Oe=y("span","persona-inline-flex persona-items-center");Oe.setAttribute("data-approval-details-chevron","true"),se.append(We,Oe),ig(se,ae,t),u.appendChild(se);let V=y("div");if(V.setAttribute("data-approval-details","true"),V.style.display=ae?"":"none",P){let K=y("p","persona-text-sm persona-mt-1 persona-text-persona-muted");r!=null&&r.descriptionColor&&(K.style.color=r.descriptionColor),K.textContent=n.description,V.appendChild(K)}if(n.parameters){let K=y("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");r!=null&&r.parameterBackgroundColor&&(K.style.backgroundColor=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(K.style.color=r.parameterTextColor),K.style.fontSize="0.75rem",K.style.lineHeight="1rem",K.textContent=fo(n.parameters),V.appendChild(K)}u.appendChild(V)}if(o){let ae=y("div","persona-flex persona-gap-2 persona-mt-2");ae.setAttribute("data-approval-buttons","true");let se=y("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");se.type="button",se.style.backgroundColor=(Te=r==null?void 0:r.approveButtonColor)!=null?Te:"var(--persona-approval-approve-bg, #22c55e)",se.style.color=(pe=r==null?void 0:r.approveButtonTextColor)!=null?pe:"#ffffff",se.setAttribute("data-approval-action","approve");let We=me("shield-check",14,(ee=r==null?void 0:r.approveButtonTextColor)!=null?ee:"#ffffff",2);We&&(We.style.marginRight="4px",se.appendChild(We));let Oe=document.createTextNode((xe=r==null?void 0:r.approveLabel)!=null?xe:"Approve");se.appendChild(Oe);let V=y("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");V.type="button",V.style.backgroundColor=(Me=r==null?void 0:r.denyButtonColor)!=null?Me:"transparent",V.style.color=(oe=r==null?void 0:r.denyButtonTextColor)!=null?oe:"var(--persona-feedback-error, #dc2626)",V.style.border=`1px solid ${r!=null&&r.denyButtonTextColor?r.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,V.setAttribute("data-approval-action","deny");let K=me("shield-x",14,(be=r==null?void 0:r.denyButtonTextColor)!=null?be:"var(--persona-feedback-error, #dc2626)",2);K&&(K.style.marginRight="4px",V.appendChild(K));let ve=document.createTextNode((de=r==null?void 0:r.denyLabel)!=null?de:"Deny");V.appendChild(ve),ae.append(se,V),u.appendChild(ae)}return a.append(i,u),s.appendChild(a),s};function nv(e){var n,r;let t=(n=e.getRootNode)==null?void 0:n.call(e);return t instanceof ShadowRoot?t:((r=e.ownerDocument)!=null?r:document).body}function cg(e){var x;let{anchor:t,content:n,placement:r="bottom-start",offset:o=6,matchAnchorWidth:s=!1,zIndex:a=2147483e3,onOpen:i,onDismiss:d}=e,l=(x=e.container)!=null?x:nv(t),p=!1,u=null,g=()=>{if(!p)return;let E=t.getBoundingClientRect();n.style.position="fixed",s&&(n.style.minWidth=`${E.width}px`);let T=r==="top-start"||r==="top-end"?E.top-o-n.getBoundingClientRect().height:E.bottom+o,L=r==="bottom-end"||r==="top-end"?E.right-n.getBoundingClientRect().width:E.left;n.style.top=`${T}px`,n.style.left=`${L}px`},f=()=>{p&&(p=!1,u&&(u(),u=null),n.remove())},v=()=>{var P,C,R;if(p)return;p=!0,a!=null&&(n.style.zIndex=String(a)),l.appendChild(n),g();let E=(C=((P=t.ownerDocument)!=null?P:document).defaultView)!=null?C:window,T=(R=t.ownerDocument)!=null?R:document,L=()=>{if(!t.isConnected){f(),d==null||d("anchor-removed");return}g()},k=F=>{let j=typeof F.composedPath=="function"?F.composedPath():[];j.includes(n)||j.includes(t)||(f(),d==null||d("outside"))},M=E.setTimeout(()=>{T.addEventListener("pointerdown",k,!0)},0);E.addEventListener("scroll",L,!0),E.addEventListener("resize",L),u=()=>{E.clearTimeout(M),T.removeEventListener("pointerdown",k,!0),E.removeEventListener("scroll",L,!0),E.removeEventListener("resize",L)},i==null||i()};return{get isOpen(){return p},open:v,close:f,toggle:()=>p?f():v(),reposition:g,destroy:f}}function dg(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(n=>n instanceof HTMLElement&&(n.tagName==="INPUT"||n.tagName==="TEXTAREA"||n.isContentEditable))}var rv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),pg=(e,t)=>{let n=e.keyHandlers.get(t);n&&(document.removeEventListener("keydown",n),e.keyHandlers.delete(t));let r=e.popovers.get(t);r&&(r.destroy(),e.popovers.delete(t))},Go=(e,t)=>{pg(e,t);let n=e.pendingOrder.indexOf(t);n!==-1&&e.pendingOrder.splice(n,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},ov=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,sv=(e,t)=>{var r,o;let n=(r=t==null?void 0:t.detailsDisplay)!=null?r:"collapsed";return(o=Ko.get(e))!=null?o:n==="expanded"},Sl=e=>{let t=y("span","persona-approval-kbd");return t.textContent=e,t},av=(e,t)=>{var l,p;let n=y("span","persona-approval-title");t!=null&&t.titleColor&&(n.style.color=t.titleColor);let o=e.toolType==="webmcp"||e.toolName.startsWith(Rr)?Us(e.toolName):void 0,s=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...o?{displayTitle:o}:{},...e.reason?{reason:e.reason}:{}});if(s)return n.textContent=s,n;let a=o!=null?o:mi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;n.append("The assistant wants to use ");let d=document.createElement("strong");if(d.textContent=a,n.appendChild(d),i){n.append(" from ");let u=document.createElement("strong");u.textContent=i,n.appendChild(u)}return n},iv=e=>{let t=y("div","persona-approval-resolved"),n=me("ban",15,"currentColor",2);n&&t.appendChild(n);let r=y("span","persona-approval-resolved-name");return r.textContent=e.toolName?mi(e.toolName):"Tool",t.append(r,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},lv=(e,t,n,r,o,s,a)=>{var F,j,W,O,N,Z,Te;let i=y("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),r!=null&&r.backgroundColor&&(i.style.background=r.backgroundColor),r!=null&&r.borderColor&&(i.style.borderColor=r.borderColor),(r==null?void 0:r.shadow)!==void 0&&(i.style.boxShadow=r.shadow.trim()===""?"none":r.shadow);let d=(F=r==null?void 0:r.detailsDisplay)!=null?F:"collapsed",l=!!n.description&&d!=="hidden",p=n.parameters!=null&&d!=="hidden",u=l||p,g=u&&sv(t.id,r),f=(j=r==null?void 0:r.showDetailsLabel)!=null?j:"Show details",v=(W=r==null?void 0:r.hideDetailsLabel)!=null?W:"Hide details",x=y("button","persona-approval-head");x.type="button",u?(x.setAttribute("data-action","toggle-params"),x.setAttribute("aria-expanded",g?"true":"false"),x.setAttribute("aria-label",g?v:f)):x.setAttribute("data-static","true");let E=y("span","persona-approval-logo"),T=me("shield-check",16,"currentColor",2);T&&E.appendChild(T),x.appendChild(E);let L=av(n,r);if(u){let pe=y("span","persona-approval-toggle");pe.setAttribute("aria-hidden","true");let ee=me("chevron-down",14,"currentColor",2);ee&&pe.appendChild(ee),L.append(" "),L.appendChild(pe)}x.appendChild(L),i.appendChild(x);let k=y("div","persona-approval-body");if(u){let pe=y("div","persona-approval-details");if(pe.setAttribute("data-role","params"),pe.hidden=!g,l){let ee=y("p","persona-approval-desc");r!=null&&r.descriptionColor&&(ee.style.color=r.descriptionColor),ee.textContent=n.description,pe.appendChild(ee)}if(p){let ee=y("pre","persona-approval-params");r!=null&&r.parameterBackgroundColor&&(ee.style.background=r.parameterBackgroundColor),r!=null&&r.parameterTextColor&&(ee.style.color=r.parameterTextColor),ee.textContent=fo(n.parameters),pe.appendChild(ee)}k.appendChild(pe)}if(n.reason){let pe=y("p","persona-approval-reason");r!=null&&r.reasonColor?pe.style.color=r.reasonColor:r!=null&&r.descriptionColor&&(pe.style.color=r.descriptionColor);let ee=y("span","persona-approval-reason-label");ee.textContent=`${(O=r==null?void 0:r.reasonLabel)!=null?O:"Agent's stated reason:"} `,pe.append(ee,document.createTextNode(n.reason)),k.appendChild(pe)}let M=y("div","persona-approval-actions"),P=null,C=pe=>{r!=null&&r.approveButtonColor&&(pe.style.background=r.approveButtonColor),r!=null&&r.approveButtonTextColor&&(pe.style.color=r.approveButtonTextColor)},R=y("button","persona-approval-deny");if(R.type="button",R.setAttribute("data-action","deny"),r!=null&&r.denyButtonColor&&(R.style.background=r.denyButtonColor),r!=null&&r.denyButtonTextColor&&(R.style.color=r.denyButtonTextColor),R.append((N=r==null?void 0:r.denyLabel)!=null?N:"Deny"),a){let pe=y("div","persona-approval-split"),ee=y("button","persona-approval-primary");ee.type="button",ee.setAttribute("data-action","always"),C(ee),ee.append((Z=r==null?void 0:r.approveLabel)!=null?Z:"Always allow",Sl("\u23CE"));let xe=y("button","persona-approval-caret");xe.type="button",xe.setAttribute("data-action","toggle-menu"),xe.setAttribute("aria-label","More options"),C(xe);let Me=me("chevron-down",15,"currentColor",2);Me&&xe.appendChild(Me),pe.append(ee,xe),M.append(pe,R),R.append(Sl("Esc"));let oe=y("div","persona-approval-menu"),be=y("button","persona-approval-menu-item");be.type="button",be.append("Allow once",Sl("\u2318\u23CE")),oe.appendChild(be),P=cg({anchor:pe,content:oe,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,P),be.addEventListener("click",()=>{Go(e,t.id),o()})}else{let pe=y("button","persona-approval-primary persona-approval-primary--solo");pe.type="button",pe.setAttribute("data-action","allow"),C(pe),pe.append((Te=r==null?void 0:r.approveLabel)!=null?Te:"Allow"),M.append(pe,R)}return k.appendChild(M),i.appendChild(k),i.addEventListener("click",pe=>{let ee=pe.target instanceof Element?pe.target.closest("[data-action]"):null;if(!ee)return;let xe=ee.getAttribute("data-action");if(xe==="toggle-params"){let Me=i.querySelector('[data-role="params"]');if(Me){let oe=Me.hidden;Me.hidden=!oe,x.setAttribute("aria-expanded",oe?"true":"false"),x.setAttribute("aria-label",oe?v:f),Ko.set(t.id,oe)}return}if(xe==="toggle-menu"){P==null||P.toggle();return}if(xe==="always"){Go(e,t.id),o({remember:!0});return}if(xe==="allow"){Go(e,t.id),o();return}if(xe==="deny"){Go(e,t.id),s();return}}),i},ug=()=>{let e=rv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:r,approve:o,deny:s,config:a})=>{let i=r==null?void 0:r.approval;if(!i)return null;let d=ov(a);if(i.status!=="pending"){if(Go(e,r.id),i.status==="approved"){let u=document.createElement("div");return u.style.display="none",u}return iv(i)}pg(e,r.id);let l=(d==null?void 0:d.enableAlwaysAllow)===!0,p=lv(e,r,i,d,o,s,l);if(l){e.pendingOrder.includes(r.id)||e.pendingOrder.push(r.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let u=g=>{dg(g)||r.id===e.latestPendingApprovalId&&(g.key!=="Escape"&&g.key!=="Enter"||(g.preventDefault(),g.stopImmediatePropagation(),Go(e,r.id),g.key==="Escape"?s():g.metaKey||g.ctrlKey?o():o({remember:!0})))};e.keyHandlers.set(r.id,u),document.addEventListener("keydown",u)}return p}},teardown:()=>{for(let r of[...e.keyHandlers.keys(),...e.popovers.keys()])Go(e,r);e.latestPendingApprovalId=null}}};var mg=e=>{let t=[],n=null;return{buttons:t,render:(o,s,a,i,d,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(n=null),!o||!o.length||!p&&(i!=null?i:s?s.getMessages():[]).some(E=>E.role==="user"))return;let u=document.createDocumentFragment(),g=s?s.isStreaming():!1,f=v=>{switch(v){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'}};if(o.forEach(v=>{let x=y("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");x.type="button",x.textContent=v,x.disabled=g,d!=null&&d.fontFamily&&(x.style.fontFamily=f(d.fontFamily)),d!=null&&d.fontWeight&&(x.style.fontWeight=d.fontWeight),d!=null&&d.paddingX&&(x.style.paddingLeft=d.paddingX,x.style.paddingRight=d.paddingX),d!=null&&d.paddingY&&(x.style.paddingTop=d.paddingY,x.style.paddingBottom=d.paddingY),x.addEventListener("click",()=>{!s||s.isStreaming()||(a.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:v},bubbles:!0,composed:!0})),s.sendMessage(v))}),u.appendChild(x),t.push(x)}),e.appendChild(u),p){let v=JSON.stringify(o);v!==n&&(n=v,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...o]},bubbles:!0,composed:!0})))}}}};var fa=class{constructor(t=2e3,n=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=n}push(t){var n;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(n=this.store)==null||n.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let n=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let r of n)this.buffer[this.head]=r,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(r.type);return this.totalCaptured=t.length,n.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let n=this.getAll();return t>=n.length?n:n.slice(n.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var ha=class{constructor(t="persona-event-stream",n="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=n}open(){return new Promise((t,n)=>{try{let r=indexedDB.open(this.dbName,1);r.onupgradeneeded=()=>{let o=r.result;o.objectStoreNames.contains(this.storeName)||o.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},r.onsuccess=()=>{this.db=r.result,t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}getAll(){return new Promise((t,n)=>{if(!this.db){t([]);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{n(a.error)}}catch(r){n(r)}})}getCount(){return new Promise((t,n)=>{if(!this.db){t(0);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}clear(){return new Promise((t,n)=>{if(!this.db){t();return}this.pendingWrites=[];try{let s=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();s.onsuccess=()=>{t()},s.onerror=()=>{n(s.error)}}catch(r){n(r)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,n)=>{try{let r=indexedDB.deleteDatabase(this.dbName);r.onsuccess=()=>{t()},r.onerror=()=>{n(r.error)}}catch(r){n(r)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let r=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let o of t)r.put(o)}catch{}}};var cv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),dv=new Set(["step_start","execution_start"]),pv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),uv=new Set(["step_complete","agent_turn_complete"]),mv=new Set(["flow_complete","agent_complete"]),gg=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),hg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),Jn=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,Jo=(e,t)=>{let n=e[t];return hg(n)?n:void 0};function Tl(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function fi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function gv(e,t){return typeof t.type=="string"?t.type:e}function fv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function hv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function fg(e){var r,o,s,a,i;let t=Jo(e,"result"),n=[Jo(e,"tokens"),Jo(e,"totalTokens"),t?Jo(t,"tokens"):void 0,Jo(e,"usage"),t?Jo(t,"usage"):void 0];for(let d of n){if(!d)continue;let l=(o=(r=Jn(d.output))!=null?r:Jn(d.outputTokens))!=null?o:Jn(d.completionTokens);if(l!==void 0)return l}return(i=(s=Jn(e.outputTokens))!=null?s:Jn(e.completionTokens))!=null?i:t?(a=Jn(t.outputTokens))!=null?a:Jn(t.completionTokens):void 0}function yv(e){var n,r,o,s,a;let t=Jo(e,"result");return(a=(o=(r=(n=Jn(e.executionTime))!=null?n:Jn(e.executionTimeMs))!=null?r:Jn(e.execution_time))!=null?o:Jn(e.duration))!=null?a:t?(s=Jn(t.executionTime))!=null?s:Jn(t.executionTimeMs):void 0}function bv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var ya=class{constructor(t=bv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let n=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:n,tokensPerSecond:fi(this.metric.outputTokens,n)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,n){var s;if(!hg(n)){gg.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let r=gv(t,n),o=this.now();if(cv.has(r)){this.startRun(o);return}if(dv.has(r)){this.run||this.startRun(o);return}if(pv.has(r)){if(!hv(r,n))return;let a=fv(n);if(!a)return;this.run||this.startRun(o);let i=this.run;(s=i.firstDeltaAt)!=null||(i.firstDeltaAt=o),i.visibleCharCount+=a.length;let d=i.exactOutputTokens+Tl(i.visibleCharCount),l=o-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:fi(d,l),outputTokens:d,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(uv.has(r)){if(!this.run)return;let a=this.run,i=fg(n);i!==void 0&&(a.exactOutputTokens+=i,a.visibleCharCount=0);let d=a.exactOutputTokens>0,l=a.exactOutputTokens+Tl(a.visibleCharCount),p=this.resolveDuration(a,n,o);this.metric={status:"running",tokensPerSecond:fi(l,p),outputTokens:l,durationMs:p,source:d?"usage":"estimate"};return}if(mv.has(r)){if(!this.run)return;let a=this.run,i=fg(n),d=i!=null?i:a.exactOutputTokens+Tl(a.visibleCharCount),l=i!==void 0||a.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(a,n,o);this.metric={status:"complete",tokensPerSecond:fi(d,p),outputTokens:d,durationMs:p,source:l},this.run=null;return}if(gg.has(r)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,n,r){let o=t.firstDeltaAt!==void 0?r-t.firstDeltaAt:void 0;if(o!==void 0&&o>=250)return o;let s=yv(n);return s!=null?s:r-t.startedAt}};function Ts(e,t){t&&t.split(/\s+/).forEach(n=>n&&e.classList.add(n))}var xv={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)"}},vv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},wv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Cv=100;function Av(e,t){let n={...xv,...t};if(n[e])return n[e];for(let r of Object.keys(n))if(r.endsWith("_")&&e.startsWith(r))return n[r];return vv}function Sv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Tv(e){let t=new Date(e),n=String(t.getHours()).padStart(2,"0"),r=String(t.getMinutes()).padStart(2,"0"),o=String(t.getSeconds()).padStart(2,"0"),s=String(t.getMilliseconds()).padStart(3,"0");return`${n}:${r}:${o}.${s}`}function Ev(e,t){try{let n=JSON.parse(e);if(typeof n!="object"||n===null)return null;for(let r of t){let o=r.split("."),s=n;for(let a of o)if(s&&typeof s=="object"&&s!==null)s=s[a];else{s=void 0;break}if(typeof s=="string"&&s.trim())return s.trim()}}catch{}return null}function Mv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(n=>{let r=document.createElement("textarea");r.value=e,r.style.position="fixed",r.style.opacity="0",document.body.appendChild(r),r.select(),document.execCommand("copy"),document.body.removeChild(r),n()})}function kv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Lv(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function Pv(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Iv(e,t,n){let r,o;try{o=JSON.parse(e.payload),r=JSON.stringify(o,null,2)}catch{o=e.payload,r=e.payload}let s=t.find(i=>i.renderEventStreamPayload);if(s!=null&&s.renderEventStreamPayload&&n){let i=s.renderEventStreamPayload({event:e,config:n,defaultRenderer:()=>a(),parsedPayload:o});if(i)return i}return a();function a(){let i=y("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),d=y("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return d.textContent=r,i.appendChild(d),i}}function El(e,t,n,r,o,s,a,i){var g;let d=o.has(e.id),l=y("div","persona-border-b persona-border-persona-divider persona-text-xs");Ts(l,(g=r.classNames)==null?void 0:g.eventRow);let p=a.find(f=>f.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let f=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>u(),isExpanded:d,onToggleExpand:()=>s(e.id)});if(f)return l.appendChild(f),l}return l.appendChild(u()),l;function u(){var N,Z;let f=y("div",""),v=y("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 x=y("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),E=me(d?"chevron-down":"chevron-right","14px","currentColor",2);E&&x.appendChild(E);let T=y("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),L=(N=r.timestampFormat)!=null?N:"relative";T.textContent=L==="relative"?Sv(e.timestamp,n):Tv(e.timestamp);let k=null;r.showSequenceNumbers!==!1&&(k=y("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),k.textContent=String(t+1));let M=Av(e.type,r.badgeColors),P=y("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");P.style.backgroundColor=M.bg,P.style.color=M.text,P.style.borderColor=M.text+"50",P.textContent=e.type;let C=(Z=r.descriptionFields)!=null?Z:wv,R=Ev(e.payload,C),F=null;R&&(F=y("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),F.textContent=R);let j=y("div","persona-flex-1 persona-min-w-0"),W=y("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),O=me("clipboard","12px","currentColor",1.5);return O&&W.appendChild(O),W.addEventListener("click",async Te=>{Te.stopPropagation(),await Mv(kv(e)),W.innerHTML="";let pe=me("check","12px","currentColor",1.5);pe&&W.appendChild(pe),setTimeout(()=>{W.innerHTML="";let ee=me("clipboard","12px","currentColor",1.5);ee&&W.appendChild(ee)},1500)}),v.appendChild(x),v.appendChild(T),k&&v.appendChild(k),v.appendChild(P),F&&v.appendChild(F),v.appendChild(j),v.appendChild(W),f.appendChild(v),d&&f.appendChild(Iv(e,a,i)),f}}function yg(e){var v,x,E,T,L;let{buffer:t,getFullHistory:n,onClose:r,config:o,plugins:s=[],getThroughput:a}=e,i=(v=o==null?void 0:o.features)==null?void 0:v.scrollToBottom,d=(i==null?void 0:i.enabled)!==!1,l=(x=i==null?void 0:i.iconName)!=null?x:"arrow-down",p=(E=i==null?void 0:i.label)!=null?E:"",u=(L=(T=o==null?void 0:o.features)==null?void 0:T.eventStream)!=null?L:{},g=s.find(k=>k.renderEventStreamView);if(g!=null&&g.renderEventStreamView&&o){let k=g.renderEventStreamView({config:o,events:t.getAll(),defaultRenderer:()=>f().element,onClose:r});if(k)return{element:k,update:()=>{},destroy:()=>{}}}return f();function f(){let k=u.classNames,M=y("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ts(M,k==null?void 0:k.panel);let P=[],C="",R="",F=null,j=[],W={},O=0,N=Qa(),Z=0,Te=0,pe=!1,ee=null,xe=!1,Me=0,oe=new Set,be=new Map,de="",ae="",se=null,We,Oe,V,K,ve,J=null,ce=null,Re=null;function ge(){let H=y("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Q=y("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");Ts(Q,k==null?void 0:k.headerBar);let Se=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Se.textContent="Events",We=y("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"),We.textContent="0",a){ce=y("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),ce.style.cursor="help";let _t=y("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");_t.textContent="Throughput",J=y("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 persona-tabular-nums"),J.textContent="-- tok/s",Re=y("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Re.style.display="none",Re.style.pointerEvents="none";let Nn=ce,Sn=Re,Tn=()=>{if(!Sn.textContent)return;let En=Nn.getBoundingClientRect(),lr=H.getBoundingClientRect();Sn.style.left=`${En.left-lr.left}px`,Sn.style.top=`${En.bottom-lr.top+4}px`,Sn.style.display="block"},xn=()=>{Sn.style.display="none"};ce.addEventListener("mouseenter",Tn),ce.addEventListener("mouseleave",xn),ce.appendChild(_t),ce.appendChild(J)}let lt=y("div","persona-flex-1");Oe=y("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 Qe=y("option","");Qe.value="",Qe.textContent="All events",Oe.appendChild(Qe),V=y("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),V.type="button",V.title="Copy All";let yn=me("clipboard-copy","12px","currentColor",1.5);yn&&V.appendChild(yn);let xt=y("span","persona-text-xs");xt.textContent="Copy All",V.appendChild(xt),Q.appendChild(Se),Q.appendChild(We),ce&&Q.appendChild(ce),Q.appendChild(lt),Q.appendChild(Oe),Q.appendChild(V);let vt=y("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ts(vt,k==null?void 0:k.searchBar);let It=me("search","14px","var(--persona-muted, #9ca3af)",1.5),wt=y("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");It&&wt.appendChild(It),K=y("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"),Ts(K,k==null?void 0:k.searchInput),K.type="text",K.placeholder="Search event payloads...",ve=y("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"),ve.type="button",ve.style.display="none";let dn=me("x","12px","currentColor",2);return dn&&ve.appendChild(dn),vt.appendChild(wt),vt.appendChild(K),vt.appendChild(ve),H.appendChild(Q),H.appendChild(vt),Re&&H.appendChild(Re),H}let Ke,tt=s.find(H=>H.renderEventStreamToolbar);if(tt!=null&&tt.renderEventStreamToolbar&&o){let H=tt.renderEventStreamToolbar({config:o,defaultRenderer:()=>ge(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Q=>{C=Q,$e(),Qt()},onSearchChange:Q=>{R=Q,$e(),Qt()}});Ke=H!=null?H:ge()}else Ke=ge();let Lt=y("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");Lt.style.display="none";function Ye(){if(!a||!J||!ce)return;let H=a();J.textContent=Lv(H);let Q=Pv(H);Re&&(Re.textContent=Q,Q||(Re.style.display="none")),Q?ce.setAttribute("aria-label",Q):ce.removeAttribute("aria-label")}let _e=y("div","persona-flex-1 persona-min-h-0 persona-relative"),G=y("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");G.style.height="100%";let ze=y("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ts(ze,k==null?void 0:k.scrollIndicator),ze.style.display="none",ze.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let qe=me(l,"14px","currentColor",2);qe&&ze.appendChild(qe);let we=y("span","");we.textContent=p,ze.appendChild(we);let Ae=y("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");Ae.style.display="none",_e.appendChild(G),_e.appendChild(Ae),_e.appendChild(ze),M.setAttribute("tabindex","0"),M.appendChild(Ke),M.appendChild(Lt),M.appendChild(_e);function nt(){let H=t.getAll(),Q={};for(let xt of H)Q[xt.type]=(Q[xt.type]||0)+1;let Se=Object.keys(Q).sort(),lt=Se.length!==j.length||!Se.every((xt,vt)=>xt===j[vt]),Qe=!lt&&Se.some(xt=>Q[xt]!==W[xt]),jt=H.length!==Object.values(W).reduce((xt,vt)=>xt+vt,0);if(!lt&&!Qe&&!jt||(j=Se,W=Q,!Oe))return;let yn=Oe.value;if(Oe.options[0].textContent="All events",lt){for(;Oe.options.length>1;)Oe.remove(1);for(let xt of Se){let vt=y("option","");vt.value=xt,vt.textContent=`${xt} (${Q[xt]||0})`,Oe.appendChild(vt)}yn&&Se.includes(yn)?Oe.value=yn:yn&&(Oe.value="",C="")}else for(let xt=1;xt<Oe.options.length;xt++){let vt=Oe.options[xt];vt.textContent=`${vt.value} (${Q[vt.value]||0})`}}function Ft(){let H=t.getAll();if(C&&(H=H.filter(Q=>Q.type===C)),R){let Q=R.toLowerCase();H=H.filter(Se=>Se.type.toLowerCase().includes(Q)||Se.payload.toLowerCase().includes(Q))}return H}function ne(){return C!==""||R!==""}function $e(){O=0,Z=0,N.resume(),ze.style.display="none"}function hn(H){oe.has(H)?oe.delete(H):oe.add(H),se=H;let Q=G.scrollTop,Se=N.isFollowing();xe=!0,N.pause(),Qt(),G.scrollTop=Q,Se&&N.resume(),xe=!1}function Ht(){return zo(G,50)}function Qt(){Te=Date.now(),pe=!1,Ye(),nt();let H=t.getEvictedCount();H>0?(Lt.textContent=`${H.toLocaleString()} older events truncated`,Lt.style.display=""):Lt.style.display="none",P=Ft();let Q=P.length,Se=t.getSize()>0;We&&(We.textContent=String(t.getSize())),Q===0&&Se&&ne()?(Ae.textContent=R?`No events matching '${R}'`:"No events matching filter",Ae.style.display="",G.style.display="none"):(Ae.style.display="none",G.style.display=""),V&&(V.title=ne()?`Copy Filtered (${Q})`:"Copy All"),d&&!N.isFollowing()&&Q>O&&(Z+=Q-O,we.textContent=p?`${p}${Z>0?` (${Z})`:""}`:"",ze.style.display=""),O=Q;let lt=t.getAll(),Qe=lt.length>0?lt[0].timestamp:0,jt=new Set(P.map(vt=>vt.id));for(let vt of oe)jt.has(vt)||oe.delete(vt);let yn=C!==de||R!==ae,xt=be.size===0&&P.length>0;if(yn||xt||P.length===0){G.innerHTML="",be.clear();let vt=document.createDocumentFragment();for(let It=0;It<P.length;It++){let wt=El(P[It],It,Qe,u,oe,hn,s,o);be.set(P[It].id,wt),vt.appendChild(wt)}G.appendChild(vt),de=C,ae=R,se=null}else{if(se!==null){let It=be.get(se);if(It&&It.parentNode===G){let wt=P.findIndex(dn=>dn.id===se);if(wt>=0){let dn=El(P[wt],wt,Qe,u,oe,hn,s,o);G.insertBefore(dn,It),It.remove(),be.set(se,dn)}}se=null}let vt=new Set(P.map(It=>It.id));for(let[It,wt]of be)vt.has(It)||(wt.remove(),be.delete(It));for(let It=0;It<P.length;It++){let wt=P[It];if(!be.has(wt.id)){let dn=El(wt,It,Qe,u,oe,hn,s,o);be.set(wt.id,dn),G.appendChild(dn)}}}N.isFollowing()&&(G.scrollTop=G.scrollHeight)}function Dr(){if(Date.now()-Te>=Cv){ee!==null&&(cancelAnimationFrame(ee),ee=null),Qt();return}pe||(pe=!0,ee=requestAnimationFrame(()=>{ee=null,Qt()}))}let br=(H,Q)=>{if(!V)return;V.innerHTML="";let Se=me(H,"12px","currentColor",1.5);Se&&V.appendChild(Se);let lt=y("span","persona-text-xs");lt.textContent="Copy All",V.appendChild(lt),setTimeout(()=>{V.innerHTML="";let Qe=me("clipboard-copy","12px","currentColor",1.5);Qe&&V.appendChild(Qe);let jt=y("span","persona-text-xs");jt.textContent="Copy All",V.appendChild(jt),V.disabled=!1},Q)},A=async()=>{if(V){V.disabled=!0;try{let H;ne()?H=P:n?(H=await n(),H.length===0&&(H=t.getAll())):H=t.getAll();let Q=H.map(Se=>{try{return JSON.parse(Se.payload)}catch{return Se.payload}});await navigator.clipboard.writeText(JSON.stringify(Q,null,2)),br("check",1500)}catch{br("x",1500)}}},te=()=>{Oe&&(C=Oe.value,$e(),Qt())},Ee=()=>{!K||!ve||(ve.style.display=K.value?"":"none",F&&clearTimeout(F),F=setTimeout(()=>{R=K.value,$e(),Qt()},150))},Be=()=>{!K||!ve||(K.value="",R="",ve.style.display="none",F&&clearTimeout(F),$e(),Qt())},Le=()=>{if(xe)return;let H=G.scrollTop,{action:Q,nextLastScrollTop:Se}=Ya({following:N.isFollowing(),currentScrollTop:H,lastScrollTop:Me,nearBottom:Ht(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});Me=Se,Q==="resume"?(N.resume(),Z=0,ze.style.display="none"):Q==="pause"&&(N.pause(),d&&(we.textContent=p,ze.style.display=""))},De=H=>{let Q=Za({following:N.isFollowing(),deltaY:H.deltaY,nearBottom:Ht(),resumeWhenNearBottom:!0});Q==="pause"?(N.pause(),d&&(we.textContent=p,ze.style.display="")):Q==="resume"&&(N.resume(),Z=0,ze.style.display="none")},Ge=()=>{d&&(G.scrollTop=G.scrollHeight,N.resume(),Z=0,ze.style.display="none")},it=H=>{let Q=H.target;if(!Q||Q.closest("button"))return;let Se=Q.closest("[data-event-id]");if(!Se)return;let lt=Se.getAttribute("data-event-id");lt&&hn(lt)},Pt=H=>{if((H.metaKey||H.ctrlKey)&&H.key==="f"){H.preventDefault(),K==null||K.focus(),K==null||K.select();return}H.key==="Escape"&&(K&&document.activeElement===K?(Be(),K.blur(),M.focus()):r&&r())};V&&V.addEventListener("click",A),Oe&&Oe.addEventListener("change",te),K&&K.addEventListener("input",Ee),ve&&ve.addEventListener("click",Be),G.addEventListener("scroll",Le),G.addEventListener("wheel",De,{passive:!0}),G.addEventListener("click",it),ze.addEventListener("click",Ge),M.addEventListener("keydown",Pt);function bt(){F&&clearTimeout(F),ee!==null&&(cancelAnimationFrame(ee),ee=null),pe=!1,be.clear(),V&&V.removeEventListener("click",A),Oe&&Oe.removeEventListener("change",te),K&&K.removeEventListener("input",Ee),ve&&ve.removeEventListener("click",Be),G.removeEventListener("scroll",Le),G.removeEventListener("wheel",De),G.removeEventListener("click",it),ze.removeEventListener("click",Ge),M.removeEventListener("keydown",Pt)}return{element:M,update:Dr,destroy:bt}}}function bg(e,t){let n=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",r=typeof e.artifactId=="string"?e.artifactId:"",o=e.status==="streaming"?"streaming":"complete",a=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${n} in artifact panel`),r&&i.setAttribute("data-open-artifact",r);let d=document.createElement("div");d.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",d.style.border="1px solid var(--persona-border, #e5e7eb)",d.style.color="var(--persona-muted, #9ca3af)",d.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=n;let u=document.createElement("div");if(u.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",u.style.color="var(--persona-muted, #9ca3af)",o==="streaming"){let g=document.createElement("span");g.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",g.style.backgroundColor="var(--persona-primary, #171717)",g.style.animation="persona-pulse 1.5s ease-in-out infinite",u.appendChild(g);let f=document.createElement("span");f.textContent=`Generating ${a.toLowerCase()}...`,u.appendChild(f)}else u.textContent=a;if(l.append(p,u),i.append(d,l),o==="complete"){let g=document.createElement("button");g.type="button",g.textContent="Download",g.title=`Download ${n}`,g.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",g.style.border="1px solid var(--persona-border, #e5e7eb)",g.style.color="var(--persona-text, #1f2937)",g.style.backgroundColor="transparent",g.style.cursor="pointer",g.setAttribute("data-download-artifact",r),i.append(g)}return i}var xg=(e,t)=>{var r,o,s;let n=(s=(o=(r=t==null?void 0:t.config)==null?void 0:r.features)==null?void 0:o.artifacts)==null?void 0:s.renderCard;if(n){let a=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",d=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=n({artifact:{artifactId:i,title:a,artifactType:l,status:d},config:t.config,defaultRenderer:()=>bg(e,t)});if(p)return p}return bg(e,t)};var Ml=class{constructor(){this.components=new Map}register(t,n){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,n)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([n,r])=>{this.register(n,r)})}},vo=new Ml;vo.register("PersonaArtifactCard",xg);function Rv(e){var o;let t=y("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),n=y("div","persona-font-semibold persona-text-sm persona-mb-2");n.textContent=e.component?`Component: ${e.component}`:"Component";let r=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return r.textContent=JSON.stringify((o=e.props)!=null?o:{},null,2),t.appendChild(n),t.appendChild(r),t}function vg(e,t){var Oe,V,K,ve;let n=(V=(Oe=e.features)==null?void 0:Oe.artifacts)==null?void 0:V.layout,o=((K=n==null?void 0:n.toolbarPreset)!=null?K:"default")==="document",s=(ve=n==null?void 0:n.panePadding)==null?void 0:ve.trim(),a=e.markdown?us(e.markdown):null,i=$s(e.sanitize),d=J=>{let ce=a?a(J):Kr(J);return i?i(ce):ce},l=typeof document!="undefined"?y("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"),O==null||O.hide()};l&&l.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let u=y("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");u.setAttribute("data-persona-theme-zone","artifact-pane"),o&&u.classList.add("persona-artifact-pane-document");let g=y("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");g.setAttribute("data-persona-theme-zone","artifact-toolbar"),o&&g.classList.add("persona-artifact-toolbar-document");let f=y("span","persona-text-xs persona-font-medium persona-truncate");f.textContent="Artifacts";let v=y("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");v.type="button",v.textContent="Close",v.setAttribute("aria-label","Close artifacts panel"),v.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let x="rendered",E=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),T=o?Gt({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):Gt({icon:"eye",label:"Rendered view"}),L=o?Gt({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):Gt({icon:"code-2",label:"Source"}),k=y("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),M=(n==null?void 0:n.documentToolbarShowCopyLabel)===!0,P=(n==null?void 0:n.documentToolbarShowCopyChevron)===!0,C=n==null?void 0:n.documentToolbarCopyMenuItems,R=!!(P&&C&&C.length>0),F=null,j,W=null,O=null;if(o&&(M||P)&&!R){if(j=M?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),P){let J=me("chevron-down",14,"currentColor",2);J&&j.appendChild(J)}}else o&&R?(F=y("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),j=M?si({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),W=Gt({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"}}),F.append(j,W)):o?j=Gt({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):j=Gt({icon:"copy",label:"Copy"});let N=o?Gt({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"refresh-cw",label:"Refresh"}),Z=o?Gt({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):Gt({icon:"x",label:"Close"}),Te=()=>{var Ke,tt,Lt;let J=(Ke=be.find(Ye=>Ye.id===de))!=null?Ke:be[be.length-1],ce=(tt=J==null?void 0:J.id)!=null?tt:null,Re=(J==null?void 0:J.artifactType)==="markdown"&&(Lt=J.markdown)!=null?Lt:"",ge=J?JSON.stringify({component:J.component,props:J.props},null,2):"";return{markdown:Re,jsonPayload:ge,id:ce}},pe=async()=>{var Ke;let{markdown:J,jsonPayload:ce}=Te(),Re=(Ke=be.find(tt=>tt.id===de))!=null?Ke:be[be.length-1],ge=(Re==null?void 0:Re.artifactType)==="markdown"?J:Re?ce:"";try{await navigator.clipboard.writeText(ge)}catch{}};if(j.addEventListener("click",async()=>{let J=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;if(J&&R){let{markdown:ce,jsonPayload:Re,id:ge}=Te();try{await J({actionId:"primary",artifactId:ge,markdown:ce,jsonPayload:Re})}catch{}return}await pe()}),W&&(C!=null&&C.length)){let J=()=>{var Re;return(Re=u.closest("[data-persona-root]"))!=null?Re:document.body},ce=()=>{O=Vo({items:C.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:ge,jsonPayload:Ke,id:tt}=Te(),Lt=n==null?void 0:n.onDocumentToolbarCopyMenuSelect;try{Lt?await Lt({actionId:Re,artifactId:tt,markdown:ge,jsonPayload:Ke}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(ge):Re==="json"||Re==="source"?await navigator.clipboard.writeText(Ke):await navigator.clipboard.writeText(ge||Ke)}catch{}},anchor:F!=null?F:W,position:"bottom-right",portal:J()})};u.isConnected?ce():requestAnimationFrame(ce),W.addEventListener("click",Re=>{Re.stopPropagation(),O==null||O.toggle()})}N.addEventListener("click",async()=>{var J;try{await((J=n==null?void 0:n.onDocumentToolbarRefresh)==null?void 0:J.call(n))}catch{}se()}),Z.addEventListener("click",()=>{var J;p(),(J=t.onDismiss)==null||J.call(t)});let ee=()=>{o&&(T.setAttribute("aria-pressed",x==="rendered"?"true":"false"),L.setAttribute("aria-pressed",x==="source"?"true":"false"))};T.addEventListener("click",()=>{x="rendered",ee(),se()}),L.addEventListener("click",()=>{x="source",ee(),se()});let xe=y("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");o?(g.replaceChildren(),E.append(T,L),F?k.append(F,N,Z):k.append(j,N,Z),g.append(E,xe,k),ee()):(g.appendChild(f),g.appendChild(v)),s&&(g.style.paddingLeft=s,g.style.paddingRight=s);let Me=y("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"),oe=y("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");s&&(Me.style.paddingLeft=s,Me.style.paddingRight=s,oe.style.padding=s),u.appendChild(g),u.appendChild(Me),u.appendChild(oe);let be=[],de=null,ae=!1,se=()=>{var ge,Ke,tt,Lt;let J=o&&be.length<=1;Me.classList.toggle("persona-hidden",J),Me.replaceChildren();for(let Ye of be){let _e=y("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");_e.type="button",_e.textContent=Ye.title||Ye.id.slice(0,8),Ye.id===de&&_e.classList.add("persona-bg-persona-container","persona-border-persona-border"),_e.addEventListener("click",()=>t.onSelect(Ye.id)),Me.appendChild(_e)}oe.replaceChildren();let ce=de&&be.find(Ye=>Ye.id===de)||be[be.length-1];if(!ce)return;if(o){let Ye=ce.artifactType==="markdown"?"MD":(ge=ce.component)!=null?ge:"Component",G=(ce.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";xe.textContent=`${G} \xB7 ${Ye}`}else f.textContent="Artifacts";if(ce.artifactType==="markdown"){if(o&&x==="source"){let _e=y("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");_e.textContent=(Ke=ce.markdown)!=null?Ke:"",oe.appendChild(_e);return}let Ye=y("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");Ye.innerHTML=d((tt=ce.markdown)!=null?tt:""),oe.appendChild(Ye);return}let Re=ce.component?vo.get(ce.component):void 0;if(Re){let _e={message:{id:ce.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let G=Re((Lt=ce.props)!=null?Lt:{},_e);if(G){oe.appendChild(G);return}}catch{}}oe.appendChild(Rv(ce))},We=()=>{var ce;let J=be.length>0;if(u.classList.toggle("persona-hidden",!J),l){let Re=typeof u.closest=="function"?u.closest("[data-persona-root]"):null,Ke=((ce=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?ce:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;J&&Ke&&ae?(l.classList.remove("persona-hidden"),u.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open"))}};return{element:u,backdrop:l,update(J){var ce,Re,ge;be=J.artifacts,de=(ge=(Re=J.selectedId)!=null?Re:(ce=J.artifacts[J.artifacts.length-1])==null?void 0:ce.id)!=null?ge:null,be.length>0&&(ae=!0),se(),We()},setMobileOpen(J){ae=J,!J&&l?(l.classList.add("persona-hidden"),u.classList.remove("persona-artifact-drawer-open")):We()}}}function ir(e){var t,n;return((n=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:n.enabled)===!0}function wg(e,t){var s,a,i,d;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!ir(t))return;let n=(a=(s=t.features)==null?void 0:s.artifacts)==null?void 0:a.layout,r=(i=n==null?void 0:n.paneBorder)==null?void 0:i.trim(),o=(d=n==null?void 0:n.paneBorderLeft)==null?void 0:d.trim();r?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",r)):o&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",o))}function Wv(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 hi(e,t){var d,l,p,u,g,f,v,x,E,T;if(!ir(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Wv(e),wg(e,t);return}let n=(l=(d=t.features)==null?void 0:d.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=n==null?void 0:n.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(u=n==null?void 0:n.paneWidth)!=null?u:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(g=n==null?void 0:n.paneMaxWidth)!=null?g:"28rem"),n!=null&&n.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",n.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let r=(f=n==null?void 0:n.paneBackground)==null?void 0:f.trim();r?e.style.setProperty("--persona-artifact-pane-bg",r):e.style.removeProperty("--persona-artifact-pane-bg");let o=(v=n==null?void 0:n.panePadding)==null?void 0:v.trim();o?e.style.setProperty("--persona-artifact-pane-padding",o):e.style.removeProperty("--persona-artifact-pane-padding");let s=(x=n==null?void 0:n.documentToolbarIconColor)==null?void 0:x.trim();s?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",s):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let a=(E=n==null?void 0:n.documentToolbarToggleActiveBackground)==null?void 0:E.trim();a?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",a):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(T=n==null?void 0:n.documentToolbarToggleActiveBorderColor)==null?void 0:T.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),wg(e,t)}var Cg=["panel","seamless"];function yi(e,t){var i,d,l,p,u,g;for(let f of Cg)e.classList.remove(`persona-artifact-appearance-${f}`);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"),!ir(t))return;let n=(d=(i=t.features)==null?void 0:i.artifacts)==null?void 0:d.layout,r=(l=n==null?void 0:n.paneAppearance)!=null?l:"panel",o=Cg.includes(r)?r:"panel";e.classList.add(`persona-artifact-appearance-${o}`);let s=(p=n==null?void 0:n.paneBorderRadius)==null?void 0:p.trim();s&&e.style.setProperty("--persona-artifact-pane-radius",s);let a=(u=n==null?void 0:n.paneShadow)==null?void 0:u.trim();if(a&&e.style.setProperty("--persona-artifact-pane-shadow",a),(n==null?void 0:n.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let f=((g=n.unifiedSplitOuterRadius)==null?void 0:g.trim())||s;f&&e.style.setProperty("--persona-artifact-unified-outer-radius",f)}}function Ag(e,t){var n,r,o;return!t||!ir(e)?!1:((o=(r=(n=e.features)==null?void 0:n.artifacts)==null?void 0:r.layout)==null?void 0:o.expandLauncherPanelWhenOpen)!==!1}function Hv(e,t){if(!(e!=null&&e.trim()))return t;let n=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return n?Math.max(0,Number(n[1])):t}function Bv(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function Dv(e,t,n){return n<t?t:Math.min(n,Math.max(t,e))}function Nv(e,t,n,r){let o=e-r-2*t-n;return Math.max(0,o)}function Sg(e,t){var a;let r=(a=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?a:"0px",o=/^([\d.]+)px$/i.exec(r);if(o)return Number(o[1]);let s=/^([\d.]+)/.exec(r);return s?Number(s[1]):8}function Tg(e,t,n,r,o,s){let a=Hv(o,200),i=Nv(t,n,r,200);i=Math.max(a,i);let d=Bv(s);return d!==null&&(i=Math.min(i,d)),Dv(e,a,i)}var Eg={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"}},kl=(e,t,n,r)=>{let o=e.querySelectorAll("[data-tv-form]");o.length&&o.forEach(s=>{var v,x,E;if(s.dataset.enhanced==="true")return;let a=(v=s.dataset.tvForm)!=null?v:"init";s.dataset.enhanced="true";let i=(x=Eg[a])!=null?x:Eg.init;s.classList.add("persona-form-card","persona-space-y-4");let d=y("div","persona-space-y-1"),l=y("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,d.appendChild(l),i.description){let T=y("p","persona-text-sm persona-text-persona-muted");T.textContent=i.description,d.appendChild(T)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(T=>{var C,R;let L=y("label","persona-form-field persona-flex persona-flex-col persona-gap-1");L.htmlFor=`${t.id}-${a}-${T.name}`;let k=y("span","persona-text-xs persona-font-medium persona-text-persona-muted");k.textContent=T.label,L.appendChild(k);let M=(C=T.type)!=null?C:"text",P;M==="textarea"?(P=document.createElement("textarea"),P.rows=3):(P=document.createElement("input"),P.type=M),P.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",P.id=`${t.id}-${a}-${T.name}`,P.name=T.name,P.placeholder=(R=T.placeholder)!=null?R:"",T.required&&(P.required=!0),L.appendChild(P),p.appendChild(L)});let u=y("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),g=y("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),f=y("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");f.type="submit",f.textContent=(E=i.submitLabel)!=null?E:"Submit",u.appendChild(g),u.appendChild(f),p.appendChild(u),s.replaceChildren(d,p),p.addEventListener("submit",async T=>{var P,C;T.preventDefault();let L=(P=n.formEndpoint)!=null?P:"/form",k=new FormData(p),M={};k.forEach((R,F)=>{M[F]=R}),M.type=a,f.disabled=!0,g.textContent="Submitting\u2026";try{let R=await fetch(L,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(M)});if(!R.ok)throw new Error(`Form submission failed (${R.status})`);let F=await R.json();g.textContent=(C=F.message)!=null?C:"Thanks! We'll be in touch soon.",F.success&&F.nextPrompt&&await r.sendMessage(String(F.nextPrompt))}catch(R){g.textContent=R instanceof Error?R.message:"Something went wrong. Please try again."}finally{f.disabled=!1}})})};var Ll=class{constructor(){this.plugins=new Map}register(t){var n;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(n=t.onRegister)==null||n.call(t)}unregister(t){var r;let n=this.plugins.get(t);n&&((r=n.onUnregister)==null||r.call(n),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,n)=>{var r,o;return((r=n.priority)!=null?r:0)-((o=t.priority)!=null?o:0)})}getForInstance(t){let n=this.getAll();if(!t||t.length===0)return n;let r=new Set(t.map(s=>s.id));return[...n.filter(s=>!r.has(s.id)),...t].sort((s,a)=>{var i,d;return((i=a.priority)!=null?i:0)-((d=s.priority)!=null?d:0)})}clear(){this.plugins.forEach(t=>{var n;return(n=t.onUnregister)==null?void 0:n.call(t)}),this.plugins.clear()}},bi=new Ll;var Mg=()=>{let e=new Map,t=(o,s)=>(e.has(o)||e.set(o,new Set),e.get(o).add(s),()=>n(o,s)),n=(o,s)=>{var a;(a=e.get(o))==null||a.delete(s)};return{on:t,off:n,emit:(o,s)=>{var a;(a=e.get(o))==null||a.forEach(i=>{try{i(s)}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",d)}})}}};var Ov=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Fv=e=>{let t=e.trim(),n=t.indexOf("{");if(n===-1)return null;let r=0;for(let o=n;o<t.length;o+=1){let s=t[o];if(s==="{"&&(r+=1),s==="}"&&(r-=1,r===0))return t.slice(n,o+1)}return null},xi=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Ov(e),n=Fv(t);if(!n)return null;let r=JSON.parse(n);if(!r||typeof r!="object"||!r.action)return null;let{action:o,...s}=r;return{type:String(o),payload:s,raw:r}}catch{return null}},Pl=e=>typeof e=="string"?e:e==null?"":String(e),Es={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:Pl(e.payload.text)},messageAndClick:(e,t)=>{var o;if(e.type!=="message_and_click")return;let n=e.payload,r=Pl(n.element);if(r&&((o=t.document)!=null&&o.querySelector)){let s=t.document.querySelector(r);s?setTimeout(()=>{s.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",r)}return{handled:!0,displayText:Pl(n.text)}}},kg=e=>Array.isArray(e)?e.map(t=>String(t)):[],vi=e=>{let t=new Set(kg(e.getSessionMetadata().processedActionMessageIds)),n=()=>{t=new Set(kg(e.getSessionMetadata().processedActionMessageIds))},r=()=>{let s=Array.from(t);e.updateSessionMetadata(a=>({...a,processedActionMessageIds:s}))};return{process:s=>{if(s.streaming||s.message.role!=="assistant"||!s.text||t.has(s.message.id))return null;let a=typeof s.raw=="string"&&s.raw||typeof s.message.rawContent=="string"&&s.message.rawContent||typeof s.text=="string"&&s.text||null;!a&&typeof s.text=="string"&&s.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=a?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:a,message:s.message}))||null,null):null;if(!i)return null;t.add(s.message.id),r();let d={action:i,message:s.message};e.emit("action:detected",d);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",d)},u=l(i,{message:s.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!u)continue;if(u.handled){let g=u.persistMessage!==!1;return{text:u.displayText!==void 0?u.displayText:"",persist:g,resubmit:u.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:n}};var _v=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},$v=e=>e.map(t=>({...t,streaming:!1})),jv=e=>e.map(t=>({...t,status:"complete"})),Il=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let n=t();return n?_v(n.getItem(e)):null},save:n=>{let r=t();if(r)try{let o={...n,messages:n.messages?$v(n.messages):void 0,artifacts:n.artifacts?jv(n.artifacts):void 0};r.setItem(e,JSON.stringify(o))}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",o)}},clear:()=>{let n=t();if(n)try{n.removeItem(e)}catch(r){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",r)}}}};import{parse as Uv,STR as qv,OBJ as zv}from"partial-json";function Vv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function Kv(e,t){if(!Vv(e))return null;let n=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:n,raw:t}}function Rl(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e;try{let o=Uv(n,qv|zv),s=Kv(o,n);s&&(e=s)}catch{}return t=n.length,e},reset:()=>{e=null,t=0}}}function Gv(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function Wl(e,t){let{config:n,message:r,onPropsUpdate:o}=t,s=vo.get(e.component);if(!s)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let a={message:r,config:n,updateProps:i=>{o&&o(i)}};try{return s(e.props,a)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function Jv(){let e=Rl();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function Lg(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function Hl(e){let t=Lg(e);if(!t)return!1;try{let n=JSON.parse(t);return typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"}catch{return!1}}function Bl(e){let t=Lg(e);if(!t)return null;try{let n=JSON.parse(t);if(typeof n=="object"&&n!==null&&"component"in n&&typeof n.component=="string"){let r=n;return{component:r.component,props:r.props&&typeof r.props=="object"&&r.props!==null?r.props:{},raw:t}}}catch{}return null}var Xv=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function Dl(e){let{onSubmit:t,onDismiss:n,title:r="How satisfied are you?",subtitle:o="Please rate your experience",commentPlaceholder:s="Share your thoughts (optional)...",submitText:a="Submit",skipText:i="Skip",showComment:d=!0,ratingLabels:l=Xv}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let u=null,g=document.createElement("div");g.className="persona-feedback-content";let f=document.createElement("div");f.className="persona-feedback-header";let v=document.createElement("h3");v.className="persona-feedback-title",v.textContent=r,f.appendChild(v);let x=document.createElement("p");x.className="persona-feedback-subtitle",x.textContent=o,f.appendChild(x),g.appendChild(f);let E=document.createElement("div");E.className="persona-feedback-rating persona-feedback-rating-csat",E.setAttribute("role","radiogroup"),E.setAttribute("aria-label","Satisfaction rating from 1 to 5");let T=[];for(let C=1;C<=5;C++){let R=document.createElement("button");R.type="button",R.className="persona-feedback-rating-btn persona-feedback-star-btn",R.setAttribute("role","radio"),R.setAttribute("aria-checked","false"),R.setAttribute("aria-label",`${C} star${C>1?"s":""}: ${l[C-1]}`),R.title=l[C-1],R.dataset.rating=String(C),R.innerHTML=`