@runtypelabs/persona 4.6.0 → 4.6.1

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.
@@ -8,14 +8,14 @@ ${e}`:"")+(n.description?`
8
8
  ${n.description}`:"");return window.confirm(t)},Xg=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},Jg=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Yg=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var Zg="agent_",ef="flow_";function pu(n){return n.startsWith(Zg)?{kind:"agentId",agentId:n}:n.startsWith(ef)?{kind:"flowId",flowId:n}:null}function uu(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),i=t.slice(r+1);if(a==="runtype"){let c=pu(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[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=pu(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}import{parse as tf,ARR as nf,OBJ as rf,STR as of}from"partial-json";var b=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Pr=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},Os=(...n)=>n.filter(Boolean).join(" ");var wi="ask_user_question",_s=8,is="data-persona-ask-sheet-for",sf="Other",af="Other\u2026",gu="Type your own answer here",fu="Send",lf="Next",cf="Back",df="Submit all",pf="Skip",uf=3,xi="data-ask-current-index",Ci="data-ask-question-count",hu="data-ask-answers",Ai="data-ask-grouped",yu="data-ask-layout",mf=n=>n.layout==="pills"?"pills":"rows",gf=n=>n.getAttribute(yu)==="pills"?"pills":"rows",mu=!1,bu=n=>n.replace(/["\\]/g,"\\$&"),Fo=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===wi,Si=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ls=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=tf(o,of|rf|nf);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},$s=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>_s&&!mu&&(mu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${_s}.`)),e.slice(0,_s)},ff=n=>{var e;return(e=$s(n)[0])!=null?e:null},hf=(n,e)=>{var t;return(t=$s(n)[e])!=null?t:null},yf=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},vu=(n,e,t)=>{if(n!=="rows")return null;let r=b("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=b("span","persona-ask-row-check");r.appendChild(o)}else{let o=b("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},bf=(n,e,t,r)=>{let s=b("button",t==="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(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=b("span","persona-ask-row-content"),i=b("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=b("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=vu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},vf=n=>{let t=b("span",n==="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 t.setAttribute("aria-hidden","true"),t},wf=(n,e,t,r)=>{var u,g,h;let s=b("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=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<uf;m++)s.appendChild(vf(r));return s}if(d.forEach((m,v)=>{s.appendChild(bf(m,v,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?sf:af;if(r==="rows"){let v=b("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 w=b("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(u=e.freeTextPlaceholder)!=null?u:gu,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(T),v.appendChild(w);let B=vu(r,a,d.length);B&&v.appendChild(B),s.appendChild(v)}else{let v=b("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=(h=e.freeTextLabel)!=null?h:m,s.appendChild(v)}}return s},wu=(n,e)=>{var s,a;let r=b("div",e==="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=n.freeTextPlaceholder)!=null?s:gu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=b("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:fu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},xf=n=>{var r;let e=b("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=b("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:fu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Cf=(n,e,t)=>{var c,u,g,h;let r=b("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=b("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:cf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=b("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=b("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(u=t.skipLabel)!=null?u:pf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=b("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(g=t.submitAllLabel)!=null?g:df:(h=t.nextLabel)!=null?h:lf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Oo=n=>{let e=n.getAttribute(hu);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},xu=(n,e)=>{n.setAttribute(hu,JSON.stringify(e))},er=n=>{var t;let e=Number((t=n.getAttribute(xi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Af=(n,e)=>{n.setAttribute(xi,String(Math.max(0,Math.floor(e))))},cs=n=>{var t;let e=Number((t=n.getAttribute(Ci))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},go=n=>n.getAttribute(Ai)==="true",Sf=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Tf=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},xa=(n,e)=>{let{payload:t}=ls(e),r=$s(t),o=Oo(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Cu=n=>{let e=Oo(n),t=er(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",u=o.has(c);d.setAttribute("aria-pressed",u?"true":"false"),d.classList.toggle("persona-ask-pill-selected",u)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.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=""},Au=n=>{if(!go(n))return;let e=Oo(n),t=er(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ti=(n,e,t)=>{let r=Si(t),o=gf(n),{payload:s,complete:a}=ls(e),i=go(n),d=er(n),c=cs(n),u=i?hf(s,d):ff(s),g=!!(u!=null&&u.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let v=n.querySelector('[data-ask-question="true"]');if(v){let S=typeof(u==null?void 0:u.question)=="string"?u.question:"";v.textContent=S,v.classList.toggle("persona-ask-question-skeleton",!S&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let S=wf(u,r,a,o);w.replaceWith(S)}if(o!=="rows"){let S=n.querySelector('[data-ask-free-text-row="true"]');S&&S.replaceWith(wu(r,o))}let T=n.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!T?n.appendChild(xf(r)):(!g||i)&&T&&T.remove(),n.setAttribute("data-multi-select",g?"true":"false");let B=n.querySelector('[data-ask-nav-row="true"]');if(i){let S=Cf(d,c,r);B?B.replaceWith(S):n.appendChild(S)}else B&&B.remove();Cu(n),Au(n)},Mf=(n,e,t)=>{let r=Si(e),o=mf(r),s=n.toolCall.id,a=$s(t),i=Math.max(1,a.length),d=i>1,c=Sf(n,a),u=d?Tf(n,i):0,g=b("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(is,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(Ci,String(i)),g.setAttribute(xi,String(u)),g.setAttribute(Ai,d?"true":"false"),g.setAttribute(yu,o),xu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),yf(g,r);let h=b("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=b("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let v=b("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",h.appendChild(v),g.appendChild(h);let T=b("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 T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),g.appendChild(T),o!=="rows"&&g.appendChild(wu(r,o)),Ti(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Ef=(n,e,t)=>{let{payload:r}=ls(e),o=Math.max(1,$s(r).length);o>cs(n)&&(n.setAttribute(Ci,String(o)),o>1&&!go(n)&&n.setAttribute(Ai,"true")),Ti(n,e,t)};var Ca=(n,e,t)=>{if(!t||!Fo(n)||Si(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${is}]`).forEach(c=>{c.getAttribute(is)!==o&&c.remove()});let a=t.querySelector(`[${is}="${bu(o)}"]`);if(a){Ef(a,n,e);return}let{payload:i}=ls(n),d=Mf(n,e,i);t.appendChild(d)},ds=(n,e)=>{if(!n)return;let t=e?`[${is}="${bu(e)}"]`:`[${is}]`;n.querySelectorAll(t).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)})},Mi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),fo=(n,e)=>{let t=Oo(n),r=er(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,xu(n,t),Cu(n),Au(n)},Aa=(n,e,t,r)=>{let o=cs(n),s=Math.max(0,Math.min(o-1,r));Af(n,s),Ti(n,e,t)};var zr="suggest_replies";var kf={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},Su={name:zr,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:kf,origin:"sdk",annotations:{readOnlyHint:!0}},Ei=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ki=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===zr},Lf=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.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},Tu=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!ki(r))continue;let o=Lf((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},Mu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var Pf={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:_s,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},If={name:wi,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:Pf,origin:"sdk",annotations:{readOnlyHint:!0}},Li=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(If),Mu(n)&&e.push(Su),e};import{parse as Wf,STR as Rf,OBJ as Hf}from"partial-json";var Eu=n=>n.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ho=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},Bf=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},ku=n=>n.status==="complete"?Bf(n):n.status==="pending"?"Waiting":"",Df=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var Lu=n=>n.status==="complete"?Df(n):"Using tool...",Sa=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},zs=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Sa(e)},Ta=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Sa(e)},Pi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=zs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Ma=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Us(r,t.slice(s,a.index),[]),a[1]!==void 0?Us(r,a[1],["bold"]):a[2]!==void 0?Us(r,a[2],["italic"]):a[3]!==void 0&&Us(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Us(r,t.slice(s),[]),r},Us=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},Nf=()=>{let n=null,e=0,t=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:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Pu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Iu=()=>{var e;let n=Nf();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Wu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=Wf(t,Rf|Hf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Eu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Eu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Ru=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Hu="4.6.0";var js=Hu;var Of="https://api.runtype.com/v1/dispatch",Ea="https://api.runtype.com";function _f(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.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 Ii=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function $f(n){switch(n){case"json":return Wu;case"regex-json":return Iu;case"xml":return Ru;default:return Pu}}var Bu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Uf(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Bu(t);if(!Bu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=qs(n);return qs(e)!==null&&a===null?e:n}var Vs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:Of,this.headers={"Content-Type":"application/json","X-Persona-Version":js,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:$f(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new wa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=uu(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(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},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(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(Ii).map(M=>{var k,C,P;return{id:M.id,role:M.role,content:(P=(C=(k=M.contentParts)!=null?k:M.llmContent)!=null?C:M.rawContent)!=null?P:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},h=c.clientTools,m=!!(h&&h.length>0),v=m?cu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&w&&this.lastSentClientToolsFingerprint===v,B=!1,S=null,L;for(let M=0;;M++){let C={...g,...m&&(B||!T)&&h?{clientTools:h}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(C),signal:r.signal}),L.status===409&&M===0&&m){let P=await L.json().catch(()=>null);if((P==null?void 0:P.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}S=P!=null?P:{error:"Chat request failed"}}break}if(!L.ok){let M=S!=null?S:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(L.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let k=new Error(M.error||"Failed to send message");throw t({type:"error",error:k}),k}if(!L.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ea}/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:e,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!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(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Ii).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let g=new Date(c.createdAt).getTime(),h=new Date(u.createdAt).getTime();return g-h}).map(c=>{var u,g,h;return{role:c.role,content:(h=(g=(u=c.contentParts)!=null?u:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Li(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 c={};await Promise.all(this.contextProviders.map(async u=>{try{let g=await u({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(Ii).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return u-g}).map(d=>{var c,u,g;return{role:d.role,content:(g=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Li(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 c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),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 c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=g,o(g),g},c=u=>r.current?r.current:d(u);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 u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var gn,fr,hr,Ue;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,u=()=>d+c++,g=E=>{let me=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,Me=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,ke=E.tools?E.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...E,reasoning:me,toolCall:Me,tools:ke}},h=E=>{if(E.role!=="assistant"||E.variant)return!0;let me=Array.isArray(E.contentParts)&&E.contentParts.length>0,Me=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||me||Me||!!E.stopReason},m=E=>{h(E)&&t({type:"message",message:g(E)})},v=null,w=null,T={current:null},B={current:null},S=null,L="",M=new Map,k=new Map,C=new Map,P=new Map,U=new Map,_={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},$=E=>{if(E==null)return null;try{return String(E)}catch{return null}},N=E=>{var me,Me,ke,Re,tt;return $((tt=(Re=(ke=(Me=(me=E.stepId)!=null?me:E.step_id)!=null?Me:E.step)!=null?ke:E.parentId)!=null?Re:E.flowStepId)!=null?tt:E.flow_step_id)},te=E=>{var me,Me,ke,Re,tt,Qe,ht;return $((ht=(Qe=(tt=(Re=(ke=(Me=(me=E.callId)!=null?me:E.call_id)!=null?Me:E.requestId)!=null?ke:E.request_id)!=null?Re:E.toolCallId)!=null?tt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ht:E.step_id)},Ee=r,de=!1,Y=()=>{if(v)return v;let E,me="",Me=S;return!de&&Ee?(E=Ee,de=!0,me=o!=null?o:""):Ee&&Me?E=`${Ee}_${Me}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:E,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(v),v},Le=(E,me)=>{_.lastId=me,E&&_.byStep.set(E,me)},Pe=(E,me)=>{var tt;let Me=(tt=E.reasoningId)!=null?tt:E.id,ke=N(E);if(Me){let Qe=String(Me);return Le(ke,Qe),Qe}if(ke){let Qe=_.byStep.get(ke);if(Qe)return _.lastId=Qe,Qe}if(_.lastId&&!me)return _.lastId;if(!me)return null;let Re=`reason-${u()}`;return Le(ke,Re),Re},ae=E=>{let me=P.get(E);if(me)return me;let Me={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:E,status:"streaming",chunks:[]}};return P.set(E,Me),m(Me),Me},fe=(E,me)=>{I.lastId=me,E&&I.byCall.set(E,me)},ne=new Set,re=new Map,ce=new Set,Ce=new Map,_e=E=>{if(!E)return!1;let me=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},V=(E,me)=>{var tt;let Me=(tt=E.toolId)!=null?tt:E.id,ke=te(E);if(Me){let Qe=String(Me);return fe(ke,Qe),Qe}if(ke){let Qe=I.byCall.get(ke);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!me)return I.lastId;if(!me)return null;let Re=`tool-${u()}`;return fe(ke,Re),Re},X=E=>{let me=U.get(E);if(me)return me;let Me={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:E,status:"pending"}};return U.set(E,Me),m(Me),Me},Ae=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let me=Number(E);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Me=Date.parse(E);if(!Number.isNaN(Me))return Me}return Date.now()},J=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},ie=new Map,Se=new Map,Je=new Map,et=(E,me,Me)=>{var ht;let ke=Je.get(E);ke||(ke=[],Je.set(E,ke));let Re=0,tt=ke.length;for(;Re<tt;){let ge=Re+tt>>>1;ke[ge].seq<me?Re=ge+1:tt=ge}((ht=ke[Re])==null?void 0:ht.seq)===me?ke[Re]={seq:me,text:Me}:ke.splice(Re,0,{seq:me,text:Me});let Qe="";for(let ge=0;ge<ke.length;ge++)Qe+=ke[ge].text;return Qe},Wt=(E,me)=>{let Me=J(me),ke=Se.get(E.id),Re=Uf(ke,Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=le=>{var Ke;let gt=(Ke=E.content)!=null?Ke:"";le.trim()!==""&&(gt.trim().length===0||le.startsWith(gt)||le.trimStart().startsWith(gt.trim()))&&(E.content=le)},ht=()=>{var le;if(tt){let gt=(le=tt.close)==null?void 0:le.call(tt);gt instanceof Promise&&gt.catch(()=>{})}ie.delete(E.id),Se.delete(E.id),E.streaming=!1,m(E)};if(!tt){Qe(Me),ht();return}let ge=qs(Re);if(ge!==null&&ge.trim()!==""){Qe(ge),ht();return}let H=le=>{var Lt;let gt=typeof le=="string"?le:(Lt=le==null?void 0:le.text)!=null?Lt:null;if(gt!==null&&gt.trim()!=="")return gt;let Ke=tt.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Me},be;try{be=tt.processChunk(Re)}catch{Qe(Me),ht();return}if(be instanceof Promise){be.then(le=>{Qe(H(le)),ht()}).catch(()=>{Qe(Me),ht()});return}Qe(H(be)),ht()},ft=null,rt=(E,me,Me,ke)=>{var ge;E.rawContent=me,ie.has(E.id)||ie.set(E.id,this.createStreamParser());let Re=ie.get(E.id),tt=me.trim().startsWith("{")||me.trim().startsWith("[");if(tt&&Se.set(E.id,me),Re.__isPlainTextParser===!0){E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E);return}let ht=Re.processChunk(me);if(ht instanceof Promise)ht.then(H=>{var le;let be=typeof H=="string"?H:(le=H==null?void 0:H.text)!=null?le:null;be!==null&&be.trim()!==""?(E.content=be,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}).catch(()=>{E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E)});else{let H=typeof ht=="string"?ht:(ge=ht==null?void 0:ht.text)!=null?ge:null;H!==null&&H.trim()!==""?(E.content=H,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}},ue=(E,me)=>{var ge,H;let Me=me!=null?me:E.content;if(Me==null||Me===""){E.streaming=!1,m(E);return}let ke=Se.get(E.id),Re=ke!=null?ke:J(Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=null,ht=!1;if(tt&&(Qe=tt.getExtractedText(),Qe===null&&(Qe=qs(Re)),Qe===null)){let be=tt.processChunk(Re);be instanceof Promise?(ht=!0,be.then(le=>{var Ke;let gt=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;gt!==null&&(E.content=gt,E.streaming=!1,ie.delete(E.id),Se.delete(E.id),m(E))}).catch(()=>{})):Qe=typeof be=="string"?be:(ge=be==null?void 0:be.text)!=null?ge:null}if(!ht){Qe!==null&&Qe.trim()!==""?E.content=Qe:Se.has(E.id)||(E.content=J(Me));let be=ie.get(E.id);if(be){let le=(H=be.close)==null?void 0:H.call(be);le instanceof Promise&&le.catch(()=>{}),ie.delete(E.id)}Se.delete(E.id),E.streaming=!1,m(E)}},Q=(E,me,Me)=>{let ke=k.get(E);if(ke)return ke;let Re={id:`nested-${me}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return k.set(E,Re),m(Re),Re},it=[],je,Te=new Map,we=0,Ye="agent",qt=!1,ye=null,pe=null,wn=new Map,Ct=(gn=this.config.iterationDisplay)!=null?gn:"separate";for(je=()=>{var E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr,xe,Dr,Gn,Ot,Qn,Nr,As,Go,Ss,So,Cr,eo,lt,nn,rn,Ar,Ts,Fr,To,Sr,F,Qo,ir,Tr,Or,Mr,lr,Xo,pa,fn,Cn,cr,An,Mo,dr,hn,Er,Jo,Eo,Yo,to;for(let no=0;no<it.length;no++){let ot=it[no].payloadType,x=it[no].payload;if(!qt&&Ye!=="flow"&&typeof x.stepType=="string"&&(Ye="flow"),ot==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q),Q(j,q,"reasoning");continue}let G=(E=Pe(x,!0))!=null?E:`reason-${u()}`,K=ae(G);K.reasoning=(me=K.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Ae((Me=x.startedAt)!=null?Me:x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(ot==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let De=k.get(j),nt=(Qe=(tt=(Re=x.reasoningText)!=null?Re:x.text)!=null?tt:x.delta)!=null?Qe:"";nt&&x.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(nt)),m(De));continue}let q=(ge=(ht=Pe(x,!1))!=null?ht:Pe(x,!0))!=null?ge:`reason-${u()}`,G=ae(q);G.reasoning=(H=G.reasoning)!=null?H:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(le=G.reasoning.startedAt)!=null?le:Ae((be=x.startedAt)!=null?be:x.timestamp);let K=(Lt=(Ke=(gt=x.reasoningText)!=null?gt:x.text)!=null?Ke:x.delta)!=null?Lt:"";if(K&&x.hidden!==!0){let De=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(De!==void 0){let nt=et(q,De,String(K));G.reasoning.chunks=[nt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=x.done?"complete":"streaming",x.done){G.reasoning.completedAt=Ae((Et=x.completedAt)!=null?Et:x.timestamp);let De=(vt=G.reasoning.startedAt)!=null?vt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-De)}G.streaming=G.reasoning.status!=="complete",m(G)}else if(ot==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let nt=k.get(j);if(nt.reasoning){let ct=typeof x.text=="string"?x.text:"";ct&&nt.reasoning.chunks.length===0&&nt.reasoning.chunks.push(ct),nt.reasoning.status="complete",nt.streaming=!1,m(nt)}M.delete(j),k.delete(j);continue}let q=(Ft=(Qt=Pe(x,!1))!=null?Qt:Pe(x,!0))!=null?Ft:`reason-${u()}`,G=typeof x.text=="string"?x.text:"";!P.get(q)&&(G||x.scope==="loop")&&ae(q);let K=P.get(q);if(K!=null&&K.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Ae((Zt=x.completedAt)!=null?Zt:x.timestamp);let nt=(yr=K.reasoning.startedAt)!=null?yr:Date.now();K.reasoning.durationMs=Math.max(0,((Wr=K.reasoning.completedAt)!=null?Wr:Date.now())-nt),K.streaming=!1,m(K)}let De=N(x);De&&_.byStep.delete(De)}else if(ot==="tool_start"){v&&(v.streaming=!1,m(v),v=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(rr=(nr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?nr:V(x,!0))!=null?rr:`tool-${u()}`,q=(Vr=x.toolName)!=null?Vr:x.name;if(_e(q)){ne.add(j);continue}fe(te(x),j);let G=X(j),K=(jt=G.toolCall)!=null?jt:{id:j,status:"pending"};K.name=q!=null?q:K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=(Rr=K.startedAt)!=null?Rr:Ae((or=x.startedAt)!=null?or:x.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,x.executionId&&(G.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(G)}else if(ot==="tool_output_delta"){let j=(kn=(Hn=V(x,!1))!=null?Hn:V(x,!0))!=null?kn:`tool-${u()}`;if(ne.has(j))continue;let q=X(j),G=(Bn=q.toolCall)!=null?Bn:{id:j,status:"running"};G.startedAt=(br=G.startedAt)!=null?br:Ae((sr=x.startedAt)!=null?sr:x.timestamp);let K=(Gr=(jn=(Kr=x.text)!=null?Kr:x.delta)!=null?jn:x.message)!=null?Gr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Hr=q.agentMetadata)!=null?Hr:{executionId:(vr=De==null?void 0:De.executionId)!=null?vr:x.executionId,iteration:(wr=De==null?void 0:De.iteration)!=null?wr:x.iteration}),m(q)}else if(ot==="tool_complete"){let j=(yt=(ar=V(x,!1))!=null?ar:V(x,!0))!=null?yt:`tool-${u()}`;if(ne.has(j)){ne.delete(j);continue}let q=X(j),G=(wo=q.toolCall)!=null?wo:{id:j,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=Ae((xr=x.completedAt)!=null?xr:x.timestamp);let K=(xo=x.duration)!=null?xo:x.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((Ko=G.completedAt)!=null?Ko:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Xr=q.agentMetadata)!=null?Xr:{executionId:(Qr=De==null?void 0:De.executionId)!=null?Qr:x.executionId,iteration:(Br=De==null?void 0:De.iteration)!=null?Br:x.iteration}),m(q);let nt=te(x);nt&&I.byCall.delete(nt)}else if(ot==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,q=(Jr=j!=null?j:x.toolId)!=null?Jr:`local-${u()}`,G=X(q),K=x.toolName,De=x.origin==="webmcp"&&!as(K)?`webmcp:${K}`:K,nt=as(De),ct=(Co=G.toolCall)!=null?Co:{id:q,status:"pending"};ct.name=De,ct.args=x.parameters,ct.status=nt?"running":"complete",ct.chunks=(Ao=ct.chunks)!=null?Ao:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Ae((wt=(Yr=x.startedAt)!=null?Yr:x.timestamp)!=null?wt:x.awaitedAt),nt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=x.executionId)!=null?St:(xn=G.agentMetadata)==null?void 0:xn.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},m(G)}else if(ot==="text_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q);continue}let G=v;G&&(Ye==="flow"?(ue(G),ft=G):(G.streaming=!1,m(G)),v=null),S=typeof x.id=="string"?x.id:S,L=""}else if(ot==="text_delta"){let j=typeof x.id=="string"?x.id:null,q=j?M.get(j):void 0;if(j&&q){let K=typeof x.delta=="string"?x.delta:"",De=((Vn=C.get(j))!=null?Vn:"")+K;if(C.set(j,De),De.trim()==="")continue;let nt=Q(j,q);nt.agentMetadata={...nt.agentMetadata,executionId:x.executionId,parentToolId:q},rt(nt,De,K,void 0);continue}if(S=typeof x.id=="string"?x.id:S,Ye==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(L+=K,L.trim()==="")continue;let De=Y();De.agentMetadata={executionId:x.executionId,iteration:x.iteration},rt(De,L,K,void 0),w=De;continue}let G=Y();G.content+=(Kn=x.delta)!=null?Kn:"",G.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:ye!=null?ye:void 0,agentName:pe==null?void 0:pe.agentName},w=G,m(G)}else if(ot==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)){let G=k.get(j);G&&ue(G),M.delete(j),C.delete(j),k.delete(j);continue}let q=v;q&&(Ye==="flow"?(ue(q),ft=q):(((Fn=q.content)!=null?Fn:"")===""&&typeof x.text=="string"&&(q.content=x.text),q.streaming=!1,m(q)),v=null),S=null,L=""}else if(ot==="step_complete"){let j=x.stepType,q=x.executionType;if(j==="tool"||q==="context")continue;if(x.success===!1){let G=x.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&"message"in G?String((Zr=G.message)!=null?Zr:"Step failed"):"Step failed";t({type:"error",error:new Error(K)});let De=v;De&&De.streaming&&(De.streaming=!1,m(De)),t({type:"status",status:"idle"});continue}{let G=ft;ft=null;let K=x.stopReason,De=(xe=x.result)==null?void 0:xe.response;if(G)K&&(G.stopReason=K),De!=null?Wt(G,De):G.streaming!==!1&&(ie.delete(G.id),Se.delete(G.id),G.streaming=!1,m(G));else{let nt=De!=null&&De!=="";if(nt||K){let ct=Y();K&&(ct.stopReason=K),nt?ue(ct,De):(ct.streaming=!1,m(ct))}}continue}}else if(ot==="execution_start")Ye=x.kind==="flow"?"flow":"agent",qt=!0,Ye==="agent"&&(pe={executionId:x.executionId,agentId:(Dr=x.agentId)!=null?Dr:"virtual",agentName:(Gn=x.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ot=x.maxTurns)!=null?Ot:1,startedAt:Ae(x.startedAt)});else if(ot==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(pe&&(pe.currentIteration=j),Ct==="separate"&&j>1){let q=v;q&&(q.streaming=!1,m(q),wn.set(j-1,q),v=null)}we=j}ye=typeof x.id=="string"?x.id:null,w=null}else if(ot==="tool_input_delta"){let j=(Qn=x.toolCallId)!=null?Qn:I.lastId;if(j){let q=U.get(j);q!=null&&q.toolCall&&(q.toolCall.chunks=(Nr=q.toolCall.chunks)!=null?Nr:[],q.toolCall.chunks.push((As=x.delta)!=null?As:""),m(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=x.stopReason,q=v!=null?v:w;if(j&&q!==null){let G=x.id;(!G||((Go=q.agentMetadata)==null?void 0:Go.turnId)===G)&&(q.stopReason=j,m(q))}ye===x.id&&(ye=null)}else if(ot==="media_start"){let j=String(x.id);Te.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Te.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(ot==="media_complete"){let j=String(x.id),q=Te.get(j);Te.delete(j);let G=(So=(Ss=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ss:q==null?void 0:q.mediaType)!=null?So:"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,De=typeof x.url=="string"?x.url:q&&q.parts.length>0?q.parts.join(""):void 0,nt=null;if(K)nt={type:"media",data:K,mediaType:G};else if(De){let Pn=G.toLowerCase();nt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:De,mediaType:G}}let ct=(Cr=x.toolCallId)!=null?Cr:q==null?void 0:q.toolCallId,ii=nt?[nt]:[],ro=[];for(let Pn of ii){if(!Pn||typeof Pn!="object")continue;let Xt=Pn,oo=typeof Xt.type=="string"?Xt.type:void 0,Xn=typeof Xt.mediaType=="string"?Xt.mediaType.toLowerCase():"",Sn=null,In="";if(oo==="media"){let Tn=typeof Xt.data=="string"?Xt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(oo==="image-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(oo==="file-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(oo==="image-url"||In.startsWith("image/"))ro.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))ro.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))ro.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";ro.push({type:"file",data:Sn,mimeType:Tn,filename:_f(Tn)})}}if(ro.length>0){let Pn=u(),Xt=ct,Xn={id:`agent-media-${typeof Xt=="string"&&Xt.length>0?`${Xt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:ro,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};m(Xn);let Sn=v;Sn&&(Sn.streaming=!1,m(Sn)),v=null,T.current=null}}else if(ot==="execution_complete"){let j=(eo=x.kind)!=null?eo:Ye;j==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=Ae(x.completedAt),pe.stopReason=x.stopReason);let q=v;q&&(j==="flow"&&q.streaming!==!1?ue(q):(q.streaming=!1,m(q)),v=null),S=null,L="",ft=null,t({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let j=typeof x.error=="string"?x.error:(nn=(lt=x.error)==null?void 0:lt.message)!=null?nn:"Execution error";t({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(rn=x.approvalId)!=null?rn:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(Ar=pe==null?void 0:pe.agentId)!=null?Ar:"virtual",executionId:(Fr=(Ts=x.executionId)!=null?Ts:pe==null?void 0:pe.executionId)!=null?Fr:"",toolName:(To=x.toolName)!=null?To:"",toolType:x.toolType,description:(F=x.description)!=null?F:`Execute ${(Sr=x.toolName)!=null?Sr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="step_await"&&x.awaitReason==="approval_required"){let j=(Qo=x.approvalId)!=null?Qo:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(ir=pe==null?void 0:pe.agentId)!=null?ir:"virtual",executionId:(Or=(Tr=x.executionId)!=null?Tr:pe==null?void 0:pe.executionId)!=null?Or:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Xo=x.description)!=null?Xo:`Execute ${(lr=x.toolName)!=null?lr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="approval_complete"){let j=x.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:(pa=x.decision)!=null?pa:"approved",agentId:(fn=pe==null?void 0:pe.agentId)!=null?fn:"virtual",executionId:(cr=(Cn=x.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?cr:"",toolName:(An=x.toolName)!=null?An:"",description:(Mo=x.description)!=null?Mo:"",resolvedAt:Date.now()}};m(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=x.artifactType,q=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:q,artifactType:j,title:G,component:typeof x.component=="string"?x.component:void 0}),Ce.set(q,{markdown:"",title:G}),!ce.has(q)){ce.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:j,status:"streaming"}})};re.set(q,K),m(K)}}else if(ot==="artifact_delta"){let j=String(x.id),q=typeof x.delta=="string"?x.delta:String((dr=x.delta)!=null?dr:"");t({type:"artifact_delta",id:j,artDelta:q});let G=Ce.get(j);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(ot==="artifact_complete"){let j=String(x.id);t({type:"artifact_complete",id:j});let q=re.get(j);if(q){q.streaming=!1;try{let G=JSON.parse((hn=q.rawContent)!=null?hn:"{}");if(G.props){G.props.status="complete";let K=Ce.get(j);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}Ce.delete(j),m(q),re.delete(j)}}}else if(ot==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let q=String((Er=j.id)!=null?Er:`msg-${u()}`),G=j.role,De={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:u()};if(m(De),De.rawContent)try{let nt=JSON.parse(De.rawContent),ct=(Jo=nt==null?void 0:nt.props)==null?void 0:Jo.artifactId;typeof ct=="string"&&ce.add(ct)}catch{}v=null,T.current=null,ie.delete(q),Se.delete(q)}else if(ot==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Eo=x.error)==null?void 0:Eo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(j)});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(ot==="dispatch_error"){let q=(Yo=x.message)!=null?Yo:x.error;q!=null&&q!==""&&(j=new Error(String(q)))}else{let q=x.error;typeof q=="string"&&q!==""?j=new Error(q):q!=null&&typeof q=="object"&&"message"in q&&(j=new Error(String((to=q.message)!=null?to:q)))}if(j){t({type:"error",error:j});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:E,value:me}=await s.read();if(E)break;i+=a.decode(me,{stream:!0});let Me=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Pu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Iu=()=>{var e;let n=Nf();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Wu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=Wf(t,Rf|Hf);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?Eu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=Eu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Ru=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Hu="4.6.1";var js=Hu;var Of="https://api.runtype.com/v1/dispatch",Ea="https://api.runtype.com";function _f(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.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 Ii=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function $f(n){switch(n){case"json":return Wu;case"regex-json":return Iu;case"xml":return Ru;default:return Pu}}var Bu=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function Uf(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Bu(t);if(!Bu(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=qs(n);return qs(e)!==null&&a===null?e:n}var Vs=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:Of,this.headers={"Content-Type":"application/json","X-Persona-Version":js,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:$f(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new wa(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=uu(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(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(o)});if(!s.ok){let u=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${u.hint||u.error}`):s.status===403?new Error(`Origin not allowed: ${u.hint||u.error}`):new Error(u.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 t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/client/feedback`}async sendFeedback(e){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(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},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(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),u=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(Ii).map(M=>{var k,C,P;return{id:M.id,role:M.role,content:(P=(C=(k=M.contentParts)!=null?k:M.llmContent)!=null?C:M.rawContent)!=null?P:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...u&&Object.keys(u).length>0&&{metadata:u},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},h=c.clientTools,m=!!(h&&h.length>0),v=m?cu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,T=m&&w&&this.lastSentClientToolsFingerprint===v,B=!1,S=null,L;for(let M=0;;M++){let C={...g,...m&&(B||!T)&&h?{clientTools:h}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),L=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":js},body:JSON.stringify(C),signal:r.signal}),L.status===409&&M===0&&m){let P=await L.json().catch(()=>null);if((P==null?void 0:P.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}S=P!=null?P:{error:"Chat request failed"}}break}if(!L.ok){let M=S!=null?S:await L.json().catch(()=>({error:"Chat request failed"}));if(L.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(L.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let k=new Error(M.error||"Failed to send message");throw t({type:"error",error:k}),k}if(!L.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(L.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.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 t({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 t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ea}/v1/agents/${e.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:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,u;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ea}/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:e,toolOutputs:t,streamResponse:(u=r==null?void 0:r.streamResponse)!=null?u:!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(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(Ii).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,u)=>{let g=new Date(c.createdAt).getTime(),h=new Date(u.createdAt).getTime();return g-h}).map(c=>{var u,g,h;return{role:c.role,content:(h=(g=(u=c.contentParts)!=null?u:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Li(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 c={};await Promise.all(this.contextProviders.map(async u=>{try{let g=await u({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(Ii).sort((d,c)=>{let u=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return u-g}).map(d=>{var c,u,g;return{role:d.role,content:(g=(u=(c=d.contentParts)!=null?c:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Li(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 c=>{try{let u=await c({messages:e,config:this.config});u&&typeof u=="object"&&Object.assign(d,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),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 c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=u=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...u!==void 0&&{partId:u}};return r.current=g,o(g),g},c=u=>r.current?r.current:d(u);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 u=c(i.partId);i.partId!==void 0&&!u.partId&&(u.partId=i.partId),u.content+=i.text,o(u)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var gn,fr,hr,Ue;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,u=()=>d+c++,g=E=>{let me=E.reasoning?{...E.reasoning,chunks:[...E.reasoning.chunks]}:void 0,Me=E.toolCall?{...E.toolCall,chunks:E.toolCall.chunks?[...E.toolCall.chunks]:void 0}:void 0,ke=E.tools?E.tools.map(Re=>({...Re,chunks:Re.chunks?[...Re.chunks]:void 0})):void 0;return{...E,reasoning:me,toolCall:Me,tools:ke}},h=E=>{if(E.role!=="assistant"||E.variant)return!0;let me=Array.isArray(E.contentParts)&&E.contentParts.length>0,Me=typeof E.rawContent=="string"&&E.rawContent.trim()!=="";return typeof E.content=="string"&&E.content.trim()!==""||me||Me||!!E.stopReason},m=E=>{h(E)&&t({type:"message",message:g(E)})},v=null,w=null,T={current:null},B={current:null},S=null,L="",M=new Map,k=new Map,C=new Map,P=new Map,U=new Map,_={lastId:null,byStep:new Map},I={lastId:null,byCall:new Map},$=E=>{if(E==null)return null;try{return String(E)}catch{return null}},N=E=>{var me,Me,ke,Re,tt;return $((tt=(Re=(ke=(Me=(me=E.stepId)!=null?me:E.step_id)!=null?Me:E.step)!=null?ke:E.parentId)!=null?Re:E.flowStepId)!=null?tt:E.flow_step_id)},te=E=>{var me,Me,ke,Re,tt,Qe,ht;return $((ht=(Qe=(tt=(Re=(ke=(Me=(me=E.callId)!=null?me:E.call_id)!=null?Me:E.requestId)!=null?ke:E.request_id)!=null?Re:E.toolCallId)!=null?tt:E.tool_call_id)!=null?Qe:E.stepId)!=null?ht:E.step_id)},Ee=r,de=!1,Y=()=>{if(v)return v;let E,me="",Me=S;return!de&&Ee?(E=Ee,de=!0,me=o!=null?o:""):Ee&&Me?E=`${Ee}_${Me}`:E=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,v={id:E,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:u()},m(v),v},Le=(E,me)=>{_.lastId=me,E&&_.byStep.set(E,me)},Pe=(E,me)=>{var tt;let Me=(tt=E.reasoningId)!=null?tt:E.id,ke=N(E);if(Me){let Qe=String(Me);return Le(ke,Qe),Qe}if(ke){let Qe=_.byStep.get(ke);if(Qe)return _.lastId=Qe,Qe}if(_.lastId&&!me)return _.lastId;if(!me)return null;let Re=`reason-${u()}`;return Le(ke,Re),Re},ae=E=>{let me=P.get(E);if(me)return me;let Me={id:`reason-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:u(),reasoning:{id:E,status:"streaming",chunks:[]}};return P.set(E,Me),m(Me),Me},fe=(E,me)=>{I.lastId=me,E&&I.byCall.set(E,me)},ne=new Set,re=new Map,ce=new Set,Ce=new Map,_e=E=>{if(!E)return!1;let me=E.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},V=(E,me)=>{var tt;let Me=(tt=E.toolId)!=null?tt:E.id,ke=te(E);if(Me){let Qe=String(Me);return fe(ke,Qe),Qe}if(ke){let Qe=I.byCall.get(ke);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!me)return I.lastId;if(!me)return null;let Re=`tool-${u()}`;return fe(ke,Re),Re},X=E=>{let me=U.get(E);if(me)return me;let Me={id:`tool-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:u(),toolCall:{id:E,status:"pending"}};return U.set(E,Me),m(Me),Me},Ae=E=>{if(typeof E=="number"&&Number.isFinite(E))return E;if(typeof E=="string"){let me=Number(E);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Me=Date.parse(E);if(!Number.isNaN(Me))return Me}return Date.now()},J=E=>{if(typeof E=="string")return E;if(E==null)return"";try{return JSON.stringify(E)}catch{return String(E)}},ie=new Map,Se=new Map,Je=new Map,et=(E,me,Me)=>{var ht;let ke=Je.get(E);ke||(ke=[],Je.set(E,ke));let Re=0,tt=ke.length;for(;Re<tt;){let ge=Re+tt>>>1;ke[ge].seq<me?Re=ge+1:tt=ge}((ht=ke[Re])==null?void 0:ht.seq)===me?ke[Re]={seq:me,text:Me}:ke.splice(Re,0,{seq:me,text:Me});let Qe="";for(let ge=0;ge<ke.length;ge++)Qe+=ke[ge].text;return Qe},Wt=(E,me)=>{let Me=J(me),ke=Se.get(E.id),Re=Uf(ke,Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=le=>{var Ke;let gt=(Ke=E.content)!=null?Ke:"";le.trim()!==""&&(gt.trim().length===0||le.startsWith(gt)||le.trimStart().startsWith(gt.trim()))&&(E.content=le)},ht=()=>{var le;if(tt){let gt=(le=tt.close)==null?void 0:le.call(tt);gt instanceof Promise&&gt.catch(()=>{})}ie.delete(E.id),Se.delete(E.id),E.streaming=!1,m(E)};if(!tt){Qe(Me),ht();return}let ge=qs(Re);if(ge!==null&&ge.trim()!==""){Qe(ge),ht();return}let H=le=>{var Lt;let gt=typeof le=="string"?le:(Lt=le==null?void 0:le.text)!=null?Lt:null;if(gt!==null&&gt.trim()!=="")return gt;let Ke=tt.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Me},be;try{be=tt.processChunk(Re)}catch{Qe(Me),ht();return}if(be instanceof Promise){be.then(le=>{Qe(H(le)),ht()}).catch(()=>{Qe(Me),ht()});return}Qe(H(be)),ht()},ft=null,rt=(E,me,Me,ke)=>{var ge;E.rawContent=me,ie.has(E.id)||ie.set(E.id,this.createStreamParser());let Re=ie.get(E.id),tt=me.trim().startsWith("{")||me.trim().startsWith("[");if(tt&&Se.set(E.id,me),Re.__isPlainTextParser===!0){E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E);return}let ht=Re.processChunk(me);if(ht instanceof Promise)ht.then(H=>{var le;let be=typeof H=="string"?H:(le=H==null?void 0:H.text)!=null?le:null;be!==null&&be.trim()!==""?(E.content=be,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}).catch(()=>{E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E)});else{let H=typeof ht=="string"?ht:(ge=ht==null?void 0:ht.text)!=null?ge:null;H!==null&&H.trim()!==""?(E.content=H,m(E)):!tt&&!me.trim().startsWith("<")&&(E.content=ke!==void 0?me:E.content+Me,Se.delete(E.id),ie.delete(E.id),E.rawContent=void 0,m(E))}},ue=(E,me)=>{var ge,H;let Me=me!=null?me:E.content;if(Me==null||Me===""){E.streaming=!1,m(E);return}let ke=Se.get(E.id),Re=ke!=null?ke:J(Me);E.rawContent=Re;let tt=ie.get(E.id),Qe=null,ht=!1;if(tt&&(Qe=tt.getExtractedText(),Qe===null&&(Qe=qs(Re)),Qe===null)){let be=tt.processChunk(Re);be instanceof Promise?(ht=!0,be.then(le=>{var Ke;let gt=typeof le=="string"?le:(Ke=le==null?void 0:le.text)!=null?Ke:null;gt!==null&&(E.content=gt,E.streaming=!1,ie.delete(E.id),Se.delete(E.id),m(E))}).catch(()=>{})):Qe=typeof be=="string"?be:(ge=be==null?void 0:be.text)!=null?ge:null}if(!ht){Qe!==null&&Qe.trim()!==""?E.content=Qe:Se.has(E.id)||(E.content=J(Me));let be=ie.get(E.id);if(be){let le=(H=be.close)==null?void 0:H.call(be);le instanceof Promise&&le.catch(()=>{}),ie.delete(E.id)}Se.delete(E.id),E.streaming=!1,m(E)}},Q=(E,me,Me)=>{let ke=k.get(E);if(ke)return ke;let Re={id:`nested-${me}-${E}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:E,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return k.set(E,Re),m(Re),Re},it=[],je,Te=new Map,we=0,Ye="agent",qt=!1,ye=null,pe=null,wn=new Map,Ct=(gn=this.config.iterationDisplay)!=null?gn:"separate";for(je=()=>{var E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr,xe,Dr,Gn,Ot,Qn,Nr,As,Go,Ss,So,Cr,eo,lt,nn,rn,Ar,Ts,Fr,To,Sr,F,Qo,ir,Tr,Or,Mr,lr,Xo,pa,fn,Cn,cr,An,Mo,dr,hn,Er,Jo,Eo,Yo,to;for(let no=0;no<it.length;no++){let ot=it[no].payloadType,x=it[no].payload;if(!qt&&Ye!=="flow"&&typeof x.stepType=="string"&&(Ye="flow"),ot==="reasoning_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q),Q(j,q,"reasoning");continue}let G=(E=Pe(x,!0))!=null?E:`reason-${u()}`,K=ae(G);K.reasoning=(me=K.reasoning)!=null?me:{id:G,status:"streaming",chunks:[]},K.reasoning.startedAt=(ke=K.reasoning.startedAt)!=null?ke:Ae((Me=x.startedAt)!=null?Me:x.timestamp),K.reasoning.completedAt=void 0,K.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),K.streaming=!0,K.reasoning.status="streaming",m(K)}else if(ot==="reasoning_delta"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let De=k.get(j),nt=(Qe=(tt=(Re=x.reasoningText)!=null?Re:x.text)!=null?tt:x.delta)!=null?Qe:"";nt&&x.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(nt)),m(De));continue}let q=(ge=(ht=Pe(x,!1))!=null?ht:Pe(x,!0))!=null?ge:`reason-${u()}`,G=ae(q);G.reasoning=(H=G.reasoning)!=null?H:{id:q,status:"streaming",chunks:[]},G.reasoning.startedAt=(le=G.reasoning.startedAt)!=null?le:Ae((be=x.startedAt)!=null?be:x.timestamp);let K=(Lt=(Ke=(gt=x.reasoningText)!=null?gt:x.text)!=null?Ke:x.delta)!=null?Lt:"";if(K&&x.hidden!==!0){let De=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(De!==void 0){let nt=et(q,De,String(K));G.reasoning.chunks=[nt]}else G.reasoning.chunks.push(String(K))}if(G.reasoning.status=x.done?"complete":"streaming",x.done){G.reasoning.completedAt=Ae((Et=x.completedAt)!=null?Et:x.timestamp);let De=(vt=G.reasoning.startedAt)!=null?vt:Date.now();G.reasoning.durationMs=Math.max(0,((Rt=G.reasoning.completedAt)!=null?Rt:Date.now())-De)}G.streaming=G.reasoning.status!=="complete",m(G)}else if(ot==="reasoning_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)&&k.has(j)){let nt=k.get(j);if(nt.reasoning){let ct=typeof x.text=="string"?x.text:"";ct&&nt.reasoning.chunks.length===0&&nt.reasoning.chunks.push(ct),nt.reasoning.status="complete",nt.streaming=!1,m(nt)}M.delete(j),k.delete(j);continue}let q=(Ft=(Qt=Pe(x,!1))!=null?Qt:Pe(x,!0))!=null?Ft:`reason-${u()}`,G=typeof x.text=="string"?x.text:"";!P.get(q)&&(G||x.scope==="loop")&&ae(q);let K=P.get(q);if(K!=null&&K.reasoning){(x.scope==="loop"||x.scope==="turn")&&(K.reasoning.scope=x.scope),G&&K.reasoning.chunks.length===0&&K.reasoning.chunks.push(G),K.reasoning.status="complete",K.reasoning.completedAt=Ae((Zt=x.completedAt)!=null?Zt:x.timestamp);let nt=(yr=K.reasoning.startedAt)!=null?yr:Date.now();K.reasoning.durationMs=Math.max(0,((Wr=K.reasoning.completedAt)!=null?Wr:Date.now())-nt),K.streaming=!1,m(K)}let De=N(x);De&&_.byStep.delete(De)}else if(ot==="tool_start"){v&&(v.streaming=!1,m(v),v=null),typeof x.iteration=="number"&&(we=x.iteration);let j=(rr=(nr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?nr:V(x,!0))!=null?rr:`tool-${u()}`,q=(Vr=x.toolName)!=null?Vr:x.name;if(_e(q)){ne.add(j);continue}fe(te(x),j);let G=X(j),K=(jt=G.toolCall)!=null?jt:{id:j,status:"pending"};K.name=q!=null?q:K.name,K.status="running",x.parameters!==void 0?K.args=x.parameters:x.args!==void 0&&(K.args=x.args),K.startedAt=(Rr=K.startedAt)!=null?Rr:Ae((or=x.startedAt)!=null?or:x.timestamp),K.completedAt=void 0,K.durationMs=void 0,G.toolCall=K,G.streaming=!0,x.executionId&&(G.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(G)}else if(ot==="tool_output_delta"){let j=(kn=(Hn=V(x,!1))!=null?Hn:V(x,!0))!=null?kn:`tool-${u()}`;if(ne.has(j))continue;let q=X(j),G=(Bn=q.toolCall)!=null?Bn:{id:j,status:"running"};G.startedAt=(br=G.startedAt)!=null?br:Ae((sr=x.startedAt)!=null?sr:x.timestamp);let K=(Gr=(jn=(Kr=x.text)!=null?Kr:x.delta)!=null?jn:x.message)!=null?Gr:"";K&&(G.chunks=(At=G.chunks)!=null?At:[],G.chunks.push(String(K))),G.status="running",q.toolCall=G,q.streaming=!0;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Hr=q.agentMetadata)!=null?Hr:{executionId:(vr=De==null?void 0:De.executionId)!=null?vr:x.executionId,iteration:(wr=De==null?void 0:De.iteration)!=null?wr:x.iteration}),m(q)}else if(ot==="tool_complete"){let j=(yt=(ar=V(x,!1))!=null?ar:V(x,!0))!=null?yt:`tool-${u()}`;if(ne.has(j)){ne.delete(j);continue}let q=X(j),G=(wo=q.toolCall)!=null?wo:{id:j,status:"running"};G.status="complete",x.result!==void 0&&(G.result=x.result),typeof x.duration=="number"&&(G.duration=x.duration),G.completedAt=Ae((xr=x.completedAt)!=null?xr:x.timestamp);let K=(xo=x.duration)!=null?xo:x.executionTime;if(typeof K=="number")G.durationMs=K;else{let ct=(Ln=G.startedAt)!=null?Ln:Date.now();G.durationMs=Math.max(0,((Ko=G.completedAt)!=null?Ko:Date.now())-ct)}q.toolCall=G,q.streaming=!1;let De=x.agentContext;(De||x.executionId)&&(q.agentMetadata=(Xr=q.agentMetadata)!=null?Xr:{executionId:(Qr=De==null?void 0:De.executionId)!=null?Qr:x.executionId,iteration:(Br=De==null?void 0:De.iteration)!=null?Br:x.iteration}),m(q);let nt=te(x);nt&&I.byCall.delete(nt)}else if(ot==="await"&&x.toolName){let j=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,q=(Jr=j!=null?j:x.toolId)!=null?Jr:`local-${u()}`,G=X(q),K=x.toolName,De=x.origin==="webmcp"&&!as(K)?`webmcp:${K}`:K,nt=as(De),ct=(Co=G.toolCall)!=null?Co:{id:q,status:"pending"};ct.name=De,ct.args=x.parameters,ct.status=nt?"running":"complete",ct.chunks=(Ao=ct.chunks)!=null?Ao:[],ct.startedAt=(Dn=ct.startedAt)!=null?Dn:Ae((wt=(Yr=x.startedAt)!=null?Yr:x.timestamp)!=null?wt:x.awaitedAt),nt?(ct.completedAt=void 0,ct.duration=void 0,ct.durationMs=void 0):ct.completedAt=(Nn=ct.completedAt)!=null?Nn:ct.startedAt,G.toolCall=ct,G.streaming=!1,G.agentMetadata={...G.agentMetadata,executionId:(St=x.executionId)!=null?St:(xn=G.agentMetadata)==null?void 0:xn.executionId,awaitingLocalTool:!0,...j?{webMcpToolCallId:j}:{}},m(G)}else if(ot==="text_start"){let j=typeof x.id=="string"?x.id:null,q=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(j&&q){M.set(j,q);continue}let G=v;G&&(Ye==="flow"?(ue(G),ft=G):(G.streaming=!1,m(G)),v=null),S=typeof x.id=="string"?x.id:S,L=""}else if(ot==="text_delta"){let j=typeof x.id=="string"?x.id:null,q=j?M.get(j):void 0;if(j&&q){let K=typeof x.delta=="string"?x.delta:"",De=((Vn=C.get(j))!=null?Vn:"")+K;if(C.set(j,De),De.trim()==="")continue;let nt=Q(j,q);nt.agentMetadata={...nt.agentMetadata,executionId:x.executionId,parentToolId:q},rt(nt,De,K,void 0);continue}if(S=typeof x.id=="string"?x.id:S,Ye==="flow"){let K=typeof x.delta=="string"?x.delta:"";if(L+=K,L.trim()==="")continue;let De=Y();De.agentMetadata={executionId:x.executionId,iteration:x.iteration},rt(De,L,K,void 0),w=De;continue}let G=Y();G.content+=(Kn=x.delta)!=null?Kn:"",G.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:ye!=null?ye:void 0,agentName:pe==null?void 0:pe.agentName},w=G,m(G)}else if(ot==="text_complete"){let j=typeof x.id=="string"?x.id:null;if(j&&M.has(j)){let G=k.get(j);G&&ue(G),M.delete(j),C.delete(j),k.delete(j);continue}let q=v;q&&(Ye==="flow"?(ue(q),ft=q):(((Fn=q.content)!=null?Fn:"")===""&&typeof x.text=="string"&&(q.content=x.text),q.streaming=!1,m(q)),v=null),S=null,L=""}else if(ot==="step_complete"){let j=x.stepType,q=x.executionType;if(j==="tool"||q==="context")continue;if(x.success===!1){let G=x.error,K=typeof G=="string"&&G!==""?G:G!=null&&typeof G=="object"&&Reflect.has(G,"message")?String((Zr=G.message)!=null?Zr:"Step failed"):"Step failed";t({type:"error",error:new Error(K)});let De=v;De&&De.streaming&&(De.streaming=!1,m(De)),t({type:"status",status:"idle"});continue}{let G=ft;ft=null;let K=x.stopReason,De=(xe=x.result)==null?void 0:xe.response;if(G)K&&(G.stopReason=K),De!=null?Wt(G,De):G.streaming!==!1&&(ie.delete(G.id),Se.delete(G.id),G.streaming=!1,m(G));else{let nt=De!=null&&De!=="";if(nt||K){let ct=Y();K&&(ct.stopReason=K),nt?ue(ct,De):(ct.streaming=!1,m(ct))}}continue}}else if(ot==="execution_start")Ye=x.kind==="flow"?"flow":"agent",qt=!0,Ye==="agent"&&(pe={executionId:x.executionId,agentId:(Dr=x.agentId)!=null?Dr:"virtual",agentName:(Gn=x.agentName)!=null?Gn:"",status:"running",currentIteration:0,maxTurns:(Ot=x.maxTurns)!=null?Ot:1,startedAt:Ae(x.startedAt)});else if(ot==="turn_start"){let j=typeof x.iteration=="number"?x.iteration:we;if(j!==we){if(pe&&(pe.currentIteration=j),Ct==="separate"&&j>1){let q=v;q&&(q.streaming=!1,m(q),wn.set(j-1,q),v=null)}we=j}ye=typeof x.id=="string"?x.id:null,w=null}else if(ot==="tool_input_delta"){let j=(Qn=x.toolCallId)!=null?Qn:I.lastId;if(j){let q=U.get(j);q!=null&&q.toolCall&&(q.toolCall.chunks=(Nr=q.toolCall.chunks)!=null?Nr:[],q.toolCall.chunks.push((As=x.delta)!=null?As:""),m(q))}}else{if(ot==="tool_input_complete")continue;if(ot==="turn_complete"){let j=x.stopReason,q=v!=null?v:w;if(j&&q!==null){let G=x.id;(!G||((Go=q.agentMetadata)==null?void 0:Go.turnId)===G)&&(q.stopReason=j,m(q))}ye===x.id&&(ye=null)}else if(ot==="media_start"){let j=String(x.id);Te.set(j,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(ot==="media_delta"){let j=Te.get(String(x.id));j&&typeof x.delta=="string"&&j.parts.push(x.delta)}else if(ot==="media_complete"){let j=String(x.id),q=Te.get(j);Te.delete(j);let G=(So=(Ss=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ss:q==null?void 0:q.mediaType)!=null?So:"application/octet-stream",K=typeof x.data=="string"?x.data:void 0,De=typeof x.url=="string"?x.url:q&&q.parts.length>0?q.parts.join(""):void 0,nt=null;if(K)nt={type:"media",data:K,mediaType:G};else if(De){let Pn=G.toLowerCase();nt={type:Pn==="image"||Pn.startsWith("image/")?"image-url":"file-url",url:De,mediaType:G}}let ct=(Cr=x.toolCallId)!=null?Cr:q==null?void 0:q.toolCallId,ii=nt?[nt]:[],ro=[];for(let Pn of ii){if(!Pn||typeof Pn!="object")continue;let Xt=Pn,oo=typeof Xt.type=="string"?Xt.type:void 0,Xn=typeof Xt.mediaType=="string"?Xt.mediaType.toLowerCase():"",Sn=null,In="";if(oo==="media"){let Tn=typeof Xt.data=="string"?Xt.data:void 0;if(!Tn)continue;In=Xn.length>0?Xn:"application/octet-stream",Sn=`data:${In};base64,${Tn}`}else if(oo==="image-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else if(oo==="file-url"){let Tn=typeof Xt.url=="string"?Xt.url:void 0;if(!Tn)continue;In=Xn,Sn=Tn}else continue;if(Sn)if(oo==="image-url"||In.startsWith("image/"))ro.push({type:"image",image:Sn,...In.includes("/")?{mimeType:In}:{}});else if(In.startsWith("audio/"))ro.push({type:"audio",audio:Sn,mimeType:In});else if(In.startsWith("video/"))ro.push({type:"video",video:Sn,mimeType:In});else{let Tn=In||"application/octet-stream";ro.push({type:"file",data:Sn,mimeType:Tn,filename:_f(Tn)})}}if(ro.length>0){let Pn=u(),Xt=ct,Xn={id:`agent-media-${typeof Xt=="string"&&Xt.length>0?`${Xt}-${Pn}`:String(Pn)}`,role:"assistant",content:"",contentParts:ro,createdAt:new Date().toISOString(),streaming:!1,sequence:Pn,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:we}};m(Xn);let Sn=v;Sn&&(Sn.streaming=!1,m(Sn)),v=null,T.current=null}}else if(ot==="execution_complete"){let j=(eo=x.kind)!=null?eo:Ye;j==="agent"&&pe&&(pe.status=x.success?"complete":"error",pe.completedAt=Ae(x.completedAt),pe.stopReason=x.stopReason);let q=v;q&&(j==="flow"&&q.streaming!==!1?ue(q):(q.streaming=!1,m(q)),v=null),S=null,L="",ft=null,t({type:"status",status:"idle",terminal:!0})}else if(ot==="execution_error"){let j=typeof x.error=="string"?x.error:(nn=(lt=x.error)==null?void 0:lt.message)!=null?nn:"Execution error";t({type:"error",error:new Error(j)})}else if(ot!=="ping"){if(ot==="approval_start"){let j=(rn=x.approvalId)!=null?rn:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(Ar=pe==null?void 0:pe.agentId)!=null?Ar:"virtual",executionId:(Fr=(Ts=x.executionId)!=null?Ts:pe==null?void 0:pe.executionId)!=null?Fr:"",toolName:(To=x.toolName)!=null?To:"",toolType:x.toolType,description:(F=x.description)!=null?F:`Execute ${(Sr=x.toolName)!=null?Sr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="step_await"&&x.awaitReason==="approval_required"){let j=(Qo=x.approvalId)!=null?Qo:`approval-${u()}`,q={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:"pending",agentId:(ir=pe==null?void 0:pe.agentId)!=null?ir:"virtual",executionId:(Or=(Tr=x.executionId)!=null?Tr:pe==null?void 0:pe.executionId)!=null?Or:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Xo=x.description)!=null?Xo:`Execute ${(lr=x.toolName)!=null?lr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(q)}else if(ot==="approval_complete"){let j=x.approvalId;if(j){let G={id:`approval-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:u(),approval:{id:j,status:(pa=x.decision)!=null?pa:"approved",agentId:(fn=pe==null?void 0:pe.agentId)!=null?fn:"virtual",executionId:(cr=(Cn=x.executionId)!=null?Cn:pe==null?void 0:pe.executionId)!=null?cr:"",toolName:(An=x.toolName)!=null?An:"",description:(Mo=x.description)!=null?Mo:"",resolvedAt:Date.now()}};m(G)}}else if(ot==="artifact_start"||ot==="artifact_delta"||ot==="artifact_update"||ot==="artifact_complete"){if(ot==="artifact_start"){let j=x.artifactType,q=String(x.id),G=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:q,artifactType:j,title:G,component:typeof x.component=="string"?x.component:void 0}),Ce.set(q,{markdown:"",title:G}),!ce.has(q)){ce.add(q);let K={id:`artifact-ref-${q}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:u(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:q,title:G,artifactType:j,status:"streaming"}})};re.set(q,K),m(K)}}else if(ot==="artifact_delta"){let j=String(x.id),q=typeof x.delta=="string"?x.delta:String((dr=x.delta)!=null?dr:"");t({type:"artifact_delta",id:j,artDelta:q});let G=Ce.get(j);G&&(G.markdown+=q)}else if(ot==="artifact_update"){let j=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:j,component:typeof x.component=="string"?x.component:void 0})}else if(ot==="artifact_complete"){let j=String(x.id);t({type:"artifact_complete",id:j});let q=re.get(j);if(q){q.streaming=!1;try{let G=JSON.parse((hn=q.rawContent)!=null?hn:"{}");if(G.props){G.props.status="complete";let K=Ce.get(j);K!=null&&K.markdown&&(G.props.markdown=K.markdown)}q.rawContent=JSON.stringify(G)}catch{}Ce.delete(j),m(q),re.delete(j)}}}else if(ot==="transcript_insert"){let j=x.message;if(!j||typeof j!="object")continue;let q=String((Er=j.id)!=null?Er:`msg-${u()}`),G=j.role,De={id:q,role:G==="user"?"user":G==="system"?"system":"assistant",content:typeof j.content=="string"?j.content:"",rawContent:typeof j.rawContent=="string"?j.rawContent:void 0,createdAt:typeof j.createdAt=="string"?j.createdAt:new Date().toISOString(),streaming:j.streaming===!0,...typeof j.variant=="string"?{variant:j.variant}:{},sequence:u()};if(m(De),De.rawContent)try{let nt=JSON.parse(De.rawContent),ct=(Jo=nt==null?void 0:nt.props)==null?void 0:Jo.artifactId;typeof ct=="string"&&ce.add(ct)}catch{}v=null,T.current=null,ie.delete(q),Se.delete(q)}else if(ot==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let j=typeof x.error=="string"?x.error:((Eo=x.error)==null?void 0:Eo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(j)});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}else if(ot==="step_error"||ot==="dispatch_error"||ot==="flow_error"){let j=null;if(x.error instanceof Error)j=x.error;else if(ot==="dispatch_error"){let q=(Yo=x.message)!=null?Yo:x.error;q!=null&&q!==""&&(j=new Error(String(q)))}else{let q=x.error;typeof q=="string"&&q!==""?j=new Error(q):q!=null&&typeof q=="object"&&Reflect.has(q,"message")&&(j=new Error(String((to=q.message)!=null?to:q)))}if(j){t({type:"error",error:j});let q=v;q&&q.streaming&&(q.streaming=!1,m(q)),t({type:"status",status:"idle"})}}}}}it.length=0};;){let{done:E,value:me}=await s.read();if(E)break;i+=a.decode(me,{stream:!0});let Me=i.split(`
12
12
 
13
13
  `);i=(fr=Me.pop())!=null?fr:"";for(let ke of Me){let Re=ke.split(`
14
14
  `),tt="message",Qe="",ht=null;for(let le of Re)le.startsWith("event:")?tt=le.replace("event:","").trim():le.startsWith("data:")?Qe+=le.replace("data:","").trim():le.startsWith("id:")&&(ht=le.slice(3).trim());let ge=()=>{ht!==null&&ht!==""&&t({type:"cursor",id:ht})};if(!Qe){ge();continue}let H;try{H=JSON.parse(Qe)}catch(le){t({type:"error",error:le instanceof Error?le:new Error("Failed to parse chat stream payload")});continue}let be=tt!=="message"?tt:(hr=H.type)!=null?hr:"message";if((Ue=this.onSSEEvent)==null||Ue.call(this,be,H),this.parseSSEEvent){T.current=v;let le=await this.handleCustomSSEEvent(H,t,T,m,u,B);if(T.current&&T.current!==v&&(v=T.current),le){ge();continue}}it.push({payloadType:be,payload:H}),je(),ge()}}je()}};function ka(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function ps(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var La="[Image]";function Wi(n){return{type:"text",text:n}}var Du=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zf=["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"],qr=[...Du,...zf];function qf(n){return Du.includes(n)||n.startsWith("image/")}function Pa(n){return qf(n.type)}async function Nu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Pa(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function Fu(n,e=qr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function jf(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function Ou(n,e){let t=jf(e).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"}[n]||t||"FILE"}var _u=16e3,Vf=24e3,Kf=4096,Gf=1380533830;function Qf(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===Gf?new Uint8Array(n,44):new Uint8Array(n)}function Xf(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Ks=class{constructor(e){this.config=e;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 e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)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 c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:_u,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let u=window.AudioContext||window.webkitAudioContext,g=new u({sampleRate:_u});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Zp(Vf);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${Xf(r)}/ws/agents/${encodeURIComponent(e)}/voice`,v=new WebSocket(m,["runtype.bearer",t]);v.binaryType="arraybuffer",this.ws=v,v.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,v,o))},v.onmessage=w=>this.handleMessage(w,o),v.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},v.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let T=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}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(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(Kf,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let u=0;u<d.length;u++){let g=Math.max(-1,Math.min(1,d[u]));c[u]=g<0?g*32768:g*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.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(e,t){if(t!==this.callGeneration||!this.playback)return;let r=Qf(e);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(e=>e.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(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var _o=class{constructor(e={}){this.config=e;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(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.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(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function us(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ks(n.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function $u(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return us({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return us({type:"runtype",runtype:n.runtype});if(_o.isSupported())return us({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ri(n){try{return $u(n),!0}catch{return!1}}function Ia(n){var t;let e=["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 e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var ms=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ia(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,u;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(u=t.onError)==null||u.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Gs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"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(t,{onStart:()=>{r===this.generation&&this.set(e,"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 e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function Hi(n){if(!n)return"";let e=Jf(n);return Uu(e!==null?e:n)}function Jf(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Uu(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),e=e.replace(/\n{2,}/g,`
16
16
  `),e.trim()}var zu=null;var Bi=()=>zu?zu():import("./runtype-tts-entry-HFUV2UF7.js");var Yf=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Zf(n,e){return Yf.some(t=>n[t]!==e[t])}function Di(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);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 t.message?`${r}
17
17
 
18
- _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]}),qu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,ju=n=>as(n)||n===zr,Wa=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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 Gs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,u,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(as(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.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 Vs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.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?c:this.config.agentId;!t||!r||!this.config.clientToken||Bi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Ri((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=ms.isSupported()?new ms({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(i=e.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,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&u&&g)return Bi().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:v})=>{let w=new m({host:c,agentId:u,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new v(w,t,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=us(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).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,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.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,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,u,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Zf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Vs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:g}=e,m={id:a!=null?a:t==="user"?ka():t==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?ka():o==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,u,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=ka(),s=ps();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){if(this.status==="resuming"||this.reconnecting)return;let w=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!w){let T=Di(v,this.config.errorMessage);if(T){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(v instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,v):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=ps();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=Di(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var u,g,h,m,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let T=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}T=w.body}else w instanceof ReadableStream&&(T=w);T?await this.connectStream(T,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.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(w){let T=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(v=(m=this.callbacks).onError)==null||v.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,g,h,m,v,w,T,B,S,L,M,k;let r=this.messages.find(C=>C.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,P=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(P.length===1){let U=typeof((T=P[0])==null?void 0:T.question)=="string"?P[0].question:"";U&&(a={[U]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(S=e.toolCall)==null?void 0:S.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([P,U])=>`${P}: ${Array.isArray(U)?U.join(", "):U}`).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:{};c.forEach((P,U)=>{let _=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!_)return;let I=C[_],$=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let P=await C.json().catch(()=>null);throw new Error((L=P==null?void 0:P.error)!=null?L:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let P=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(k=(M=this.callbacks).onError)==null||k.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,u,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var k,C,P,U,_,I,$;let m=(k=h.toolCall)==null?void 0:k.name,v=(C=h.toolCall)==null?void 0:C.id;if(!m||!v)return null;let w=`${e}:${v}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let T=this.markWebMcpToolRunning(h),B=(U=(P=h.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?U:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Ei(),toolMessage:h,startedAt:T,completedAt:Date.now()};let S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let L=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,S.signal),M;if(!L)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await L}catch(N){let te=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return te||($=(I=this.callbacks).onError)==null||$.call(I,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(h,Qs(te?"Aborted by cancel()":qu(N)),T),this.webMcpInflightKeys.delete(w),null}return S.signal.aborted?(this.markWebMcpToolComplete(h,Qs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let h={};for(let v of i)h[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,h instanceof Error?h:new Error(String(h)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,Qs("Aborted by cancel()"),v.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,w,T,B,S,L,M,k,C,P,U,_;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(T=e.toolCall)==null?void 0:T.id;if(!t){(S=(B=this.callbacks).onError)==null||S.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let I=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(I)}catch($){(M=(L=this.callbacks).onError)==null||M.call(L,$ instanceof Error?$:new Error(String($)))}finally{this.webMcpInflightKeys.delete(I)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(k=e.toolCall)==null?void 0:k.args,g=c?null:this.client.executeWebMcpToolCall(r,u,d),h="execute",m=a;try{let I;if(c?I=Ei():g?I=await g:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Qs("Aborted by cancel()"),a);return}let $=(P=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?P:r;h="resume",await this.resumeWithToolOutput(t,$,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,I,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(I){let $=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(h==="execute"||$||d.aborted)&&this.markWebMcpToolComplete(e,Qs($||d.aborted?"Aborted by cancel()":qu(I)),a),$||(_=(U=this.callbacks).onError)==null||_.call(U,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]: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 e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.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(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-U77QFUR7.js").then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Di(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=ps(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.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=Hi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ia(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Hi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var u,g,h,m,v,w,T,B,S,L,M,k,C,P,U;if(s!==r)return o;let a={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,I=t.approval;a.approval={..._,...I,executionId:I.executionId||_.executionId,toolName:I.toolName||_.toolName,description:I.description||_.description,toolType:(m=I.toolType)!=null?m:_.toolType,reason:(v=I.reason)!=null?v:_.reason,parameters:(w=I.parameters)!=null?w:_.parameters}}let i=(T=t.toolCall)==null?void 0:T.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(S=t.toolCall)==null?void 0:S.id;if(i&&ju(i)&&d&&c&&((L=t.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let _=`${d}:${c}`,I=this.webMcpInflightKeys.has(_),$=this.webMcpResolvedKeys.has(_),N=(M=o.toolCall)==null?void 0:M.name,te=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&N!==void 0&&ju(N)&&((P=o.toolCall)==null?void 0:P.status)==="complete";(I||$||te)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};import{Activity as eh,ArrowDown as th,ArrowUp as nh,ArrowUpRight as rh,Bot as oh,ChevronDown as sh,ChevronUp as ah,ChevronRight as ih,ChevronLeft as lh,Check as ch,Clipboard as dh,ClipboardCopy as ph,Copy as uh,File as mh,FileCode as gh,FileSpreadsheet as fh,FileText as hh,ImagePlus as yh,Loader as bh,LoaderCircle as vh,Mic as wh,Paperclip as xh,RefreshCw as Ch,Search as Ah,Send as Sh,ShieldAlert as Th,ShieldCheck as Mh,ShieldX as Eh,Square as kh,ThumbsDown as Lh,ThumbsUp as Ph,Upload as Ih,Volume2 as Wh,X as Rh,User as Hh,Mail as Bh,Phone as Dh,Calendar as Nh,Clock as Fh,Building as Oh,MapPin as _h,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Vh,Link as Kh,CircleCheck as Gh,CircleX as Qh,TriangleAlert as Xh,Info as Jh,Ban as Yh,Shield as Zh,ArrowLeft as ey,ArrowRight as ty,ExternalLink as ny,Ellipsis as ry,EllipsisVertical as oy,Menu as sy,House as ay,Plus as iy,Minus as ly,Pencil as cy,Trash as dy,Trash2 as py,Save as uy,Download as my,Share as gy,Funnel as fy,Settings as hy,RotateCw as yy,Maximize as by,Minimize as vy,ShoppingCart as wy,ShoppingBag as xy,Package as Cy,Truck as Ay,Tag as Sy,Gift as Ty,Receipt as My,Wallet as Ey,Store as ky,DollarSign as Ly,Percent as Py,Play as Iy,Pause as Wy,VolumeX as Ry,Camera as Hy,Image as By,Film as Dy,Headphones as Ny,MessageCircle as Fy,MessageSquare as Oy,Bell as _y,Heart as $y,Star as Uy,Eye as zy,EyeOff as qy,Bookmark as jy,CalendarDays as Vy,History as Ky,Timer as Gy,Folder as Qy,FolderOpen as Xy,Files as Jy,Sparkles as Yy,Zap as Zy,Sun as eb,Moon as tb,Flag as nb,Monitor as rb,Smartphone as ob}from"lucide";var sb={activity:eh,"arrow-down":th,"arrow-up":nh,"arrow-up-right":rh,bot:oh,"chevron-down":sh,"chevron-up":ah,"chevron-right":ih,"chevron-left":lh,check:ch,clipboard:dh,"clipboard-copy":ph,copy:uh,file:mh,"file-code":gh,"file-spreadsheet":fh,"file-text":hh,"image-plus":yh,loader:bh,"loader-circle":vh,mic:wh,paperclip:xh,"refresh-cw":Ch,search:Ah,send:Sh,"shield-alert":Th,"shield-check":Mh,"shield-x":Eh,square:kh,"thumbs-down":Lh,"thumbs-up":Ph,upload:Ih,"volume-2":Wh,x:Rh,user:Hh,mail:Bh,phone:Dh,calendar:Nh,clock:Fh,building:Oh,"map-pin":_h,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Vh,link:Kh,"circle-check":Gh,"circle-x":Qh,"triangle-alert":Xh,info:Jh,ban:Yh,shield:Zh,"arrow-left":ey,"arrow-right":ty,"external-link":ny,ellipsis:ry,"ellipsis-vertical":oy,menu:sy,house:ay,plus:iy,minus:ly,pencil:cy,trash:dy,"trash-2":py,save:uy,download:my,share:gy,funnel:fy,settings:hy,"rotate-cw":yy,maximize:by,minimize:vy,"shopping-cart":wy,"shopping-bag":xy,package:Cy,truck:Ay,tag:Sy,gift:Ty,receipt:My,wallet:Ey,store:ky,"dollar-sign":Ly,percent:Py,play:Iy,pause:Wy,"volume-x":Ry,camera:Hy,image:By,film:Dy,headphones:Ny,"message-circle":Fy,"message-square":Oy,bell:_y,heart:$y,star:Uy,eye:zy,"eye-off":qy,bookmark:jy,"calendar-days":Vy,history:Ky,timer:Gy,folder:Qy,"folder-open":Xy,files:Jy,sparkles:Yy,zap:Zy,sun:eb,moon:tb,flag:nb,monitor:rb,smartphone:ob},he=(n,e=24,t="currentColor",r=2)=>{let o=sb[n];return o?ab(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ab(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.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(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Ra={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function ib(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function lb(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var Xs=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ra.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ra.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ra.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ra.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let u=Fu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Nu(c),h=Pa(c)?URL.createObjectURL(c):null,m={id:ib(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Pa(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.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=b("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=lb(e.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Ou(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("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=he("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(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Vu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Js(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Vu(s)&&Vu(o)?t[r]=Js(s,o):t[r]=o}return t}var jr="min(440px, calc(100vw - 24px))",Gu="440px",cb={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:jr,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)"},Ht={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:cb,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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},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 Ku(n,e){if(!(!n&&!e))return n?e?Js(n,e):n:e}function Qu(n){var e,t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k;return n?{...Ht,...n,theme:Ku(Ht.theme,n.theme),darkTheme:Ku(Ht.darkTheme,n.darkTheme),launcher:{...Ht.launcher,...n.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...n.copy},sendButton:{...Ht.sendButton,...n.sendButton},statusIndicator:{...Ht.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...n.voiceRecognition},features:(()=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie;let C=(ne=Ht.features)==null?void 0:ne.artifacts,P=(re=n.features)==null?void 0:re.artifacts,U=(ce=Ht.features)==null?void 0:ce.scrollToBottom,_=(Ce=n.features)==null?void 0:Ce.scrollToBottom,I=(_e=Ht.features)==null?void 0:_e.scrollBehavior,$=(V=n.features)==null?void 0:V.scrollBehavior,N=(X=Ht.features)==null?void 0:X.streamAnimation,te=(Ae=n.features)==null?void 0:Ae.streamAnimation,Ee=(J=Ht.features)==null?void 0:J.askUserQuestion,de=(ie=n.features)==null?void 0:ie.askUserQuestion,Y=C===void 0&&P===void 0?void 0:{...C,...P,layout:{...C==null?void 0:C.layout,...P==null?void 0:P.layout}},Le=U===void 0&&_===void 0?void 0:{...U,..._},Pe=I===void 0&&$===void 0?void 0:{...I,...$},ae=N===void 0&&te===void 0?void 0:{...N,...te},fe=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ht.features,...n.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...Y!==void 0?{artifacts:Y}:{},...ae!==void 0?{streamAnimation:ae}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ht.layout,...n.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(v=Ht.layout)==null?void 0:v.messages)==null?void 0:w.timestamp,...(B=(T=n.layout)==null?void 0:T.messages)==null?void 0:B.timestamp}},slots:{...(S=Ht.layout)==null?void 0:S.slots,...(L=n.layout)==null?void 0:L.slots}},markdown:{...Ht.markdown,...n.markdown,options:{...(M=Ht.markdown)==null?void 0:M.options,...(k=n.markdown)==null?void 0:k.options}},messageActions:{...Ht.messageActions,...n.messageActions}}:Ht}var db={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"}},pb={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"}},ub={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:jr,maxWidth:Gu,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 gs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?gs(n,r):r}function Xu(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=gs(n,a);d!==void 0&&(e[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&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function mb(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Ju(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Ju(s,o):t[r]=o}return t}function gb(n,e){return e?Ju(n,e):n}function $o(n,e={}){var o,s,a,i,d,c,u,g,h,m,v,w,T;let t={palette:db,semantic:pb,components:ub},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(u=n==null?void 0:n.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(T=n==null?void 0:n.semantic)==null?void 0:T.typography}},components:gb(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=mb(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(S=>S.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function Yu(n){var w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue,Q,it,je,Te,we,Ye,qt,ye,pe,wn,Ct,gn,fr,hr,Ue,E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr;let e=Xu(n),t={};for(let[xe,Dr]of Object.entries(e)){let Gn=xe.replace(/\./g,"-");t[`--persona-${Gn}`]=Dr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(L=t["--persona-semantic-colors-background"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(k=t["--persona-semantic-colors-text"])!=null?k:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(U=t["--persona-semantic-colors-border"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(I=t["--persona-components-voice-recording-indicator"])!=null?I:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=($=t["--persona-components-voice-recording-background"])!=null?$:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(N=t["--persona-components-voice-processing-icon"])!=null?N:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-surface"],t["--persona-approval-border"]=(de=t["--persona-components-approval-requested-border"])!=null?de:t["--persona-border"],t["--persona-approval-text"]=(Y=t["--persona-components-approval-requested-text"])!=null?Y:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Le=t["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Pe=t["--persona-components-approval-approve-background"])!=null?Pe:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ae=t["--persona-components-approval-deny-background"])!=null?ae:t["--persona-container"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ne=t["--persona-components-attachment-image-border"])!=null?ne:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ce=t["--persona-semantic-typography-fontSize"])!=null?ce:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ce=t["--persona-semantic-typography-fontWeight"])!=null?Ce:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(_e=t["--persona-semantic-typography-lineHeight"])!=null?_e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(X=t["--persona-palette-radius-md"])!=null?X:"0.375rem",t["--persona-radius-lg"]=(Ae=t["--persona-palette-radius-lg"])!=null?Ae:"0.5rem",t["--persona-radius-xl"]=(J=t["--persona-palette-radius-xl"])!=null?J:"0.75rem",t["--persona-radius-full"]=(ie=t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-launcher-radius"]=(Je=(Se=t["--persona-components-launcher-borderRadius"])!=null?Se:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-launcher-bg"]=(et=t["--persona-components-launcher-background"])!=null?et:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ft=t["--persona-components-launcher-border"])!=null?ft:t["--persona-border"],t["--persona-button-primary-bg"]=(rt=t["--persona-components-button-primary-background"])!=null?rt:t["--persona-primary"],t["--persona-button-primary-fg"]=(ue=t["--persona-components-button-primary-foreground"])!=null?ue:t["--persona-text-inverse"],t["--persona-button-radius"]=(it=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-panel-radius"]=(Te=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?Te:"0.75rem",t["--persona-panel-border"]=(we=t["--persona-components-panel-border"])!=null?we:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(qt=(Ye=t["--persona-components-panel-shadow"])!=null?Ye:t["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(ye=t["--persona-components-launcher-shadow"])!=null?ye:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(wn=(pe=t["--persona-components-input-borderRadius"])!=null?pe:t["--persona-radius-lg"])!=null?wn:"0.5rem",t["--persona-message-user-radius"]=(gn=(Ct=t["--persona-components-message-user-borderRadius"])!=null?Ct:t["--persona-radius-lg"])!=null?gn:"0.5rem",t["--persona-message-assistant-radius"]=(hr=(fr=t["--persona-components-message-assistant-borderRadius"])!=null?fr:t["--persona-radius-lg"])!=null?hr:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(E=t["--persona-components-header-border"])!=null?E:t["--persona-divider"],t["--persona-header-icon-bg"]=(me=t["--persona-components-header-iconBackground"])!=null?me:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ke=t["--persona-components-header-titleForeground"])!=null?ke:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Re=t["--persona-components-header-subtitleForeground"])!=null?Re:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(tt=t["--persona-components-header-actionIconForeground"])!=null?tt:t["--persona-muted"];let r=(Qe=n.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=n.components)==null?void 0:ht.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(H=t["--persona-components-introCard-borderRadius"])!=null?H:"1rem",t["--persona-intro-card-padding"]=(be=t["--persona-components-introCard-padding"])!=null?be:"1.5rem",t["--persona-intro-card-shadow"]=(gt=(le=o==null?void 0:o.shadow)!=null?le:t["--persona-components-introCard-shadow"])!=null?gt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ke=t["--persona-components-input-background"])!=null?Ke:t["--persona-surface"],t["--persona-input-placeholder"]=(Lt=t["--persona-components-input-placeholder"])!=null?Lt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Et=t["--persona-components-message-user-background"])!=null?Et:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Rt=t["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Qt=t["--persona-components-message-assistant-background"])!=null?Qt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ft=t["--persona-components-message-assistant-text"])!=null?Ft:t["--persona-text"],t["--persona-message-assistant-border"]=(Zt=t["--persona-components-message-assistant-border"])!=null?Zt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(yr=t["--persona-components-message-assistant-shadow"])!=null?yr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(nr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?nr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Vr=(rr=t["--persona-components-scrollToBottom-foreground"])!=null?rr:t["--persona-button-primary-fg"])!=null?Vr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(jt=t["--persona-components-scrollToBottom-border"])!=null?jt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(or=t["--persona-components-scrollToBottom-size"])!=null?or:"40px",t["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Rr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Rr:t["--persona-button-radius"])!=null?Hn:t["--persona-radius-full"])!=null?kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(sr=(Bn=t["--persona-components-scrollToBottom-shadow"])!=null?Bn:t["--persona-palette-shadows-sm"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(br=t["--persona-components-scrollToBottom-padding"])!=null?br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Kr=t["--persona-components-scrollToBottom-gap"])!=null?Kr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Gr=(jn=t["--persona-components-scrollToBottom-fontSize"])!=null?jn:t["--persona-palette-typography-fontSize-sm"])!=null?Gr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(At=t["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",t["--persona-tool-bubble-shadow"]=(vr=t["--persona-components-toolBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(wr=t["--persona-components-reasoningBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Hr=t["--persona-components-composer-shadow"])!=null?Hr:"none",t["--persona-md-inline-code-bg"]=(ar=t["--persona-components-markdown-inlineCode-background"])!=null?ar:t["--persona-container"],t["--persona-md-inline-code-color"]=(yt=t["--persona-components-markdown-inlineCode-foreground"])!=null?yt:t["--persona-text"],t["--persona-md-link-color"]=(xr=(wo=t["--persona-components-markdown-link-foreground"])!=null?wo:t["--persona-accent"])!=null?xr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(xo=t["--persona-components-markdown-codeBlock-background"])!=null?xo:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Ln=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Ko=t["--persona-components-markdown-codeBlock-textColor"])!=null?Ko:"inherit",t["--persona-md-table-header-bg"]=(Qr=t["--persona-components-markdown-table-headerBackground"])!=null?Qr:t["--persona-container"],t["--persona-md-table-border-color"]=(Br=t["--persona-components-markdown-table-borderColor"])!=null?Br:t["--persona-border"],t["--persona-md-hr-color"]=(Xr=t["--persona-components-markdown-hr-color"])!=null?Xr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Jr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Jr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Co=t["--persona-components-markdown-blockquote-background"])!=null?Co:"transparent",t["--persona-md-blockquote-text-color"]=(Ao=t["--persona-components-markdown-blockquote-textColor"])!=null?Ao:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Yr=t["--persona-components-collapsibleWidget-container"])!=null?Yr:t["--persona-surface"],t["--cw-surface"]=(wt=t["--persona-components-collapsibleWidget-surface"])!=null?wt:t["--persona-surface"],t["--cw-border"]=(Dn=t["--persona-components-collapsibleWidget-border"])!=null?Dn:t["--persona-border"],t["--persona-message-border"]=(Nn=t["--persona-components-message-border"])!=null?Nn:t["--persona-border"];let u=n.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=u==null?void 0:u.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let xe=v.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(xn=t["--persona-dropdown-bg"])!=null?xn:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(St=t["--persona-dropdown-border"])!=null?St:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Kn=t["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(v!=null&&v.tab){let xe=v.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(v!=null&&v.pane){let xe=v.pane;if(xe.toolbarBackground){let Dr=(Zr=gs(n,xe.toolbarBackground))!=null?Zr:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Dr}}return t}var fb={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"}}},Zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ni=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},hb=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ni()},yb=n=>hb(n),bb=n=>$o(n),vb=n=>{var t;let e=$o(void 0,{validate:!1});return $o({...n,palette:{...e.palette,colors:{...fb.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ha=n=>{let e=yb(n),t=Zu(n==null?void 0:n.theme),r=Zu(n==null?void 0:n.darkTheme);return e==="dark"?vb(Js(t!=null?t:{},r!=null?r:{})):bb(t)},wb=n=>Yu(n),fs=(n,e)=>{let t=Ha(e),r=wb(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},em=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ni())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ni());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};import{Idiomorph as xb}from"idiomorph";var Ba=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;xb.morph(n,e.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:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var tm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Da={index:-1,draft:""};function nm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Da}}}function rm(n,e){var t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=n.llmContent)==null?void 0:c.length)!=null?u:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(T=(w=n.toolCall)==null?void 0:w.name)!=null?T:"",(L=(S=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:S.length)!=null?L:0,(P=(C=(k=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:k[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?P:"",typeof((U=n.toolCall)==null?void 0:U.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(N=($=(I=n.reasoning)==null?void 0:I.chunks)==null?void 0:$.length)!=null?N:0,(Y=(de=(Ee=(te=n.reasoning)==null?void 0:te.chunks)==null?void 0:Ee[n.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Y:0,(fe=(ae=(Pe=(Le=n.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[n.reasoning.chunks.length-1])==null?void 0:ae.slice(-32))!=null?fe:"",(re=(ne=n.contentParts)==null?void 0:ne.length)!=null?re:0,(ce=n.stopReason)!=null?ce:"",e].join("\0")}function om(){return new Map}function sm(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function am(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function im(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Na(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ir(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function yo(n,e){return Ir(n)-n.scrollTop<=e}function Fa(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Oa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function lm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function cm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function dm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},bn=1e5,bo=bn+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Cb=["pre","code","a","script","style"],_a=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:Ys.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:Ys.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:Ys.speed,duration:(o=n==null?void 0:n.duration)!=null?o:Ys.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:Ys.buffer}},Ab=[{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"}],um=new Map;for(let n of Ab)um.set(n.name,n);var hs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=um.get(n))!=null?r:null},$a=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
18
+ _Details: ${t.message}_`:r}var Qs=n=>({isError:!0,content:[{type:"text",text:n}]}),qu=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,ju=n=>as(n)||n===zr,Wa=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=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 Gs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,u,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(as(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(u=this.callbacks).onError)==null||g.call(u,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.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 Vs(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.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,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.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?c:this.config.agentId;!t||!r||!this.config.clientToken||Bi().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return Ri((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=ms.isSupported()?new ms({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,u=(d=(i=e.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,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&u&&g)return Bi().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:v})=>{let w=new m({host:c,agentId:u,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new v(w,t,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=us(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).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,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let u=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=u.id}if(c){this.pendingVoiceUserMessageId=null;let u=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=u.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let u=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=u.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.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,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.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(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,u,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(u=e.runtype)==null?void 0:u.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Zf(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Vs(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:u,rawContent:g}=e,m={id:a!=null?a:t==="user"?ka():t==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...u!==void 0&&{voiceProcessing:u},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:u,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?ka():o==="assistant"?ps():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:u!=null?u:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,u,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=ka(),s=ps();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||La,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(v){if(this.status==="resuming"||this.reconnecting)return;let w=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));if(!w){let T=Di(v,this.config.errorMessage);if(T){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(v instanceof Error?(g=(u=this.callbacks).onError)==null||g.call(u,v):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(v))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=ps();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let u=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!u){let g=Di(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,u||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var u,g,h,m,v;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),i={id:o,role:"assistant",content:"",createdAt:(u=a==null?void 0:a.createdAt)!=null?u:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let T=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}T=w.body}else w instanceof ReadableStream&&(T=w);T?await this.connectStream(T,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.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(w){let T=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(v=(m=this.callbacks).onError)==null||v.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var u,g,h,m,v,w,T,B,S,L,M,k;let r=this.messages.find(C=>C.id===e.id);if(((u=r==null?void 0:r.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(v=(m=this.callbacks).onError)==null||v.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,P=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(P.length===1){let U=typeof((T=P[0])==null?void 0:T.question)=="string"?P[0].question:"";U&&(a={[U]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(S=e.toolCall)==null?void 0:S.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([P,U])=>`${P}: ${Array.isArray(U)?U.join(", "):U}`).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:{};c.forEach((P,U)=>{let _=typeof(P==null?void 0:P.question)=="string"?P.question:"";if(!_)return;let I=C[_],$=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:$||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let P=await C.json().catch(()=>null);throw new Error((L=P==null?void 0:P.error)!=null?L:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let P=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,P||(k=(M=this.callbacks).onError)==null||k.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,u,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var k,C,P,U,_,I,$;let m=(k=h.toolCall)==null?void 0:k.name,v=(C=h.toolCall)==null?void 0:C.id;if(!m||!v)return null;let w=`${e}:${v}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let T=this.markWebMcpToolRunning(h),B=(U=(P=h.agentMetadata)==null?void 0:P.webMcpToolCallId)!=null?U:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Ei(),toolMessage:h,startedAt:T,completedAt:Date.now()};let S=new AbortController;this.webMcpResolveControllers.add(S),o.push(S);let L=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,S.signal),M;if(!L)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await L}catch(N){let te=N instanceof Error&&(N.name==="AbortError"||N.message.includes("aborted")||N.message.includes("abort"));return te||($=(I=this.callbacks).onError)==null||$.call(I,N instanceof Error?N:new Error(String(N))),this.markWebMcpToolComplete(h,Qs(te?"Aborted by cancel()":qu(N)),T),this.webMcpInflightKeys.delete(w),null}return S.signal.aborted?(this.markWebMcpToolComplete(h,Qs("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(v=>v!==null),i.length===0)return;let h={};for(let v of i)h[v.resumeKey]=v.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let v=await m.json().catch(()=>null);throw new Error((d=v==null?void 0:v.error)!=null?d:`Resume failed: ${m.status}`)}for(let v of i)this.webMcpResolvedKeys.add(v.dedupeKey),this.markWebMcpToolComplete(v.toolMessage,v.output,v.startedAt,v.completedAt,((c=v.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(u=this.callbacks).onError)==null||g.call(u,h instanceof Error?h:new Error(String(h)));else for(let v of i)this.markWebMcpToolComplete(v.toolMessage,Qs("Aborted by cancel()"),v.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var v,w,T,B,S,L,M,k,C,P,U,_;let t=(v=e.agentMetadata)==null?void 0:v.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(T=e.toolCall)==null?void 0:T.id;if(!t){(S=(B=this.callbacks).onError)==null||S.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let I=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(I)}catch($){(M=(L=this.callbacks).onError)==null||M.call(L,$ instanceof Error?$:new Error(String($)))}finally{this.webMcpInflightKeys.delete(I)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,u=(k=e.toolCall)==null?void 0:k.args,g=c?null:this.client.executeWebMcpToolCall(r,u,d),h="execute",m=a;try{let I;if(c?I=Ei():g?I=await g:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,Qs("Aborted by cancel()"),a);return}let $=(P=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?P:r;h="resume",await this.resumeWithToolOutput(t,$,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,I,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(I){let $=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(h==="execute"||$||d.aborted)&&this.markWebMcpToolComplete(e,Qs($||d.aborted?"Aborted by cancel()":qu(I)),a),$||(_=(U=this.callbacks).onError)==null||_.call(U,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]: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 e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),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(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.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(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=import("./session-reconnect-U77QFUR7.js").then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Di(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=ps(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.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=Hi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Ia(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=Hi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var u,g,h,m,v,w,T,B,S,L,M,k,C,P,U;if(s!==r)return o;let a={...o,...t};if(((u=o.agentMetadata)==null?void 0:u.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,I=t.approval;a.approval={..._,...I,executionId:I.executionId||_.executionId,toolName:I.toolName||_.toolName,description:I.description||_.description,toolType:(m=I.toolType)!=null?m:_.toolType,reason:(v=I.reason)!=null?v:_.reason,parameters:(w=I.parameters)!=null?w:_.parameters}}let i=(T=t.toolCall)==null?void 0:T.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(S=t.toolCall)==null?void 0:S.id;if(i&&ju(i)&&d&&c&&((L=t.agentMetadata)==null?void 0:L.awaitingLocalTool)===!0){let _=`${d}:${c}`,I=this.webMcpInflightKeys.has(_),$=this.webMcpResolvedKeys.has(_),N=(M=o.toolCall)==null?void 0:M.name,te=((k=o.agentMetadata)==null?void 0:k.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&N!==void 0&&ju(N)&&((P=o.toolCall)==null?void 0:P.status)==="complete";(I||$||te)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};import{Activity as eh,ArrowDown as th,ArrowUp as nh,ArrowUpRight as rh,Bot as oh,ChevronDown as sh,ChevronUp as ah,ChevronRight as ih,ChevronLeft as lh,Check as ch,Clipboard as dh,ClipboardCopy as ph,Copy as uh,File as mh,FileCode as gh,FileSpreadsheet as fh,FileText as hh,ImagePlus as yh,Loader as bh,LoaderCircle as vh,Mic as wh,Paperclip as xh,RefreshCw as Ch,Search as Ah,Send as Sh,ShieldAlert as Th,ShieldCheck as Mh,ShieldX as Eh,Square as kh,ThumbsDown as Lh,ThumbsUp as Ph,Upload as Ih,Volume2 as Wh,X as Rh,User as Hh,Mail as Bh,Phone as Dh,Calendar as Nh,Clock as Fh,Building as Oh,MapPin as _h,Lock as $h,Key as Uh,CreditCard as zh,AtSign as qh,Hash as jh,Globe as Vh,Link as Kh,CircleCheck as Gh,CircleX as Qh,TriangleAlert as Xh,Info as Jh,Ban as Yh,Shield as Zh,ArrowLeft as ey,ArrowRight as ty,ExternalLink as ny,Ellipsis as ry,EllipsisVertical as oy,Menu as sy,House as ay,Plus as iy,Minus as ly,Pencil as cy,Trash as dy,Trash2 as py,Save as uy,Download as my,Share as gy,Funnel as fy,Settings as hy,RotateCw as yy,Maximize as by,Minimize as vy,ShoppingCart as wy,ShoppingBag as xy,Package as Cy,Truck as Ay,Tag as Sy,Gift as Ty,Receipt as My,Wallet as Ey,Store as ky,DollarSign as Ly,Percent as Py,Play as Iy,Pause as Wy,VolumeX as Ry,Camera as Hy,Image as By,Film as Dy,Headphones as Ny,MessageCircle as Fy,MessageSquare as Oy,Bell as _y,Heart as $y,Star as Uy,Eye as zy,EyeOff as qy,Bookmark as jy,CalendarDays as Vy,History as Ky,Timer as Gy,Folder as Qy,FolderOpen as Xy,Files as Jy,Sparkles as Yy,Zap as Zy,Sun as eb,Moon as tb,Flag as nb,Monitor as rb,Smartphone as ob}from"lucide";var sb={activity:eh,"arrow-down":th,"arrow-up":nh,"arrow-up-right":rh,bot:oh,"chevron-down":sh,"chevron-up":ah,"chevron-right":ih,"chevron-left":lh,check:ch,clipboard:dh,"clipboard-copy":ph,copy:uh,file:mh,"file-code":gh,"file-spreadsheet":fh,"file-text":hh,"image-plus":yh,loader:bh,"loader-circle":vh,mic:wh,paperclip:xh,"refresh-cw":Ch,search:Ah,send:Sh,"shield-alert":Th,"shield-check":Mh,"shield-x":Eh,square:kh,"thumbs-down":Lh,"thumbs-up":Ph,upload:Ih,"volume-2":Wh,x:Rh,user:Hh,mail:Bh,phone:Dh,calendar:Nh,clock:Fh,building:Oh,"map-pin":_h,lock:$h,key:Uh,"credit-card":zh,"at-sign":qh,hash:jh,globe:Vh,link:Kh,"circle-check":Gh,"circle-x":Qh,"triangle-alert":Xh,info:Jh,ban:Yh,shield:Zh,"arrow-left":ey,"arrow-right":ty,"external-link":ny,ellipsis:ry,"ellipsis-vertical":oy,menu:sy,house:ay,plus:iy,minus:ly,pencil:cy,trash:dy,"trash-2":py,save:uy,download:my,share:gy,funnel:fy,settings:hy,"rotate-cw":yy,maximize:by,minimize:vy,"shopping-cart":wy,"shopping-bag":xy,package:Cy,truck:Ay,tag:Sy,gift:Ty,receipt:My,wallet:Ey,store:ky,"dollar-sign":Ly,percent:Py,play:Iy,pause:Wy,"volume-x":Ry,camera:Hy,image:By,film:Dy,headphones:Ny,"message-circle":Fy,"message-square":Oy,bell:_y,heart:$y,star:Uy,eye:zy,"eye-off":qy,bookmark:jy,"calendar-days":Vy,history:Ky,timer:Gy,folder:Qy,"folder-open":Xy,files:Jy,sparkles:Yy,zap:Zy,sun:eb,moon:tb,flag:nb,monitor:rb,smartphone:ob},he=(n,e=24,t="currentColor",r=2)=>{let o=sb[n];return o?ab(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ab(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.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(([c,u])=>{c!=="stroke"&&d.setAttribute(c,String(u))}),o.appendChild(d)}),o}var Ra={allowedTypes:qr,maxFileSize:10*1024*1024,maxFiles:4};function ib(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function lb(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var Xs=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ra.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ra.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ra.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ra.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let u=Fu(c,this.config.allowedTypes,this.config.maxFileSize);if(!u.valid){let g=(o=u.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Nu(c),h=Pa(c)?URL.createObjectURL(c):null,m={id:ib(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Pa(e.file),r=b("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=b("img");a.src=e.previewUrl,a.alt=e.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=b("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=lb(e.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=b("span");c.textContent=Ou(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=b("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=he("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(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var Vu=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function Js(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];Vu(s)&&Vu(o)?t[r]=Js(s,o):t[r]=o}return t}var jr="min(440px, calc(100vw - 24px))",Gu="440px",cb={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:jr,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)"},Ht={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:cb,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:"anchor-top",anchorTopOffset:16,showActivityWhilePinned:!0},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 Ku(n,e){if(!(!n&&!e))return n?e?Js(n,e):n:e}function Qu(n){var e,t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k;return n?{...Ht,...n,theme:Ku(Ht.theme,n.theme),darkTheme:Ku(Ht.darkTheme,n.darkTheme),launcher:{...Ht.launcher,...n.launcher,dock:{...(e=Ht.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Ht.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Ht.copy,...n.copy},sendButton:{...Ht.sendButton,...n.sendButton},statusIndicator:{...Ht.statusIndicator,...n.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...n.voiceRecognition},features:(()=>{var ne,re,ce,Ce,_e,V,X,Ae,J,ie;let C=(ne=Ht.features)==null?void 0:ne.artifacts,P=(re=n.features)==null?void 0:re.artifacts,U=(ce=Ht.features)==null?void 0:ce.scrollToBottom,_=(Ce=n.features)==null?void 0:Ce.scrollToBottom,I=(_e=Ht.features)==null?void 0:_e.scrollBehavior,$=(V=n.features)==null?void 0:V.scrollBehavior,N=(X=Ht.features)==null?void 0:X.streamAnimation,te=(Ae=n.features)==null?void 0:Ae.streamAnimation,Ee=(J=Ht.features)==null?void 0:J.askUserQuestion,de=(ie=n.features)==null?void 0:ie.askUserQuestion,Y=C===void 0&&P===void 0?void 0:{...C,...P,layout:{...C==null?void 0:C.layout,...P==null?void 0:P.layout}},Le=U===void 0&&_===void 0?void 0:{...U,..._},Pe=I===void 0&&$===void 0?void 0:{...I,...$},ae=N===void 0&&te===void 0?void 0:{...N,...te},fe=Ee===void 0&&de===void 0?void 0:{...Ee,...de,styles:{...Ee==null?void 0:Ee.styles,...de==null?void 0:de.styles}};return{...Ht.features,...n.features,...Le!==void 0?{scrollToBottom:Le}:{},...Pe!==void 0?{scrollBehavior:Pe}:{},...Y!==void 0?{artifacts:Y}:{},...ae!==void 0?{streamAnimation:ae}:{},...fe!==void 0?{askUserQuestion:fe}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Ht.layout,...n.layout,header:{...(a=Ht.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Ht.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(u=Ht.layout)==null?void 0:u.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(v=Ht.layout)==null?void 0:v.messages)==null?void 0:w.timestamp,...(B=(T=n.layout)==null?void 0:T.messages)==null?void 0:B.timestamp}},slots:{...(S=Ht.layout)==null?void 0:S.slots,...(L=n.layout)==null?void 0:L.slots}},markdown:{...Ht.markdown,...n.markdown,options:{...(M=Ht.markdown)==null?void 0:M.options,...(k=n.markdown)==null?void 0:k.options}},messageActions:{...Ht.messageActions,...n.messageActions}}:Ht}var db={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"}},pb={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"}},ub={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:jr,maxWidth:Gu,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 gs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?gs(n,r):r}function Xu(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=gs(n,a);d!==void 0&&(e[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&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function mb(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function Ju(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=Ju(s,o):t[r]=o}return t}function gb(n,e){return e?Ju(n,e):n}function $o(n,e={}){var o,s,a,i,d,c,u,g,h,m,v,w,T;let t={palette:db,semantic:pb,components:ub},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(u=n==null?void 0:n.semantic)==null?void 0:u.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(v=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:v.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(T=n==null?void 0:n.semantic)==null?void 0:T.typography}},components:gb(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=mb(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(S=>S.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function Yu(n){var w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce,Ce,_e,V,X,Ae,J,ie,Se,Je,et,Wt,ft,rt,ue,Q,it,je,Te,we,Ye,qt,ye,pe,wn,Ct,gn,fr,hr,Ue,E,me,Me,ke,Re,tt,Qe,ht,ge,H,be,le,gt,Ke,Lt,Et,vt,Rt,Qt,Ft,Zt,yr,Wr,nr,rr,Vr,jt,or,Rr,Hn,kn,Bn,sr,br,Kr,jn,Gr,At,vr,wr,Hr,ar,yt,wo,xr,xo,Ln,Ko,Qr,Br,Xr,Jr,Co,Ao,Yr,wt,Dn,Nn,xn,St,Vn,Kn,Fn,Zr;let e=Xu(n),t={};for(let[xe,Dr]of Object.entries(e)){let Gn=xe.replace(/\./g,"-");t[`--persona-${Gn}`]=Dr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(T=t["--persona-semantic-colors-secondary"])!=null?T:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(S=t["--persona-semantic-colors-surface"])!=null?S:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(L=t["--persona-semantic-colors-background"])!=null?L:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(k=t["--persona-semantic-colors-text"])!=null?k:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(P=t["--persona-semantic-colors-text-inverse"])!=null?P:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(U=t["--persona-semantic-colors-border"])!=null?U:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(I=t["--persona-components-voice-recording-indicator"])!=null?I:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=($=t["--persona-components-voice-recording-background"])!=null?$:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(N=t["--persona-components-voice-processing-icon"])!=null?N:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(te=t["--persona-components-voice-speaking-icon"])!=null?te:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(Ee=t["--persona-components-approval-requested-background"])!=null?Ee:t["--persona-surface"],t["--persona-approval-border"]=(de=t["--persona-components-approval-requested-border"])!=null?de:t["--persona-border"],t["--persona-approval-text"]=(Y=t["--persona-components-approval-requested-text"])!=null?Y:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Le=t["--persona-components-approval-requested-shadow"])!=null?Le:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Pe=t["--persona-components-approval-approve-background"])!=null?Pe:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ae=t["--persona-components-approval-deny-background"])!=null?ae:t["--persona-container"],t["--persona-attachment-image-bg"]=(fe=t["--persona-components-attachment-image-background"])!=null?fe:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(ne=t["--persona-components-attachment-image-border"])!=null?ne:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(re=t["--persona-semantic-typography-fontFamily"])!=null?re:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(ce=t["--persona-semantic-typography-fontSize"])!=null?ce:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ce=t["--persona-semantic-typography-fontWeight"])!=null?Ce:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=(_e=t["--persona-semantic-typography-lineHeight"])!=null?_e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(V=t["--persona-palette-radius-sm"])!=null?V:"0.125rem",t["--persona-radius-md"]=(X=t["--persona-palette-radius-md"])!=null?X:"0.375rem",t["--persona-radius-lg"]=(Ae=t["--persona-palette-radius-lg"])!=null?Ae:"0.5rem",t["--persona-radius-xl"]=(J=t["--persona-palette-radius-xl"])!=null?J:"0.75rem",t["--persona-radius-full"]=(ie=t["--persona-palette-radius-full"])!=null?ie:"9999px",t["--persona-launcher-radius"]=(Je=(Se=t["--persona-components-launcher-borderRadius"])!=null?Se:t["--persona-palette-radius-full"])!=null?Je:"9999px",t["--persona-launcher-bg"]=(et=t["--persona-components-launcher-background"])!=null?et:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ft=t["--persona-components-launcher-border"])!=null?ft:t["--persona-border"],t["--persona-button-primary-bg"]=(rt=t["--persona-components-button-primary-background"])!=null?rt:t["--persona-primary"],t["--persona-button-primary-fg"]=(ue=t["--persona-components-button-primary-foreground"])!=null?ue:t["--persona-text-inverse"],t["--persona-button-radius"]=(it=(Q=t["--persona-components-button-primary-borderRadius"])!=null?Q:t["--persona-palette-radius-full"])!=null?it:"9999px",t["--persona-panel-radius"]=(Te=(je=t["--persona-components-panel-borderRadius"])!=null?je:t["--persona-radius-xl"])!=null?Te:"0.75rem",t["--persona-panel-border"]=(we=t["--persona-components-panel-border"])!=null?we:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(qt=(Ye=t["--persona-components-panel-shadow"])!=null?Ye:t["--persona-palette-shadows-xl"])!=null?qt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(ye=t["--persona-components-launcher-shadow"])!=null?ye:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(wn=(pe=t["--persona-components-input-borderRadius"])!=null?pe:t["--persona-radius-lg"])!=null?wn:"0.5rem",t["--persona-message-user-radius"]=(gn=(Ct=t["--persona-components-message-user-borderRadius"])!=null?Ct:t["--persona-radius-lg"])!=null?gn:"0.5rem",t["--persona-message-assistant-radius"]=(hr=(fr=t["--persona-components-message-assistant-borderRadius"])!=null?fr:t["--persona-radius-lg"])!=null?hr:"0.5rem",t["--persona-header-bg"]=(Ue=t["--persona-components-header-background"])!=null?Ue:t["--persona-surface"],t["--persona-header-border"]=(E=t["--persona-components-header-border"])!=null?E:t["--persona-divider"],t["--persona-header-icon-bg"]=(me=t["--persona-components-header-iconBackground"])!=null?me:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(ke=t["--persona-components-header-titleForeground"])!=null?ke:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(Re=t["--persona-components-header-subtitleForeground"])!=null?Re:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(tt=t["--persona-components-header-actionIconForeground"])!=null?tt:t["--persona-muted"];let r=(Qe=n.components)==null?void 0:Qe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(ht=n.components)==null?void 0:ht.introCard;t["--persona-intro-card-bg"]=(ge=t["--persona-components-introCard-background"])!=null?ge:t["--persona-surface"],t["--persona-intro-card-radius"]=(H=t["--persona-components-introCard-borderRadius"])!=null?H:"1rem",t["--persona-intro-card-padding"]=(be=t["--persona-components-introCard-padding"])!=null?be:"1.5rem",t["--persona-intro-card-shadow"]=(gt=(le=o==null?void 0:o.shadow)!=null?le:t["--persona-components-introCard-shadow"])!=null?gt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ke=t["--persona-components-input-background"])!=null?Ke:t["--persona-surface"],t["--persona-input-placeholder"]=(Lt=t["--persona-components-input-placeholder"])!=null?Lt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(Et=t["--persona-components-message-user-background"])!=null?Et:t["--persona-accent"],t["--persona-message-user-text"]=(vt=t["--persona-components-message-user-text"])!=null?vt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Rt=t["--persona-components-message-user-shadow"])!=null?Rt:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Qt=t["--persona-components-message-assistant-background"])!=null?Qt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ft=t["--persona-components-message-assistant-text"])!=null?Ft:t["--persona-text"],t["--persona-message-assistant-border"]=(Zt=t["--persona-components-message-assistant-border"])!=null?Zt:t["--persona-border"],t["--persona-message-assistant-shadow"]=(yr=t["--persona-components-message-assistant-shadow"])!=null?yr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(nr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?nr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Vr=(rr=t["--persona-components-scrollToBottom-foreground"])!=null?rr:t["--persona-button-primary-fg"])!=null?Vr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(jt=t["--persona-components-scrollToBottom-border"])!=null?jt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(or=t["--persona-components-scrollToBottom-size"])!=null?or:"40px",t["--persona-scroll-to-bottom-radius"]=(kn=(Hn=(Rr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Rr:t["--persona-button-radius"])!=null?Hn:t["--persona-radius-full"])!=null?kn:"9999px",t["--persona-scroll-to-bottom-shadow"]=(sr=(Bn=t["--persona-components-scrollToBottom-shadow"])!=null?Bn:t["--persona-palette-shadows-sm"])!=null?sr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(br=t["--persona-components-scrollToBottom-padding"])!=null?br:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Kr=t["--persona-components-scrollToBottom-gap"])!=null?Kr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Gr=(jn=t["--persona-components-scrollToBottom-fontSize"])!=null?jn:t["--persona-palette-typography-fontSize-sm"])!=null?Gr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(At=t["--persona-components-scrollToBottom-iconSize"])!=null?At:"14px",t["--persona-tool-bubble-shadow"]=(vr=t["--persona-components-toolBubble-shadow"])!=null?vr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(wr=t["--persona-components-reasoningBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Hr=t["--persona-components-composer-shadow"])!=null?Hr:"none",t["--persona-md-inline-code-bg"]=(ar=t["--persona-components-markdown-inlineCode-background"])!=null?ar:t["--persona-container"],t["--persona-md-inline-code-color"]=(yt=t["--persona-components-markdown-inlineCode-foreground"])!=null?yt:t["--persona-text"],t["--persona-md-link-color"]=(xr=(wo=t["--persona-components-markdown-link-foreground"])!=null?wo:t["--persona-accent"])!=null?xr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(xo=t["--persona-components-markdown-codeBlock-background"])!=null?xo:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Ln=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Ln:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Ko=t["--persona-components-markdown-codeBlock-textColor"])!=null?Ko:"inherit",t["--persona-md-table-header-bg"]=(Qr=t["--persona-components-markdown-table-headerBackground"])!=null?Qr:t["--persona-container"],t["--persona-md-table-border-color"]=(Br=t["--persona-components-markdown-table-borderColor"])!=null?Br:t["--persona-border"],t["--persona-md-hr-color"]=(Xr=t["--persona-components-markdown-hr-color"])!=null?Xr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Jr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Jr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(Co=t["--persona-components-markdown-blockquote-background"])!=null?Co:"transparent",t["--persona-md-blockquote-text-color"]=(Ao=t["--persona-components-markdown-blockquote-textColor"])!=null?Ao:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Yr=t["--persona-components-collapsibleWidget-container"])!=null?Yr:t["--persona-surface"],t["--cw-surface"]=(wt=t["--persona-components-collapsibleWidget-surface"])!=null?wt:t["--persona-surface"],t["--cw-border"]=(Dn=t["--persona-components-collapsibleWidget-border"])!=null?Dn:t["--persona-border"],t["--persona-message-border"]=(Nn=t["--persona-components-message-border"])!=null?Nn:t["--persona-border"];let u=n.components,g=u==null?void 0:u.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=u==null?void 0:u.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=u==null?void 0:u.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let v=u==null?void 0:u.artifact;if(v!=null&&v.toolbar){let xe=v.toolbar;xe.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=xe.iconHoverColor),xe.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=xe.iconHoverBackground),xe.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=xe.iconPadding),xe.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=xe.iconBorderRadius),xe.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=xe.iconBorder),xe.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=xe.toggleGroupGap),xe.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=xe.toggleBorderRadius),xe.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=xe.copyBackground),xe.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=xe.copyBorder),xe.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=xe.copyColor),xe.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=xe.copyBorderRadius),xe.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=xe.copyPadding),xe.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=xe.copyMenuBackground,t["--persona-dropdown-bg"]=(xn=t["--persona-dropdown-bg"])!=null?xn:xe.copyMenuBackground),xe.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=xe.copyMenuBorder,t["--persona-dropdown-border"]=(St=t["--persona-dropdown-border"])!=null?St:xe.copyMenuBorder),xe.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=xe.copyMenuShadow,t["--persona-dropdown-shadow"]=(Vn=t["--persona-dropdown-shadow"])!=null?Vn:xe.copyMenuShadow),xe.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=xe.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Kn=t["--persona-dropdown-radius"])!=null?Kn:xe.copyMenuBorderRadius),xe.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=xe.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(Fn=t["--persona-dropdown-item-hover-bg"])!=null?Fn:xe.copyMenuItemHoverBackground),xe.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=xe.iconBackground),xe.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=xe.toolbarBorder)}if(v!=null&&v.tab){let xe=v.tab;xe.background&&(t["--persona-artifact-tab-bg"]=xe.background),xe.activeBackground&&(t["--persona-artifact-tab-active-bg"]=xe.activeBackground),xe.activeBorder&&(t["--persona-artifact-tab-active-border"]=xe.activeBorder),xe.borderRadius&&(t["--persona-artifact-tab-radius"]=xe.borderRadius),xe.textColor&&(t["--persona-artifact-tab-color"]=xe.textColor),xe.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=xe.hoverBackground),xe.listBackground&&(t["--persona-artifact-tab-list-bg"]=xe.listBackground),xe.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=xe.listBorderColor),xe.listPadding&&(t["--persona-artifact-tab-list-padding"]=xe.listPadding)}if(v!=null&&v.pane){let xe=v.pane;if(xe.toolbarBackground){let Dr=(Zr=gs(n,xe.toolbarBackground))!=null?Zr:xe.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Dr}}return t}var fb={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"}}},Zu=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ni=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},hb=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ni()},yb=n=>hb(n),bb=n=>$o(n),vb=n=>{var t;let e=$o(void 0,{validate:!1});return $o({...n,palette:{...e.palette,colors:{...fb.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},Ha=n=>{let e=yb(n),t=Zu(n==null?void 0:n.theme),r=Zu(n==null?void 0:n.darkTheme);return e==="dark"?vb(Js(t!=null?t:{},r!=null?r:{})):bb(t)},wb=n=>Yu(n),fs=(n,e)=>{let t=Ha(e),r=wb(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},em=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ni())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ni());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};import{Idiomorph as xb}from"idiomorph";var Ba=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;xb.morph(n,e.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-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;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:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var tm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var Da={index:-1,draft:""};function nm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Da}}}function rm(n,e){var t,r,o,s,a,i,d,c,u,g,h,m,v,w,T,B,S,L,M,k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe,ne,re,ce;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(u=(c=n.llmContent)==null?void 0:c.length)!=null?u:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(v=(m=n.toolCall)==null?void 0:m.status)!=null?v:"",(T=(w=n.toolCall)==null?void 0:w.name)!=null?T:"",(L=(S=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:S.length)!=null?L:0,(P=(C=(k=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:k[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?P:"",typeof((U=n.toolCall)==null?void 0:U.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(N=($=(I=n.reasoning)==null?void 0:I.chunks)==null?void 0:$.length)!=null?N:0,(Y=(de=(Ee=(te=n.reasoning)==null?void 0:te.chunks)==null?void 0:Ee[n.reasoning.chunks.length-1])==null?void 0:de.length)!=null?Y:0,(fe=(ae=(Pe=(Le=n.reasoning)==null?void 0:Le.chunks)==null?void 0:Pe[n.reasoning.chunks.length-1])==null?void 0:ae.slice(-32))!=null?fe:"",(re=(ne=n.contentParts)==null?void 0:ne.length)!=null?re:0,(ce=n.stopReason)!=null?ce:"",e].join("\0")}function om(){return new Map}function sm(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function am(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function im(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Na(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Ir(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function yo(n,e){return Ir(n)-n.scrollTop<=e}function Fa(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,u=t-r;return a||Math.abs(u)<s?{action:"none",delta:u,nextLastScrollTop:t}:!e&&o&&(!c||u>0)?{action:"resume",delta:u,nextLastScrollTop:t}:e&&i&&u<0?{action:"pause",delta:u,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:u,nextLastScrollTop:t}:{action:"none",delta:u,nextLastScrollTop:t}}function Oa(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function lm(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function cm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function dm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var tn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},bn=1e5,bo=bn+1;var Ys={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Cb=["pre","code","a","script","style"],_a=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:Ys.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:Ys.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:Ys.speed,duration:(o=n==null?void 0:n.duration)!=null?o:Ys.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:Ys.buffer}},Ab=[{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"}],um=new Map;for(let n of Ab)um.set(n.name,n);var hs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=um.get(n))!=null?r:null},$a=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
19
19
  `);return s<0?"":n.slice(0,s)}return n},Sb=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Tb=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Fi=/\s/,Mb=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Eb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Fi.test(s[i])){let c=i;for(;c<s.length&&Fi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let u=i;for(;u<s.length&&!Fi.test(s[u]);)c.appendChild(Sb(r,s[u],e,t.value)),t.value+=1,u+=1;a.appendChild(c),i=u}o.replaceChild(a,n)},kb=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Tb(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},Zs=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:Cb).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Mb(d,s)||i.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},u=e==="char"?Eb:kb;for(let m of i)u(m,t,c);return o.innerHTML},Ua=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},ea=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},pm=new WeakMap,Lb=(n,e)=>{var s;if(!n.styles)return;let t=pm.get(e);if(t||(t=new Set,pm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Oi=new WeakMap,Pb=(n,e)=>{if(!n.onAttach)return;let t=Oi.get(e);if(t||(t=new Map,Oi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},mm=n=>{let e=Oi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},za=(n,e)=>{Lb(n,e),Pb(n,e)};function _i(n,e=bn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var ta=0,vo=null;function $i(n=document){var t;if(ta++,ta===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;vo={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 e=!1;return()=>{var r;if(!e&&(e=!0,ta=Math.max(0,ta-1),ta===0&&vo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=vo.originalOverflow,o.style.position=vo.originalPosition,o.style.top=vo.originalTop,o.style.width=vo.originalWidth,s.scrollTo(0,vo.scrollY),vo=null}}}var na={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},mn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},ra=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},mr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:na.side,width:(o=e==null?void 0:e.width)!=null?o:na.width,animate:(s=e==null?void 0:e.animate)!=null?s:na.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:na.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:na.maxHeight}};var gr={"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 Ib="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",qa=(n,e={})=>{var T,B,S,L,M,k;let{showClose:t=!0,wrapperClassName:r=Ib,buttonSize:o,iconSize:s="28px"}=e,a=(T=n==null?void 0:n.launcher)!=null?T:{},i=(B=o!=null?o:a.closeButtonSize)!=null?B:"32px",d=b("div",r),c=(S=a.closeButtonTooltipText)!=null?S:"Close chat",u=(L=a.closeButtonShowTooltip)!=null?L:!0,g=(M=a.closeButtonIconName)!=null?M:"x",h=(k=a.closeButtonIconText)!=null?k:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),v=Mt("button",{className:Os("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||En.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${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}}),w=he(g,s,"currentColor",1);if(w?(w.style.display="block",v.appendChild(w)):v.textContent=h,d.appendChild(v),u&&c){let C=null,P=()=>{if(C)return;let _=v.ownerDocument,I=_.body;if(!I)return;C=Pr(_,"div","persona-clear-chat-tooltip"),C.textContent=c;let $=Pr(_,"div");$.className="persona-clear-chat-tooltip-arrow",C.appendChild($);let N=v.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(bo),C.style.left=`${N.left+N.width/2}px`,C.style.top=`${N.top-8}px`,C.style.transform="translate(-50%, -100%)",I.appendChild(C)},U=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",P),d.addEventListener("mouseleave",U),v.addEventListener("focus",P),v.addEventListener("blur",U),d._cleanupTooltip=()=>{U(),d.removeEventListener("mouseenter",P),d.removeEventListener("mouseleave",U),v.removeEventListener("focus",P),v.removeEventListener("blur",U)}}return{button:v,wrapper:d}},Wb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ja=(n,e={})=>{var C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe;let{wrapperClassName:t=Wb,buttonSize:r,iconSize:o="20px"}=e,a=(P=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?P:{},i=(U=r!=null?r:a.size)!=null?U:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(I=a.iconColor)!=null?I:"",u=($=a.backgroundColor)!=null?$:"",g=(N=a.borderWidth)!=null?N:"",h=(te=a.borderColor)!=null?te:"",m=(Ee=a.borderRadius)!=null?Ee:"",v=(de=a.paddingX)!=null?de:"",w=(Y=a.paddingY)!=null?Y:"",T=(Le=a.tooltipText)!=null?Le:"Clear chat",B=(Pe=a.showTooltip)!=null?Pe:!0,S=b("div",t),L=!!(g||h),M=Mt("button",{className:Os("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!u&&"hover:persona-bg-gray-100",!L&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:c||En.actionIconColor,backgroundColor:u||void 0,border:L?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:v||void 0,paddingRight:v||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),k=he(d,o,"currentColor",1);if(k&&(k.style.display="block",M.appendChild(k)),S.appendChild(M),B&&T){let ae=null,fe=()=>{if(ae)return;let re=M.ownerDocument,ce=re.body;if(!ce)return;ae=Pr(re,"div","persona-clear-chat-tooltip"),ae.textContent=T;let Ce=Pr(re,"div");Ce.className="persona-clear-chat-tooltip-arrow",ae.appendChild(Ce);let _e=M.getBoundingClientRect();ae.style.position="fixed",ae.style.zIndex=String(bo),ae.style.left=`${_e.left+_e.width/2}px`,ae.style.top=`${_e.top-8}px`,ae.style.transform="translate(-50%, -100%)",ce.appendChild(ae)},ne=()=>{ae&&ae.parentNode&&(ae.parentNode.removeChild(ae),ae=null)};S.addEventListener("mouseenter",fe),S.addEventListener("mouseleave",ne),M.addEventListener("focus",fe),M.addEventListener("blur",ne),S._cleanupTooltip=()=>{ne(),S.removeEventListener("mouseenter",fe),S.removeEventListener("mouseleave",ne),M.removeEventListener("focus",fe),M.removeEventListener("blur",ne)}}return{button:M,wrapper:S}};var En={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))"},Uo=n=>{var k,C,P,U,_,I,$,N,te,Ee,de,Y,Le,Pe,ae,fe;let{config:e,showClose:t=!0}=n,r=Mt("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=(k=e==null?void 0:e.launcher)!=null?k:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(P=o.closeButtonPlacement)!=null?P:"inline",i=(U=o.headerIconHidden)!=null?U:!1,d=o.headerIconName,c=Mt("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 ne=parseFloat(s)||24,re=he(d,ne*.6,"currentColor",1);re?c.replaceChildren(re):c.textContent=(I=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?I:"\u{1F4AC}"}else if(($=e==null?void 0:e.launcher)!=null&&$.iconUrl){let ne=b("img");ne.src=e.launcher.iconUrl,ne.alt="",ne.className="persona-rounded-xl persona-object-cover",ne.style.height=s,ne.style.width=s,c.replaceChildren(ne)}else c.textContent=(te=(N=e==null?void 0:e.launcher)==null?void 0:N.agentIconText)!=null?te:"\u{1F4AC}";let u=b("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(de=(Ee=e==null?void 0:e.launcher)==null?void 0:Ee.title)!=null?de:"Chat Assistant",style:{color:En.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Le=(Y=e==null?void 0:e.launcher)==null?void 0:Y.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:En.subtitleColor}});u.append(g,h),i?r.append(u):r.append(c,u);let m=(Pe=o.clearChat)!=null?Pe:{},v=(ae=m.enabled)!=null?ae:!0,w=(fe=m.placement)!=null?fe:"inline",T=null,B=null;if(v){let re=ja(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=re.button,B=re.wrapper,w==="top-right"&&(B.style.right="48px"),w==="inline"&&r.appendChild(B)}let S=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":v&&w==="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:L,wrapper:M}=qa(e,{showClose:t,wrapperClassName:S});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:L,closeButtonWrapper:M,clearChatButton:T,clearChatButtonWrapper:B}},oa=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function ys(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=b("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(bo)):(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 m of e){if(m.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let v=document.createElement("button");if(v.type="button",v.setAttribute("role","menuitem"),v.setAttribute("data-dropdown-item-id",m.id),m.destructive&&v.setAttribute("data-destructive",""),m.icon){let T=he(m.icon,16,"currentColor",1.5);T&&v.appendChild(T)}let w=document.createElement("span");w.textContent=m.label,v.appendChild(w),v.addEventListener("click",T=>{T.stopPropagation(),u(),t(m.id)}),a.appendChild(v)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=v=>{!a.contains(v.target)&&!r.contains(v.target)&&u()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function u(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?c():u()}function h(){u(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:u,toggle:g,destroy:h}}function vn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=b("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=he(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[u,g]of Object.entries(i))d.setAttribute(u,g);return d}function Ui(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let u=b("button",c);if(u.type="button",u.setAttribute("aria-label",t),e){let h=he(e,s!=null?s:14,"currentColor",2);h&&u.appendChild(h)}let g=b("span");if(g.textContent=t,u.appendChild(g),i&&u.addEventListener("click",i),d)for(let[h,m]of Object.entries(d))u.setAttribute(h,m);return u}function gm(n){var m,v;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=b("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let u=b("span","persona-combo-btn-label");u.textContent=e,c.appendChild(u);let g=he(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(v=d.padding)!=null?v:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var w,T;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=ys({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let T=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{u.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var Rb=n=>{var r;let e=Uo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function Hb(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=b("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=he(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=b("div","persona-relative");d.appendChild(i);let c=ys({items:a.menuItems,onSelect:u=>t==null?void 0:t(u),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",u=>{u.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var Bb=n=>{var S,L,M,k,C,P,U,_,I;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(S=e==null?void 0:e.launcher)!=null?S:{},i=b("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,c,u;if(d)c=gm({label:(L=a.title)!=null?L:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=En.titleColor,u=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=b("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),u=b("span","persona-text-base persona-font-semibold persona-truncate"),u.style.color=En.titleColor,u.textContent=(k=a.title)!=null?k:"Chat Assistant",c.appendChild(u),Hb(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let N=o.onTitleClick;c.addEventListener("click",te=>{te.target.closest("button")||N()}),c.addEventListener("keydown",te=>{(te.key==="Enter"||te.key===" ")&&(te.preventDefault(),N())})}let $=o==null?void 0:o.titleRowHover;$&&(c.style.borderRadius=(P=$.borderRadius)!=null?P:"10px",c.style.padding=(U=$.padding)!=null?U:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var N,te;c.style.backgroundColor=(N=$.background)!=null?N:"",c.style.borderColor=(te=$.border)!=null?te:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let g=(_=a.closeButtonSize)!=null?_:"32px",h=b("div",""),m=b("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||En.actionIconColor;let v=(I=a.closeButtonIconName)!=null?I:"x",w=he(v,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),i.appendChild(h);let T=b("div");T.style.display="none";let B=b("span");return B.style.display="none",{header:i,iconHolder:T,headerTitle:u,headerSubtitle:B,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},fm={default:Rb,minimal:Bb},Db=n=>{var e;return(e=fm[n])!=null?e:fm.default},Va=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),u=b("div");u.style.display="none";let g=b("span"),h=b("span"),m=b("button");m.style.display="none";let v=b("div");return v.style.display="none",{header:c,iconHolder:u,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:v,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=Db(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Ka=n=>{var a,i;let e=b("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.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",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},Ga=n=>{var k,C,P,U,_,I,$,N,te,Ee,de,Y;let e=(k=n==null?void 0:n.sendButton)!=null?k:{},t=(C=e.useIcon)!=null?C:!1,r=(P=e.iconText)!=null?P:"\u2191",o=e.iconName,s=(U=e.stopIconName)!=null?U:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(I=e.stopTooltipText)!=null?I:"Stop generating",d=(N=($=n==null?void 0:n.copy)==null?void 0:$.sendButtonLabel)!=null?N:"Send",c=(Ee=(te=n==null?void 0:n.copy)==null?void 0:te.stopButtonLabel)!=null?Ee:"Stop",u=(de=e.showTooltip)!=null?de:!1,g=(Y=e.size)!=null?Y:"40px",h=e.backgroundColor,m=e.textColor,v=b("div","persona-send-button-wrapper"),w=Mt("button",{className:Os("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),T=null,B=null;if(t){let Le=parseFloat(g)||24,Pe=(m==null?void 0:m.trim())||"currentColor";o?(T=he(o,Le,Pe,2),T?w.appendChild(T):w.textContent=r):w.textContent=r,B=he(s,Le,Pe,2)}else w.textContent=d;let S=null;u&&a&&(S=b("div","persona-send-button-tooltip"),S.textContent=a,v.appendChild(S)),w.setAttribute("aria-label",a),v.appendChild(w);let L="send";return{button:w,wrapper:v,setMode:Le=>{if(Le===L)return;L=Le;let Pe=Le==="stop"?i:a;if(w.setAttribute("aria-label",Pe),S&&(S.textContent=Pe),t){if(T&&B){let ae=Le==="stop"?B:T;w.replaceChildren(ae)}}else w.textContent=Le==="stop"?c:d}}},Qa=n=>{var S,L,M,k,C,P,U,_,I,$,N,te;let e=(S=n==null?void 0:n.voiceRecognition)!=null?S:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((L=e.provider)==null?void 0:L.type)==="runtype";if(!(r||o))return null;let a=(k=(M=n==null?void 0:n.sendButton)==null?void 0:M.size)!=null?k:"40px",i=(C=e.iconName)!=null?C:"mic",d=(P=e.iconSize)!=null?P:a,c=parseFloat(d)||24,u=(_=e.backgroundColor)!=null?_:(U=n==null?void 0:n.sendButton)==null?void 0:U.backgroundColor,g=($=e.iconColor)!=null?$:(I=n==null?void 0:n.sendButton)==null?void 0:I.textColor,h=b("div","persona-send-button-wrapper"),m=Mt("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:g||"var(--persona-text, #111827)",backgroundColor:u||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=he(i,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let T=(N=e.tooltipText)!=null?N:"Start voice recognition";if(((te=e.showTooltip)!=null?te:!1)&&T){let Ee=b("div","persona-send-button-tooltip");Ee.textContent=T,h.appendChild(Ee)}return{button:m,wrapper:h}},Xa=n=>{var v,w,T,B,S,L,M,k;let e=(v=n==null?void 0:n.attachments)!=null?v:{};if(e.enabled!==!0)return null;let t=(T=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?T:"40px",r=b("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=b("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((B=e.allowedTypes)!=null?B:qr).join(","),o.multiple=((S=e.maxFiles)!=null?S:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(L=e.buttonIconName)!=null?L:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=b("div","persona-send-button-wrapper"),u=Mt("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=e.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"}});u.addEventListener("mouseenter",()=>{u.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),u.addEventListener("mouseleave",()=>{u.style.backgroundColor="transparent"});let g=he(s,d,"currentColor",1.5);g?u.appendChild(g):u.textContent="\u{1F4CE}",u.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(u);let h=(k=e.buttonTooltipText)!=null?k:"Attach file",m=b("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:u,wrapper:c,input:o,previewsContainer:r}},Ja=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=b("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=b("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},Ya=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Za=n=>{var v,w,T,B,S,L;let{config:e}=n,t=Mt("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=Ya(),o=Mt("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}=Ka(e);a();let i=Ga(e),d=Qa(e),c=Xa(e),u=Ja(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=b("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=b("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(h,m),o.append(g),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!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,u),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:u,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}};var hm=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=b("span","persona-pill-peek__icon"),t=he("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=b("span","persona-pill-peek__text"),o=b("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},ym=n=>{var v,w,T,B,S,L;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ya();r.style.display="none";let o=Ja(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=Ka(e);s.style.maxHeight="100px",a();let i=Ga(e),d=Qa(e),c=Xa(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let u=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=b("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=b("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(i.wrapper),u.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!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&u.append(c.input),u.append(g,s,h),c&&t.append(c.previewsContainer),t.append(u,r,o);let m=u;return{footer:t,suggestions:r,composerForm:u,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(v=d==null?void 0:d.button)!=null?v:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(S=c==null?void 0:c.input)!=null?S:null,attachmentPreviewsContainer:(L=c==null?void 0:c.previewsContainer)!=null?L:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:i.setMode}};var bm=n=>{var u,g,h,m,v,w,T,B,S,L,M,k,C,P,U,_,I;let e=(g=(u=n==null?void 0:n.launcher)==null?void 0:u.enabled)!=null?g:!0,t=mn(n);if(ra(n)){let $=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},N=b("div","persona-widget-wrapper persona-fixed persona-transition");N.setAttribute("data-persona-composer-bar",""),N.dataset.state="collapsed",N.dataset.expandedSize=(v=$.expandedSize)!=null?v:"anchored",N.style.zIndex=String((T=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?T:bn);let te=b("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");te.style.width="100%",N.appendChild(te);let Ee=b("div","persona-widget-pill-root");return Ee.setAttribute("data-persona-composer-bar",""),Ee.dataset.state="collapsed",Ee.dataset.expandedSize=(B=$.expandedSize)!=null?B:"anchored",Ee.style.zIndex=String((L=(S=n==null?void 0:n.launcher)==null?void 0:S.zIndex)!=null?L:bn),{wrapper:N,panel:te,pillRoot:Ee}}if(t){let $=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),N=b("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return $.appendChild(N),{wrapper:$,panel:N}}if(!e){let $=b("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),N=b("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),te=(k=(M=n==null?void 0:n.launcher)==null?void 0:M.width)!=null?k:"100%";return $.style.width=te,N.style.width="100%",$.appendChild(N),{wrapper:$,panel:N}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&gr[o.position]?gr[o.position]:gr["bottom-right"],a=b("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((U=(P=n==null?void 0:n.launcher)==null?void 0:P.zIndex)!=null?U:bn);let i=b("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(I=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?I:n==null?void 0:n.launcherWidth,c=d!=null?d:jr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},Nb=(n,e)=>{var M,k,C,P,U,_,I,$,N;let t=b("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=qa(n,{showClose:e,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=(k=(M=n==null?void 0:n.launcher)==null?void 0:M.clearChat)==null?void 0:k.enabled)!=null?C:!0,a=null,i=null;if(s){let te=ja(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=te.button,i=te.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("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"}});c.style.setProperty("scrollbar-gutter","stable");let u=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(U=(P=n==null?void 0:n.copy)==null?void 0:P.welcomeTitle)!=null?U:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(_=n==null?void 0:n.copy)==null?void 0:_.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),h=Mt("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))"}},u,g),m=b("div","persona-flex persona-flex-col persona-gap-3"),v=($=n==null?void 0:n.layout)==null?void 0:$.contentMaxWidth;v&&(m.style.maxWidth=v,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((N=n==null?void 0:n.copy)==null?void 0:N.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let T=Mt("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"}}),B=ym({config:n}),{root:S,textNode:L}=hm();return t.append(d,o,c,T),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:T,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:u,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:b("span"),headerTitle:b("span"),headerSubtitle:b("span"),header:d,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:S,peekTextNode:L}},vm=(n,e=!0)=>{var T,B,S,L,M,k,C,P,U;if(ra(n))return Nb(n,e);let t=Mt("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=(T=n==null?void 0:n.layout)==null?void 0:T.header,o=((B=n==null?void 0:n.layout)==null?void 0:B.showHeader)!==!1,s=r?Va(n,r,{showClose:e}):Uo({config:n,showClose:e}),a=Mt("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=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(L=(S=n==null?void 0:n.copy)==null?void 0:S.welcomeTitle)!=null?L:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(k=(M=n==null?void 0:n.copy)==null?void 0:M.welcomeSubtitle)!=null?k:"Ask anything about your account or products."}),c=Mt("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:mn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),u=b("div","persona-flex persona-flex-col persona-gap-3"),g=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;g&&(u.style.maxWidth=g,u.style.marginLeft="auto",u.style.marginRight="auto",u.style.width="100%"),((P=n==null?void 0:n.copy)==null?void 0:P.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,u);let m=Za({config:n}),v=((U=n==null?void 0:n.layout)==null?void 0:U.showFooter)!==!1;o?oa(t,s,n):(s.header.style.display="none",oa(t,s,n)),t.append(a);let w=Mt("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||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:u,composerOverlay:w,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle: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:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var zi=(n,e)=>{let t=b("button");t.type="button",t.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" />