@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.
@@ -9,14 +9,14 @@ ${t}`:"")+(e.description?`
9
9
  ${e.description}`:"");return window.confirm(r)},sb=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},ib=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},lb=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var db="agent_",cb="flow_";function zg(e){return e.startsWith(db)?{kind:"agentId",agentId:e}:e.startsWith(cb)?{kind:"flowId",flowId:e}:null}function $g(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let d=zg(i);if(d)return d;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(i).payload}}let n=zg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var Mn=La(oi(),1);var S=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Tt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},gs=(...e)=>e.filter(Boolean).join(" ");var xs="ask_user_question",hs=8,Ha="data-persona-ask-sheet-for",gb="Other",hb="Other\u2026",Kg="Type your own answer here",Xg="Send",xb="Next",yb="Back",bb="Submit all",vb="Skip",wb=3,Fl="data-ask-current-index",Nl="data-ask-question-count",Qg="data-ask-answers",Ol="data-ask-grouped",Jg="data-ask-layout",Cb=e=>e.layout==="pills"?"pills":"rows",Sb=e=>e.getAttribute(Jg)==="pills"?"pills":"rows",Gg=!1,Yg=e=>e.replace(/["\\]/g,"\\$&"),Jo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===xs,ni=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Yo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,Mn.parse)(n,Mn.STR|Mn.OBJ|Mn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ys=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>hs&&!Gg&&(Gg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${hs}.`)),t.slice(0,hs)},Ab=e=>{var t;return(t=ys(e)[0])!=null?t:null},Mb=(e,t)=>{var r;return(r=ys(e)[t])!=null?r:null},Zg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},eh=(e,t,r)=>{if(e!=="rows")return null;let o=S("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=S("span","persona-ask-row-check");o.appendChild(n)}else{let n=S("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Tb=(e,t,r,o)=>{let a=S("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=S("span","persona-ask-row-content"),i=S("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let d=S("span","persona-ask-row-description");d.textContent=e.description,s.appendChild(d)}a.appendChild(s);let c=eh(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Eb=e=>{let r=S("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},kb=(e,t,r,o)=>{var p,u,g;let a=S("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");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(f=>f&&typeof f.label=="string"&&f.label.length>0);if(c.length===0&&!r){for(let f=0;f<wb;f++)a.appendChild(Eb(o));return a}if(c.forEach((f,h)=>{a.appendChild(Tb(f,h,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let f=o==="rows"?gb:hb;if(o==="rows"){let h=S("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");h.setAttribute("data-ask-user-action","focus-free-text"),h.setAttribute("data-option-index",String(c.length)),h.setAttribute("data-ask-other-row","true");let b=S("span","persona-ask-row-content"),k=document.createElement("input");k.type="text",k.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",k.placeholder=(p=t.freeTextPlaceholder)!=null?p:Kg,k.setAttribute("data-ask-free-text-input","true"),k.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:f),b.appendChild(k),h.appendChild(b);let E=eh(o,s,c.length);E&&h.appendChild(E),a.appendChild(h)}else{let h=S("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");h.type="button",h.setAttribute("data-ask-user-action","open-free-text"),h.textContent=(g=t.freeTextLabel)!=null?g:f,a.appendChild(h)}}return a},th=(e,t)=>{var a,s;let o=S("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Kg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=S("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Xg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Lb=e=>{var o;let t=S("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=S("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Xg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Pb=(e,t,r)=>{var d,p,u,g;let o=S("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=S("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(d=r.backLabel)!=null?d:yb,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=S("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=S("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:vb,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=S("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(u=r.submitAllLabel)!=null?u:bb:(g=r.nextLabel)!=null?g:xb,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},na=e=>{let t=e.getAttribute(Qg);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},rh=(e,t)=>{e.setAttribute(Qg,JSON.stringify(t))},ao=e=>{var r;let t=Number((r=e.getAttribute(Fl))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Rb=(e,t)=>{e.setAttribute(Fl,String(Math.max(0,Math.floor(t))))},Wa=e=>{var r;let t=Number((r=e.getAttribute(Nl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},Tn=e=>e.getAttribute(Ol)==="true",Ib=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},Hb=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},ai=(e,t)=>{let{payload:r}=Yo(t),o=ys(r),n=na(e),a={},s=new Set;return o.forEach((i,c)=>{let d=typeof(i==null?void 0:i.question)=="string"?i.question:"";d&&(s.has(d)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${d}"; later answer wins.`),s.add(d),Object.prototype.hasOwnProperty.call(n,c)&&(a[d]=n[c]))}),a},oh=e=>{let t=na(e),r=ao(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var u;let d=(u=c.getAttribute("data-option-label"))!=null?u:"",p=n.has(d);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var d;return(d=c.getAttribute("data-option-label"))!=null?d:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},nh=e=>{if(!Tn(e))return;let t=na(e),r=ao(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},_l=(e,t,r)=>{let o=ni(r),n=Sb(e),{payload:a,complete:s}=Yo(t),i=Tn(e),c=ao(e),d=Wa(e),p=i?Mb(a,c):Ab(a),u=!!(p!=null&&p.multiSelect),g=e.querySelector('[data-ask-step-inline="true"]');g&&(g.textContent=i?`${c+1}/${d}`:"");let f=e.querySelector('[data-ask-stepper="true"]');f&&f.remove();let h=e.querySelector('[data-ask-question="true"]');if(h){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";h.textContent=A,h.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=kb(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(th(o,n))}let k=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!k?e.appendChild(Lb(o)):(!u||i)&&k&&k.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Pb(c,d,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();oh(e),nh(e)},Wb=(e,t,r)=>{let o=ni(t),n=Cb(o),a=e.toolCall.id,s=ys(r),i=Math.max(1,s.length),c=i>1,d=Ib(e,s),p=c?Hb(e,i):0,u=S("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Ha,a),u.setAttribute("data-tool-call-id",a),u.setAttribute("data-message-id",e.id),u.setAttribute(Nl,String(i)),u.setAttribute(Fl,String(p)),u.setAttribute(Ol,c?"true":"false"),u.setAttribute(Jg,n),rh(u,d),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Zg(u,o);let g=S("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),f=S("div","persona-ask-sheet-question persona-flex-1");f.setAttribute("data-ask-question","true"),f.textContent="",g.appendChild(f);let h=S("span","persona-ask-sheet-step-inline");h.setAttribute("data-ask-step-inline","true"),h.textContent="",g.appendChild(h),u.appendChild(g);let k=S("div",n==="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 k.setAttribute("data-ask-pill-list","true"),k.setAttribute("role","group"),u.appendChild(k),n!=="rows"&&u.appendChild(th(o,n)),_l(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Bb=(e,t,r)=>{let{payload:o}=Yo(t),n=Math.max(1,ys(o).length);n>Wa(e)&&(e.setAttribute(Nl,String(n)),n>1&&!Tn(e)&&e.setAttribute(Ol,"true")),_l(e,t,r)},ah=(e,t)=>{let r=S("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=ni(t);Zg(r,o);let n=S("span","persona-ask-stub-label"),{complete:a}=Yo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},Ba=(e,t,r)=>{if(!r||!Jo(e)||ni(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ha}]`).forEach(d=>{d.getAttribute(Ha)!==n&&d.remove()});let s=r.querySelector(`[${Ha}="${Yg(n)}"]`);if(s){Bb(s,e,t);return}let{payload:i}=Yo(e),c=Wb(e,t,i);r.appendChild(c)},En=(e,t)=>{if(!e)return;let r=t?`[${Ha}="${Yg(t)}"]`:`[${Ha}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Ul=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),kn=(e,t)=>{let r=na(e),o=ao(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,rh(e,r),oh(e),nh(e)},si=(e,t,r,o)=>{let n=Wa(e),a=Math.max(0,Math.min(n-1,o));Rb(e,a),_l(e,t,r)};var vo="suggest_replies";var ql={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},ii={name:vo,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:ql,origin:"sdk",annotations:{readOnlyHint:!0}},Vl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),bs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===vo},zl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},li=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!bs(o))continue;let n=zl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},sh=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var $l={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:hs,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},jl={name:xs,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:$l,origin:"sdk",annotations:{readOnlyHint:!0}},vs=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(jl),sh(e)&&t.push(ii),t};var Zo=La(oi(),1),di=e=>e.replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ln=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Db=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},ih=e=>e.status==="complete"?Db(e):e.status==="pending"?"Waiting":"",Fb=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var lh=e=>e.status==="complete"?Fb(e):"Using tool...",ci=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Cs=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ci(t)},pi=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ci(t)},Gl=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=Cs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ui=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&ws(o,r.slice(a,s.index),[]),s[1]!==void 0?ws(o,s[1],["bold"]):s[2]!==void 0?ws(o,s[2],["italic"]):s[3]!==void 0&&ws(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&ws(o,r.slice(a),[]),o},ws=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},Nb=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
11
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
12
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ss=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},mi=()=>{var t;let e=Nb();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},gi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?di(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=di(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},dh=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?di(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?di(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},hi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ch="4.6.0";var aa=ch;var _b="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Ub(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Kl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function qb(e){switch(e){case"json":return gi;case"regex-json":return mi;case"xml":return hi;default:return fi}}var ph=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Vb(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=ph(r);if(!ph(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=Ss(e);return Ss(t)!==null&&s===null?t:e}var sa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:_b,this.headers={"Content-Type":"application/json","X-Persona-Version":aa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:qb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ia(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=$g(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,d;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(d=r.agentId)!=null?d:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,u={sessionId:c.sessionId,messages:t.messages.filter(Kl).map(y=>{var w,v,M;return{id:y.id,role:y.role,content:(M=(v=(w=y.contentParts)!=null?w:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},g=d.clientTools,f=!!(g&&g.length>0),h=f?Vg(g):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,k=f&&b&&this.lastSentClientToolsFingerprint===h,E=!1,A=null,T;for(let y=0;;y++){let v={...u,...f&&(E||!k)&&g?{clientTools:g}:{},...h?{clientToolsFingerprint:h}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&f){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=h!=null?h:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o,n){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||xi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Kl).filter(d=>d.role==="user"||d.role==="assistant"||d.role==="system").filter(d=>!d.variant||d.variant==="assistant").sort((d,p)=>{let u=new Date(d.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(d=>{var p,u,g;return{role:d.role,content:(g=(u=(p=d.contentParts)!=null?p:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...vs(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,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&&(n.context=d)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(Kl).sort((c,d)=>{let p=new Date(c.createdAt).getTime(),u=new Date(d.createdAt).getTime();return p-u}).map(c=>{var d,p,u;return{role:c.role,content:(u=(p=(d=c.contentParts)!=null?d:c.llmContent)!=null?p:c.rawContent)!=null?u:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,d]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=d);let a=[...vs(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async d=>{try{let p=await d({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let d=c;return n.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=n.clientTools),d}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=u,n(u),u},d=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=d(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o,n){var xr,Co,So,Ve;let a=t.getReader(),s=new TextDecoder,i="",c=Date.now(),d=0,p=()=>c+d++,u=W=>{let ce=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,Se=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Ae=W.tools?W.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...W,reasoning:ce,toolCall:Se,tools:Ae}},g=W=>{if(W.role!=="assistant"||W.variant)return!0;let ce=Array.isArray(W.contentParts)&&W.contentParts.length>0,Se=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||ce||Se||!!W.stopReason},f=W=>{g(W)&&r({type:"message",message:u(W)})},h=null,b=null,k={current:null},E={current:null},A=null,T="",y=new Map,w=new Map,v=new Map,M=new Map,H=new Map,I={lastId:null,byStep:new Map},P={lastId:null,byCall:new Map},B=W=>{if(W==null)return null;try{return String(W)}catch{return null}},O=W=>{var ce,Se,Ae,Ie,et;return B((et=(Ie=(Ae=(Se=(ce=W.stepId)!=null?ce:W.step_id)!=null?Se:W.step)!=null?Ae:W.parentId)!=null?Ie:W.flowStepId)!=null?et:W.flow_step_id)},Q=W=>{var ce,Se,Ae,Ie,et,Qe,gt;return B((gt=(Qe=(et=(Ie=(Ae=(Se=(ce=W.callId)!=null?ce:W.call_id)!=null?Se:W.requestId)!=null?Ae:W.request_id)!=null?Ie:W.toolCallId)!=null?et:W.tool_call_id)!=null?Qe:W.stepId)!=null?gt:W.step_id)},me=o,ue=!1,Z=()=>{if(h)return h;let W,ce="",Se=A;return!ue&&me?(W=me,ue=!0,ce=n!=null?n:""):me&&Se?W=`${me}_${Se}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:W,role:"assistant",content:ce,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},f(h),h},Le=(W,ce)=>{I.lastId=ce,W&&I.byStep.set(W,ce)},We=(W,ce)=>{var et;let Se=(et=W.reasoningId)!=null?et:W.id,Ae=O(W);if(Se){let Qe=String(Se);return Le(Ae,Qe),Qe}if(Ae){let Qe=I.byStep.get(Ae);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!ce)return I.lastId;if(!ce)return null;let Ie=`reason-${p()}`;return Le(Ae,Ie),Ie},ie=W=>{let ce=M.get(W);if(ce)return ce;let Se={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:W,status:"streaming",chunks:[]}};return M.set(W,Se),f(Se),Se},Me=(W,ce)=>{P.lastId=ce,W&&P.byCall.set(W,ce)},oe=new Set,se=new Map,ge=new Set,Te=new Map,qe=W=>{if(!W)return!1;let ce=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return ce==="emit_artifact_markdown"||ce==="emit_artifact_component"},j=(W,ce)=>{var et;let Se=(et=W.toolId)!=null?et:W.id,Ae=Q(W);if(Se){let Qe=String(Se);return Me(Ae,Qe),Qe}if(Ae){let Qe=P.byCall.get(Ae);if(Qe)return P.lastId=Qe,Qe}if(P.lastId&&!ce)return P.lastId;if(!ce)return null;let Ie=`tool-${p()}`;return Me(Ae,Ie),Ie},ee=W=>{let ce=H.get(W);if(ce)return ce;let Se={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:W,status:"pending"}};return H.set(W,Se),f(Se),Se},Ee=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let ce=Number(W);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let Se=Date.parse(W);if(!Number.isNaN(Se))return Se}return Date.now()},te=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},le=new Map,ke=new Map,nt=new Map,yt=(W,ce,Se)=>{var gt;let Ae=nt.get(W);Ae||(Ae=[],nt.set(W,Ae));let Ie=0,et=Ae.length;for(;Ie<et;){let pe=Ie+et>>>1;Ae[pe].seq<ce?Ie=pe+1:et=pe}((gt=Ae[Ie])==null?void 0:gt.seq)===ce?Ae[Ie]={seq:ce,text:Se}:Ae.splice(Ie,0,{seq:ce,text:Se});let Qe="";for(let pe=0;pe<Ae.length;pe++)Qe+=Ae[pe].text;return Qe},Kt=(W,ce)=>{let Se=te(ce),Ae=ke.get(W.id),Ie=Vb(Ae,Se);W.rawContent=Ie;let et=le.get(W.id),Qe=ae=>{var Ke;let mt=(Ke=W.content)!=null?Ke:"";ae.trim()!==""&&(mt.trim().length===0||ae.startsWith(mt)||ae.trimStart().startsWith(mt.trim()))&&(W.content=ae)},gt=()=>{var ae;if(et){let mt=(ae=et.close)==null?void 0:ae.call(et);mt instanceof Promise&&mt.catch(()=>{})}le.delete(W.id),ke.delete(W.id),W.streaming=!1,f(W)};if(!et){Qe(Se),gt();return}let pe=Ss(Ie);if(pe!==null&&pe.trim()!==""){Qe(pe),gt();return}let N=ae=>{var Lt;let mt=typeof ae=="string"?ae:(Lt=ae==null?void 0:ae.text)!=null?Lt:null;if(mt!==null&&mt.trim()!=="")return mt;let Ke=et.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Se},ye;try{ye=et.processChunk(Ie)}catch{Qe(Se),gt();return}if(ye instanceof Promise){ye.then(ae=>{Qe(N(ae)),gt()}).catch(()=>{Qe(Se),gt()});return}Qe(N(ye)),gt()},jt=null,ct=(W,ce,Se,Ae)=>{var pe;W.rawContent=ce,le.has(W.id)||le.set(W.id,this.createStreamParser());let Ie=le.get(W.id),et=ce.trim().startsWith("{")||ce.trim().startsWith("[");if(et&&ke.set(W.id,ce),Ie.__isPlainTextParser===!0){W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W);return}let gt=Ie.processChunk(ce);if(gt instanceof Promise)gt.then(N=>{var ae;let ye=typeof N=="string"?N:(ae=N==null?void 0:N.text)!=null?ae:null;ye!==null&&ye.trim()!==""?(W.content=ye,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}).catch(()=>{W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W)});else{let N=typeof gt=="string"?gt:(pe=gt==null?void 0:gt.text)!=null?pe:null;N!==null&&N.trim()!==""?(W.content=N,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}},fe=(W,ce)=>{var pe,N;let Se=ce!=null?ce:W.content;if(Se==null||Se===""){W.streaming=!1,f(W);return}let Ae=ke.get(W.id),Ie=Ae!=null?Ae:te(Se);W.rawContent=Ie;let et=le.get(W.id),Qe=null,gt=!1;if(et&&(Qe=et.getExtractedText(),Qe===null&&(Qe=Ss(Ie)),Qe===null)){let ye=et.processChunk(Ie);ye instanceof Promise?(gt=!0,ye.then(ae=>{var Ke;let mt=typeof ae=="string"?ae:(Ke=ae==null?void 0:ae.text)!=null?Ke:null;mt!==null&&(W.content=mt,W.streaming=!1,le.delete(W.id),ke.delete(W.id),f(W))}).catch(()=>{})):Qe=typeof ye=="string"?ye:(pe=ye==null?void 0:ye.text)!=null?pe:null}if(!gt){Qe!==null&&Qe.trim()!==""?W.content=Qe:ke.has(W.id)||(W.content=te(Se));let ye=le.get(W.id);if(ye){let ae=(N=ye.close)==null?void 0:N.call(ye);ae instanceof Promise&&ae.catch(()=>{}),le.delete(W.id)}ke.delete(W.id),W.streaming=!1,f(W)}},X=(W,ce,Se)=>{let Ae=w.get(W);if(Ae)return Ae;let Ie={id:`nested-${ce}-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:W,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ce}};return w.set(W,Ie),f(Ie),Ie},st=[],je,Ce=new Map,ve=0,Ye="agent",Vt=!1,xe=null,de=null,Cr=new Map,Ct=(xr=this.config.iterationDisplay)!=null?xr:"separate";for(je=()=>{var W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn,we,$o,Zr,Nt,eo,jo,Ya,ya,Za,Vn,Lo,un,it,ar,sr,Po,es,Go,zn,Ro,U,ba,fo,Io,Ko,Ho,mo,va,$s,yr,Ar,go,Mr,$n,ho,br,Wo,wa,jn,Ca,fn;for(let mn=0;mn<st.length;mn++){let rt=st[mn].payloadType,L=st[mn].payload;if(!Vt&&Ye!=="flow"&&typeof L.stepType=="string"&&(Ye="flow"),rt==="reasoning_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z),X($,z,"reasoning");continue}let K=(W=We(L,!0))!=null?W:`reason-${p()}`,G=ie(K);G.reasoning=(ce=G.reasoning)!=null?ce:{id:K,status:"streaming",chunks:[]},G.reasoning.startedAt=(Ae=G.reasoning.startedAt)!=null?Ae:Ee((Se=L.startedAt)!=null?Se:L.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(rt==="reasoning_delta"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let De=w.get($),tt=(Qe=(et=(Ie=L.reasoningText)!=null?Ie:L.text)!=null?et:L.delta)!=null?Qe:"";tt&&L.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(tt)),f(De));continue}let z=(pe=(gt=We(L,!1))!=null?gt:We(L,!0))!=null?pe:`reason-${p()}`,K=ie(z);K.reasoning=(N=K.reasoning)!=null?N:{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=(ae=K.reasoning.startedAt)!=null?ae:Ee((ye=L.startedAt)!=null?ye:L.timestamp);let G=(Lt=(Ke=(mt=L.reasoningText)!=null?mt:L.text)!=null?Ke:L.delta)!=null?Lt:"";if(G&&L.hidden!==!0){let De=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(De!==void 0){let tt=yt(z,De,String(G));K.reasoning.chunks=[tt]}else K.reasoning.chunks.push(String(G))}if(K.reasoning.status=L.done?"complete":"streaming",L.done){K.reasoning.completedAt=Ee((Et=L.completedAt)!=null?Et:L.timestamp);let De=(bt=K.reasoning.startedAt)!=null?bt:Date.now();K.reasoning.durationMs=Math.max(0,((It=K.reasoning.completedAt)!=null?It:Date.now())-De)}K.streaming=K.reasoning.status!=="complete",f(K)}else if(rt==="reasoning_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let tt=w.get($);if(tt.reasoning){let lt=typeof L.text=="string"?L.text:"";lt&&tt.reasoning.chunks.length===0&&tt.reasoning.chunks.push(lt),tt.reasoning.status="complete",tt.streaming=!1,f(tt)}y.delete($),w.delete($);continue}let z=(Ft=(Qt=We(L,!1))!=null?Qt:We(L,!0))!=null?Ft:`reason-${p()}`,K=typeof L.text=="string"?L.text:"";!M.get(z)&&(K||L.scope==="loop")&&ie(z);let G=M.get(z);if(G!=null&&G.reasoning){(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),K&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(K),G.reasoning.status="complete",G.reasoning.completedAt=Ee((tr=L.completedAt)!=null?tr:L.timestamp);let tt=(Ao=G.reasoning.startedAt)!=null?Ao:Date.now();G.reasoning.durationMs=Math.max(0,((Uo=G.reasoning.completedAt)!=null?Uo:Date.now())-tt),G.streaming=!1,f(G)}let De=O(L);De&&I.byStep.delete(De)}else if(rt==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof L.iteration=="number"&&(ve=L.iteration);let $=(lo=(io=typeof L.toolCallId=="string"?L.toolCallId:void 0)!=null?io:j(L,!0))!=null?lo:`tool-${p()}`,z=(on=L.toolName)!=null?on:L.name;if(qe(z)){oe.add($);continue}Me(Q(L),$);let K=ee($),G=(zt=K.toolCall)!=null?zt:{id:$,status:"pending"};G.name=z!=null?z:G.name,G.status="running",L.parameters!==void 0?G.args=L.parameters:L.args!==void 0&&(G.args=L.args),G.startedAt=(qo=G.startedAt)!=null?qo:Ee((co=L.startedAt)!=null?co:L.timestamp),G.completedAt=void 0,G.durationMs=void 0,K.toolCall=G,K.streaming=!0,L.executionId&&(K.agentMetadata={executionId:L.executionId,iteration:L.iteration}),f(K)}else if(rt==="tool_output_delta"){let $=(Rr=(Fr=j(L,!1))!=null?Fr:j(L,!0))!=null?Rr:`tool-${p()}`;if(oe.has($))continue;let z=ee($),K=(Nr=z.toolCall)!=null?Nr:{id:$,status:"running"};K.startedAt=(Mo=K.startedAt)!=null?Mo:Ee((po=L.startedAt)!=null?po:L.timestamp);let G=(an=(Qr=(nn=L.text)!=null?nn:L.delta)!=null?Qr:L.message)!=null?an:"";G&&(K.chunks=(St=K.chunks)!=null?St:[],K.chunks.push(String(G))),K.status="running",z.toolCall=K,z.streaming=!0;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(Vo=z.agentMetadata)!=null?Vo:{executionId:(To=De==null?void 0:De.executionId)!=null?To:L.executionId,iteration:(Eo=De==null?void 0:De.iteration)!=null?Eo:L.iteration}),f(z)}else if(rt==="tool_complete"){let $=(ht=(uo=j(L,!1))!=null?uo:j(L,!0))!=null?ht:`tool-${p()}`;if(oe.has($)){oe.delete($);continue}let z=ee($),K=(On=z.toolCall)!=null?On:{id:$,status:"running"};K.status="complete",L.result!==void 0&&(K.result=L.result),typeof L.duration=="number"&&(K.duration=L.duration),K.completedAt=Ee((ko=L.completedAt)!=null?ko:L.timestamp);let G=(_n=L.duration)!=null?_n:L.executionTime;if(typeof G=="number")K.durationMs=G;else{let lt=(Ir=K.startedAt)!=null?Ir:Date.now();K.durationMs=Math.max(0,((xa=K.completedAt)!=null?xa:Date.now())-lt)}z.toolCall=K,z.streaming=!1;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(ln=z.agentMetadata)!=null?ln:{executionId:(sn=De==null?void 0:De.executionId)!=null?sn:L.executionId,iteration:(zo=De==null?void 0:De.iteration)!=null?zo:L.iteration}),f(z);let tt=Q(L);tt&&P.byCall.delete(tt)}else if(rt==="await"&&L.toolName){let $=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,z=(dn=$!=null?$:L.toolId)!=null?dn:`local-${p()}`,K=ee(z),G=L.toolName,De=L.origin==="webmcp"&&!An(G)?`webmcp:${G}`:G,tt=An(De),lt=(Un=K.toolCall)!=null?Un:{id:z,status:"pending"};lt.name=De,lt.args=L.parameters,lt.status=tt?"running":"complete",lt.chunks=(qn=lt.chunks)!=null?qn:[],lt.startedAt=(Or=lt.startedAt)!=null?Or:Ee((vt=(cn=L.startedAt)!=null?cn:L.timestamp)!=null?vt:L.awaitedAt),tt?(lt.completedAt=void 0,lt.duration=void 0,lt.durationMs=void 0):lt.completedAt=(_r=lt.completedAt)!=null?_r:lt.startedAt,K.toolCall=lt,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(At=L.executionId)!=null?At:(Sr=K.agentMetadata)==null?void 0:Sr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(K)}else if(rt==="text_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z);continue}let K=h;K&&(Ye==="flow"?(fe(K),jt=K):(K.streaming=!1,f(K)),h=null),A=typeof L.id=="string"?L.id:A,T=""}else if(rt==="text_delta"){let $=typeof L.id=="string"?L.id:null,z=$?y.get($):void 0;if($&&z){let G=typeof L.delta=="string"?L.delta:"",De=((Jr=v.get($))!=null?Jr:"")+G;if(v.set($,De),De.trim()==="")continue;let tt=X($,z);tt.agentMetadata={...tt.agentMetadata,executionId:L.executionId,parentToolId:z},ct(tt,De,G,void 0);continue}if(A=typeof L.id=="string"?L.id:A,Ye==="flow"){let G=typeof L.delta=="string"?L.delta:"";if(T+=G,T.trim()==="")continue;let De=Z();De.agentMetadata={executionId:L.executionId,iteration:L.iteration},ct(De,T,G,void 0),b=De;continue}let K=Z();K.content+=(Yr=L.delta)!=null?Yr:"",K.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:xe!=null?xe:void 0,agentName:de==null?void 0:de.agentName},b=K,f(K)}else if(rt==="text_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)){let K=w.get($);K&&fe(K),y.delete($),v.delete($),w.delete($);continue}let z=h;z&&(Ye==="flow"?(fe(z),jt=z):(((Ur=z.content)!=null?Ur:"")===""&&typeof L.text=="string"&&(z.content=L.text),z.streaming=!1,f(z)),h=null),A=null,T=""}else if(rt==="step_complete"){let $=L.stepType,z=L.executionType;if($==="tool"||z==="context")continue;if(L.success===!1){let K=L.error,G=typeof K=="string"&&K!==""?K:K!=null&&typeof K=="object"&&"message"in K?String((pn=K.message)!=null?pn:"Step failed"):"Step failed";r({type:"error",error:new Error(G)});let De=h;De&&De.streaming&&(De.streaming=!1,f(De)),r({type:"status",status:"idle"});continue}{let K=jt;jt=null;let G=L.stopReason,De=(we=L.result)==null?void 0:we.response;if(K)G&&(K.stopReason=G),De!=null?Kt(K,De):K.streaming!==!1&&(le.delete(K.id),ke.delete(K.id),K.streaming=!1,f(K));else{let tt=De!=null&&De!=="";if(tt||G){let lt=Z();G&&(lt.stopReason=G),tt?fe(lt,De):(lt.streaming=!1,f(lt))}}continue}}else if(rt==="execution_start")Ye=L.kind==="flow"?"flow":"agent",Vt=!0,Ye==="agent"&&(de={executionId:L.executionId,agentId:($o=L.agentId)!=null?$o:"virtual",agentName:(Zr=L.agentName)!=null?Zr:"",status:"running",currentIteration:0,maxTurns:(Nt=L.maxTurns)!=null?Nt:1,startedAt:Ee(L.startedAt)});else if(rt==="turn_start"){let $=typeof L.iteration=="number"?L.iteration:ve;if($!==ve){if(de&&(de.currentIteration=$),Ct==="separate"&&$>1){let z=h;z&&(z.streaming=!1,f(z),Cr.set($-1,z),h=null)}ve=$}xe=typeof L.id=="string"?L.id:null,b=null}else if(rt==="tool_input_delta"){let $=(eo=L.toolCallId)!=null?eo:P.lastId;if($){let z=H.get($);z!=null&&z.toolCall&&(z.toolCall.chunks=(jo=z.toolCall.chunks)!=null?jo:[],z.toolCall.chunks.push((Ya=L.delta)!=null?Ya:""),f(z))}}else{if(rt==="tool_input_complete")continue;if(rt==="turn_complete"){let $=L.stopReason,z=h!=null?h:b;if($&&z!==null){let K=L.id;(!K||((ya=z.agentMetadata)==null?void 0:ya.turnId)===K)&&(z.stopReason=$,f(z))}xe===L.id&&(xe=null)}else if(rt==="media_start"){let $=String(L.id);Ce.set($,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,role:typeof L.role=="string"?L.role:void 0,toolCallId:L.toolCallId,parts:[]})}else if(rt==="media_delta"){let $=Ce.get(String(L.id));$&&typeof L.delta=="string"&&$.parts.push(L.delta)}else if(rt==="media_complete"){let $=String(L.id),z=Ce.get($);Ce.delete($);let K=(Vn=(Za=typeof L.mediaType=="string"?L.mediaType:void 0)!=null?Za:z==null?void 0:z.mediaType)!=null?Vn:"application/octet-stream",G=typeof L.data=="string"?L.data:void 0,De=typeof L.url=="string"?L.url:z&&z.parts.length>0?z.parts.join(""):void 0,tt=null;if(G)tt={type:"media",data:G,mediaType:K};else if(De){let Hr=K.toLowerCase();tt={type:Hr==="image"||Hr.startsWith("image/")?"image-url":"file-url",url:De,mediaType:K}}let lt=(Lo=L.toolCallId)!=null?Lo:z==null?void 0:z.toolCallId,bl=tt?[tt]:[],gn=[];for(let Hr of bl){if(!Hr||typeof Hr!="object")continue;let Jt=Hr,hn=typeof Jt.type=="string"?Jt.type:void 0,to=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tr=null,Wr="";if(hn==="media"){let Er=typeof Jt.data=="string"?Jt.data:void 0;if(!Er)continue;Wr=to.length>0?to:"application/octet-stream",Tr=`data:${Wr};base64,${Er}`}else if(hn==="image-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else if(hn==="file-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else continue;if(Tr)if(hn==="image-url"||Wr.startsWith("image/"))gn.push({type:"image",image:Tr,...Wr.includes("/")?{mimeType:Wr}:{}});else if(Wr.startsWith("audio/"))gn.push({type:"audio",audio:Tr,mimeType:Wr});else if(Wr.startsWith("video/"))gn.push({type:"video",video:Tr,mimeType:Wr});else{let Er=Wr||"application/octet-stream";gn.push({type:"file",data:Tr,mimeType:Er,filename:Ub(Er)})}}if(gn.length>0){let Hr=p(),Jt=lt,to={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${Hr}`:String(Hr)}`,role:"assistant",content:"",contentParts:gn,createdAt:new Date().toISOString(),streaming:!1,sequence:Hr,agentMetadata:{executionId:L.executionId,iteration:typeof L.iteration=="number"?L.iteration:ve}};f(to);let Tr=h;Tr&&(Tr.streaming=!1,f(Tr)),h=null,k.current=null}}else if(rt==="execution_complete"){let $=(un=L.kind)!=null?un:Ye;$==="agent"&&de&&(de.status=L.success?"complete":"error",de.completedAt=Ee(L.completedAt),de.stopReason=L.stopReason);let z=h;z&&($==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,f(z)),h=null),A=null,T="",jt=null,r({type:"status",status:"idle",terminal:!0})}else if(rt==="execution_error"){let $=typeof L.error=="string"?L.error:(ar=(it=L.error)==null?void 0:it.message)!=null?ar:"Execution error";r({type:"error",error:new Error($)})}else if(rt!=="ping"){if(rt==="approval_start"){let $=(sr=L.approvalId)!=null?sr:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(Po=de==null?void 0:de.agentId)!=null?Po:"virtual",executionId:(Go=(es=L.executionId)!=null?es:de==null?void 0:de.executionId)!=null?Go:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(U=L.description)!=null?U:`Execute ${(Ro=L.toolName)!=null?Ro:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="step_await"&&L.awaitReason==="approval_required"){let $=(ba=L.approvalId)!=null?ba:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(fo=de==null?void 0:de.agentId)!=null?fo:"virtual",executionId:(Ko=(Io=L.executionId)!=null?Io:de==null?void 0:de.executionId)!=null?Ko:"",toolName:(Ho=L.toolName)!=null?Ho:"",toolType:L.toolType,description:(va=L.description)!=null?va:`Execute ${(mo=L.toolName)!=null?mo:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="approval_complete"){let $=L.approvalId;if($){let K={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:($s=L.decision)!=null?$s:"approved",agentId:(yr=de==null?void 0:de.agentId)!=null?yr:"virtual",executionId:(go=(Ar=L.executionId)!=null?Ar:de==null?void 0:de.executionId)!=null?go:"",toolName:(Mr=L.toolName)!=null?Mr:"",description:($n=L.description)!=null?$n:"",resolvedAt:Date.now()}};f(K)}}else if(rt==="artifact_start"||rt==="artifact_delta"||rt==="artifact_update"||rt==="artifact_complete"){if(rt==="artifact_start"){let $=L.artifactType,z=String(L.id),K=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:z,artifactType:$,title:K,component:typeof L.component=="string"?L.component:void 0}),Te.set(z,{markdown:"",title:K}),!ge.has(z)){ge.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:K,artifactType:$,status:"streaming"}})};se.set(z,G),f(G)}}else if(rt==="artifact_delta"){let $=String(L.id),z=typeof L.delta=="string"?L.delta:String((ho=L.delta)!=null?ho:"");r({type:"artifact_delta",id:$,artDelta:z});let K=Te.get($);K&&(K.markdown+=z)}else if(rt==="artifact_update"){let $=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:$,component:typeof L.component=="string"?L.component:void 0})}else if(rt==="artifact_complete"){let $=String(L.id);r({type:"artifact_complete",id:$});let z=se.get($);if(z){z.streaming=!1;try{let K=JSON.parse((br=z.rawContent)!=null?br:"{}");if(K.props){K.props.status="complete";let G=Te.get($);G!=null&&G.markdown&&(K.props.markdown=G.markdown)}z.rawContent=JSON.stringify(K)}catch{}Te.delete($),f(z),se.delete($)}}}else if(rt==="transcript_insert"){let $=L.message;if(!$||typeof $!="object")continue;let z=String((Wo=$.id)!=null?Wo:`msg-${p()}`),K=$.role,De={id:z,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:p()};if(f(De),De.rawContent)try{let tt=JSON.parse(De.rawContent),lt=(wa=tt==null?void 0:tt.props)==null?void 0:wa.artifactId;typeof lt=="string"&&ge.add(lt)}catch{}h=null,k.current=null,le.delete(z),ke.delete(z)}else if(rt==="error"){if(L.recoverable===!1&&L.error!=null&&L.error!==""){let $=typeof L.error=="string"?L.error:((jn=L.error)==null?void 0:jn.message)!=null?String(L.error.message):"Execution error";r({type:"error",error:new Error($)});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}else if(rt==="step_error"||rt==="dispatch_error"||rt==="flow_error"){let $=null;if(L.error instanceof Error)$=L.error;else if(rt==="dispatch_error"){let z=(Ca=L.message)!=null?Ca:L.error;z!=null&&z!==""&&($=new Error(String(z)))}else{let z=L.error;typeof z=="string"&&z!==""?$=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&($=new Error(String((fn=z.message)!=null?fn:z)))}if($){r({type:"error",error:$});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}}}}st.length=0};;){let{done:W,value:ce}=await a.read();if(W)break;i+=s.decode(ce,{stream:!0});let Se=i.split(`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},Ss=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},fi=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},mi=()=>{var t;let e=Nb();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},gi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?di(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=di(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},dh=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?di(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?di(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},hi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ch="4.6.1";var aa=ch;var _b="https://api.runtype.com/v1/dispatch",xi="https://api.runtype.com";function Ub(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Kl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function qb(e){switch(e){case"json":return gi;case"regex-json":return mi;case"xml":return hi;default:return fi}}var ph=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Vb(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=ph(r);if(!ph(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=Ss(e);return Ss(t)!==null&&s===null?t:e}var sa=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:_b,this.headers={"Content-Type":"application/json","X-Persona-Version":aa,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:qb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ia(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=$g(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;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 o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,d;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(d=r.agentId)!=null?d:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let d=await this.buildPayload(t.messages),p=d.metadata?Object.fromEntries(Object.entries(d.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,u={sessionId:c.sessionId,messages:t.messages.filter(Kl).map(y=>{var w,v,M;return{id:y.id,role:y.role,content:(M=(v=(w=y.contentParts)!=null?w:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...d.inputs&&Object.keys(d.inputs).length>0&&{inputs:d.inputs},...d.context&&{context:d.context}},g=d.clientTools,f=!!(g&&g.length>0),h=f?Vg(g):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,k=f&&b&&this.lastSentClientToolsFingerprint===h,E=!1,A=null,T;for(let y=0;;y++){let v={...u,...f&&(E||!k)&&g?{clientTools:g}:{},...h?{clientToolsFingerprint:h}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":aa},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&f){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let w=new Error(y.error||"Failed to send message");throw r({type:"error",error:w}),w}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=h!=null?h:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let d=c instanceof Error?c:new Error(String(c));throw!d.message.includes("Session expired")&&!d.message.includes("Message limit")&&r({type:"error",error:d}),d}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o,n){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o,n)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||xi}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var d,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((d=this.config.apiUrl)==null?void 0:d.replace(/\/+$/,""))||xi}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(Kl).filter(d=>d.role==="user"||d.role==="assistant"||d.role==="system").filter(d=>!d.variant||d.variant==="assistant").sort((d,p)=>{let u=new Date(d.createdAt).getTime(),g=new Date(p.createdAt).getTime();return u-g}).map(d=>{var p,u,g;return{role:d.role,content:(g=(u=(p=d.contentParts)!=null?p:d.llmContent)!=null?u:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...vs(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,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&&(n.context=d)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(Kl).sort((c,d)=>{let p=new Date(c.createdAt).getTime(),u=new Date(d.createdAt).getTime();return p-u}).map(c=>{var d,p,u;return{role:c.role,content:(u=(p=(d=c.contentParts)!=null?d:c.llmContent)!=null?p:c.rawContent)!=null?u:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,d]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=d);let a=[...vs(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async d=>{try{let p=await d({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let d=c;return n.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=n.clientTools),d}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=u,n(u),u},d=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=d(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o,n){var xr,Co,So,Ve;let a=t.getReader(),s=new TextDecoder,i="",c=Date.now(),d=0,p=()=>c+d++,u=W=>{let ce=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,Se=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Ae=W.tools?W.tools.map(Ie=>({...Ie,chunks:Ie.chunks?[...Ie.chunks]:void 0})):void 0;return{...W,reasoning:ce,toolCall:Se,tools:Ae}},g=W=>{if(W.role!=="assistant"||W.variant)return!0;let ce=Array.isArray(W.contentParts)&&W.contentParts.length>0,Se=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||ce||Se||!!W.stopReason},f=W=>{g(W)&&r({type:"message",message:u(W)})},h=null,b=null,k={current:null},E={current:null},A=null,T="",y=new Map,w=new Map,v=new Map,M=new Map,H=new Map,I={lastId:null,byStep:new Map},P={lastId:null,byCall:new Map},B=W=>{if(W==null)return null;try{return String(W)}catch{return null}},O=W=>{var ce,Se,Ae,Ie,et;return B((et=(Ie=(Ae=(Se=(ce=W.stepId)!=null?ce:W.step_id)!=null?Se:W.step)!=null?Ae:W.parentId)!=null?Ie:W.flowStepId)!=null?et:W.flow_step_id)},Q=W=>{var ce,Se,Ae,Ie,et,Qe,gt;return B((gt=(Qe=(et=(Ie=(Ae=(Se=(ce=W.callId)!=null?ce:W.call_id)!=null?Se:W.requestId)!=null?Ae:W.request_id)!=null?Ie:W.toolCallId)!=null?et:W.tool_call_id)!=null?Qe:W.stepId)!=null?gt:W.step_id)},me=o,ue=!1,Z=()=>{if(h)return h;let W,ce="",Se=A;return!ue&&me?(W=me,ue=!0,ce=n!=null?n:""):me&&Se?W=`${me}_${Se}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,h={id:W,role:"assistant",content:ce,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},f(h),h},Le=(W,ce)=>{I.lastId=ce,W&&I.byStep.set(W,ce)},We=(W,ce)=>{var et;let Se=(et=W.reasoningId)!=null?et:W.id,Ae=O(W);if(Se){let Qe=String(Se);return Le(Ae,Qe),Qe}if(Ae){let Qe=I.byStep.get(Ae);if(Qe)return I.lastId=Qe,Qe}if(I.lastId&&!ce)return I.lastId;if(!ce)return null;let Ie=`reason-${p()}`;return Le(Ae,Ie),Ie},ie=W=>{let ce=M.get(W);if(ce)return ce;let Se={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:W,status:"streaming",chunks:[]}};return M.set(W,Se),f(Se),Se},Me=(W,ce)=>{P.lastId=ce,W&&P.byCall.set(W,ce)},oe=new Set,se=new Map,ge=new Set,Te=new Map,qe=W=>{if(!W)return!1;let ce=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return ce==="emit_artifact_markdown"||ce==="emit_artifact_component"},j=(W,ce)=>{var et;let Se=(et=W.toolId)!=null?et:W.id,Ae=Q(W);if(Se){let Qe=String(Se);return Me(Ae,Qe),Qe}if(Ae){let Qe=P.byCall.get(Ae);if(Qe)return P.lastId=Qe,Qe}if(P.lastId&&!ce)return P.lastId;if(!ce)return null;let Ie=`tool-${p()}`;return Me(Ae,Ie),Ie},ee=W=>{let ce=H.get(W);if(ce)return ce;let Se={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:W,status:"pending"}};return H.set(W,Se),f(Se),Se},Ee=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let ce=Number(W);if(!Number.isNaN(ce)&&Number.isFinite(ce))return ce;let Se=Date.parse(W);if(!Number.isNaN(Se))return Se}return Date.now()},te=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},le=new Map,ke=new Map,nt=new Map,yt=(W,ce,Se)=>{var gt;let Ae=nt.get(W);Ae||(Ae=[],nt.set(W,Ae));let Ie=0,et=Ae.length;for(;Ie<et;){let pe=Ie+et>>>1;Ae[pe].seq<ce?Ie=pe+1:et=pe}((gt=Ae[Ie])==null?void 0:gt.seq)===ce?Ae[Ie]={seq:ce,text:Se}:Ae.splice(Ie,0,{seq:ce,text:Se});let Qe="";for(let pe=0;pe<Ae.length;pe++)Qe+=Ae[pe].text;return Qe},Kt=(W,ce)=>{let Se=te(ce),Ae=ke.get(W.id),Ie=Vb(Ae,Se);W.rawContent=Ie;let et=le.get(W.id),Qe=ae=>{var Ke;let mt=(Ke=W.content)!=null?Ke:"";ae.trim()!==""&&(mt.trim().length===0||ae.startsWith(mt)||ae.trimStart().startsWith(mt.trim()))&&(W.content=ae)},gt=()=>{var ae;if(et){let mt=(ae=et.close)==null?void 0:ae.call(et);mt instanceof Promise&&mt.catch(()=>{})}le.delete(W.id),ke.delete(W.id),W.streaming=!1,f(W)};if(!et){Qe(Se),gt();return}let pe=Ss(Ie);if(pe!==null&&pe.trim()!==""){Qe(pe),gt();return}let N=ae=>{var Lt;let mt=typeof ae=="string"?ae:(Lt=ae==null?void 0:ae.text)!=null?Lt:null;if(mt!==null&&mt.trim()!=="")return mt;let Ke=et.getExtractedText();return Ke!==null&&Ke.trim()!==""?Ke:Se},ye;try{ye=et.processChunk(Ie)}catch{Qe(Se),gt();return}if(ye instanceof Promise){ye.then(ae=>{Qe(N(ae)),gt()}).catch(()=>{Qe(Se),gt()});return}Qe(N(ye)),gt()},jt=null,ct=(W,ce,Se,Ae)=>{var pe;W.rawContent=ce,le.has(W.id)||le.set(W.id,this.createStreamParser());let Ie=le.get(W.id),et=ce.trim().startsWith("{")||ce.trim().startsWith("[");if(et&&ke.set(W.id,ce),Ie.__isPlainTextParser===!0){W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W);return}let gt=Ie.processChunk(ce);if(gt instanceof Promise)gt.then(N=>{var ae;let ye=typeof N=="string"?N:(ae=N==null?void 0:N.text)!=null?ae:null;ye!==null&&ye.trim()!==""?(W.content=ye,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}).catch(()=>{W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W)});else{let N=typeof gt=="string"?gt:(pe=gt==null?void 0:gt.text)!=null?pe:null;N!==null&&N.trim()!==""?(W.content=N,f(W)):!et&&!ce.trim().startsWith("<")&&(W.content=Ae!==void 0?ce:W.content+Se,ke.delete(W.id),le.delete(W.id),W.rawContent=void 0,f(W))}},fe=(W,ce)=>{var pe,N;let Se=ce!=null?ce:W.content;if(Se==null||Se===""){W.streaming=!1,f(W);return}let Ae=ke.get(W.id),Ie=Ae!=null?Ae:te(Se);W.rawContent=Ie;let et=le.get(W.id),Qe=null,gt=!1;if(et&&(Qe=et.getExtractedText(),Qe===null&&(Qe=Ss(Ie)),Qe===null)){let ye=et.processChunk(Ie);ye instanceof Promise?(gt=!0,ye.then(ae=>{var Ke;let mt=typeof ae=="string"?ae:(Ke=ae==null?void 0:ae.text)!=null?Ke:null;mt!==null&&(W.content=mt,W.streaming=!1,le.delete(W.id),ke.delete(W.id),f(W))}).catch(()=>{})):Qe=typeof ye=="string"?ye:(pe=ye==null?void 0:ye.text)!=null?pe:null}if(!gt){Qe!==null&&Qe.trim()!==""?W.content=Qe:ke.has(W.id)||(W.content=te(Se));let ye=le.get(W.id);if(ye){let ae=(N=ye.close)==null?void 0:N.call(ye);ae instanceof Promise&&ae.catch(()=>{}),le.delete(W.id)}ke.delete(W.id),W.streaming=!1,f(W)}},X=(W,ce,Se)=>{let Ae=w.get(W);if(Ae)return Ae;let Ie={id:`nested-${ce}-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Se?{variant:Se}:{},...Se==="reasoning"?{reasoning:{id:W,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ce}};return w.set(W,Ie),f(Ie),Ie},st=[],je,Ce=new Map,ve=0,Ye="agent",Vt=!1,xe=null,de=null,Cr=new Map,Ct=(xr=this.config.iterationDisplay)!=null?xr:"separate";for(je=()=>{var W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn,we,$o,Zr,Nt,eo,jo,Ya,ya,Za,Vn,Lo,un,it,ar,sr,Po,es,Go,zn,Ro,U,ba,fo,Io,Ko,Ho,mo,va,$s,yr,Ar,go,Mr,$n,ho,br,Wo,wa,jn,Ca,fn;for(let mn=0;mn<st.length;mn++){let rt=st[mn].payloadType,L=st[mn].payload;if(!Vt&&Ye!=="flow"&&typeof L.stepType=="string"&&(Ye="flow"),rt==="reasoning_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z),X($,z,"reasoning");continue}let K=(W=We(L,!0))!=null?W:`reason-${p()}`,G=ie(K);G.reasoning=(ce=G.reasoning)!=null?ce:{id:K,status:"streaming",chunks:[]},G.reasoning.startedAt=(Ae=G.reasoning.startedAt)!=null?Ae:Ee((Se=L.startedAt)!=null?Se:L.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),G.streaming=!0,G.reasoning.status="streaming",f(G)}else if(rt==="reasoning_delta"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let De=w.get($),tt=(Qe=(et=(Ie=L.reasoningText)!=null?Ie:L.text)!=null?et:L.delta)!=null?Qe:"";tt&&L.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(tt)),f(De));continue}let z=(pe=(gt=We(L,!1))!=null?gt:We(L,!0))!=null?pe:`reason-${p()}`,K=ie(z);K.reasoning=(N=K.reasoning)!=null?N:{id:z,status:"streaming",chunks:[]},K.reasoning.startedAt=(ae=K.reasoning.startedAt)!=null?ae:Ee((ye=L.startedAt)!=null?ye:L.timestamp);let G=(Lt=(Ke=(mt=L.reasoningText)!=null?mt:L.text)!=null?Ke:L.delta)!=null?Lt:"";if(G&&L.hidden!==!0){let De=typeof L.sequenceIndex=="number"?L.sequenceIndex:void 0;if(De!==void 0){let tt=yt(z,De,String(G));K.reasoning.chunks=[tt]}else K.reasoning.chunks.push(String(G))}if(K.reasoning.status=L.done?"complete":"streaming",L.done){K.reasoning.completedAt=Ee((Et=L.completedAt)!=null?Et:L.timestamp);let De=(bt=K.reasoning.startedAt)!=null?bt:Date.now();K.reasoning.durationMs=Math.max(0,((It=K.reasoning.completedAt)!=null?It:Date.now())-De)}K.streaming=K.reasoning.status!=="complete",f(K)}else if(rt==="reasoning_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)&&w.has($)){let tt=w.get($);if(tt.reasoning){let lt=typeof L.text=="string"?L.text:"";lt&&tt.reasoning.chunks.length===0&&tt.reasoning.chunks.push(lt),tt.reasoning.status="complete",tt.streaming=!1,f(tt)}y.delete($),w.delete($);continue}let z=(Ft=(Qt=We(L,!1))!=null?Qt:We(L,!0))!=null?Ft:`reason-${p()}`,K=typeof L.text=="string"?L.text:"";!M.get(z)&&(K||L.scope==="loop")&&ie(z);let G=M.get(z);if(G!=null&&G.reasoning){(L.scope==="loop"||L.scope==="turn")&&(G.reasoning.scope=L.scope),K&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(K),G.reasoning.status="complete",G.reasoning.completedAt=Ee((tr=L.completedAt)!=null?tr:L.timestamp);let tt=(Ao=G.reasoning.startedAt)!=null?Ao:Date.now();G.reasoning.durationMs=Math.max(0,((Uo=G.reasoning.completedAt)!=null?Uo:Date.now())-tt),G.streaming=!1,f(G)}let De=O(L);De&&I.byStep.delete(De)}else if(rt==="tool_start"){h&&(h.streaming=!1,f(h),h=null),typeof L.iteration=="number"&&(ve=L.iteration);let $=(lo=(io=typeof L.toolCallId=="string"?L.toolCallId:void 0)!=null?io:j(L,!0))!=null?lo:`tool-${p()}`,z=(on=L.toolName)!=null?on:L.name;if(qe(z)){oe.add($);continue}Me(Q(L),$);let K=ee($),G=(zt=K.toolCall)!=null?zt:{id:$,status:"pending"};G.name=z!=null?z:G.name,G.status="running",L.parameters!==void 0?G.args=L.parameters:L.args!==void 0&&(G.args=L.args),G.startedAt=(qo=G.startedAt)!=null?qo:Ee((co=L.startedAt)!=null?co:L.timestamp),G.completedAt=void 0,G.durationMs=void 0,K.toolCall=G,K.streaming=!0,L.executionId&&(K.agentMetadata={executionId:L.executionId,iteration:L.iteration}),f(K)}else if(rt==="tool_output_delta"){let $=(Rr=(Fr=j(L,!1))!=null?Fr:j(L,!0))!=null?Rr:`tool-${p()}`;if(oe.has($))continue;let z=ee($),K=(Nr=z.toolCall)!=null?Nr:{id:$,status:"running"};K.startedAt=(Mo=K.startedAt)!=null?Mo:Ee((po=L.startedAt)!=null?po:L.timestamp);let G=(an=(Qr=(nn=L.text)!=null?nn:L.delta)!=null?Qr:L.message)!=null?an:"";G&&(K.chunks=(St=K.chunks)!=null?St:[],K.chunks.push(String(G))),K.status="running",z.toolCall=K,z.streaming=!0;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(Vo=z.agentMetadata)!=null?Vo:{executionId:(To=De==null?void 0:De.executionId)!=null?To:L.executionId,iteration:(Eo=De==null?void 0:De.iteration)!=null?Eo:L.iteration}),f(z)}else if(rt==="tool_complete"){let $=(ht=(uo=j(L,!1))!=null?uo:j(L,!0))!=null?ht:`tool-${p()}`;if(oe.has($)){oe.delete($);continue}let z=ee($),K=(On=z.toolCall)!=null?On:{id:$,status:"running"};K.status="complete",L.result!==void 0&&(K.result=L.result),typeof L.duration=="number"&&(K.duration=L.duration),K.completedAt=Ee((ko=L.completedAt)!=null?ko:L.timestamp);let G=(_n=L.duration)!=null?_n:L.executionTime;if(typeof G=="number")K.durationMs=G;else{let lt=(Ir=K.startedAt)!=null?Ir:Date.now();K.durationMs=Math.max(0,((xa=K.completedAt)!=null?xa:Date.now())-lt)}z.toolCall=K,z.streaming=!1;let De=L.agentContext;(De||L.executionId)&&(z.agentMetadata=(ln=z.agentMetadata)!=null?ln:{executionId:(sn=De==null?void 0:De.executionId)!=null?sn:L.executionId,iteration:(zo=De==null?void 0:De.iteration)!=null?zo:L.iteration}),f(z);let tt=Q(L);tt&&P.byCall.delete(tt)}else if(rt==="await"&&L.toolName){let $=typeof L.toolCallId=="string"&&L.toolCallId.length>0?L.toolCallId:void 0,z=(dn=$!=null?$:L.toolId)!=null?dn:`local-${p()}`,K=ee(z),G=L.toolName,De=L.origin==="webmcp"&&!An(G)?`webmcp:${G}`:G,tt=An(De),lt=(Un=K.toolCall)!=null?Un:{id:z,status:"pending"};lt.name=De,lt.args=L.parameters,lt.status=tt?"running":"complete",lt.chunks=(qn=lt.chunks)!=null?qn:[],lt.startedAt=(Or=lt.startedAt)!=null?Or:Ee((vt=(cn=L.startedAt)!=null?cn:L.timestamp)!=null?vt:L.awaitedAt),tt?(lt.completedAt=void 0,lt.duration=void 0,lt.durationMs=void 0):lt.completedAt=(_r=lt.completedAt)!=null?_r:lt.startedAt,K.toolCall=lt,K.streaming=!1,K.agentMetadata={...K.agentMetadata,executionId:(At=L.executionId)!=null?At:(Sr=K.agentMetadata)==null?void 0:Sr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(K)}else if(rt==="text_start"){let $=typeof L.id=="string"?L.id:null,z=typeof L.parentToolCallId=="string"&&L.parentToolCallId?L.parentToolCallId:null;if($&&z){y.set($,z);continue}let K=h;K&&(Ye==="flow"?(fe(K),jt=K):(K.streaming=!1,f(K)),h=null),A=typeof L.id=="string"?L.id:A,T=""}else if(rt==="text_delta"){let $=typeof L.id=="string"?L.id:null,z=$?y.get($):void 0;if($&&z){let G=typeof L.delta=="string"?L.delta:"",De=((Jr=v.get($))!=null?Jr:"")+G;if(v.set($,De),De.trim()==="")continue;let tt=X($,z);tt.agentMetadata={...tt.agentMetadata,executionId:L.executionId,parentToolId:z},ct(tt,De,G,void 0);continue}if(A=typeof L.id=="string"?L.id:A,Ye==="flow"){let G=typeof L.delta=="string"?L.delta:"";if(T+=G,T.trim()==="")continue;let De=Z();De.agentMetadata={executionId:L.executionId,iteration:L.iteration},ct(De,T,G,void 0),b=De;continue}let K=Z();K.content+=(Yr=L.delta)!=null?Yr:"",K.agentMetadata={executionId:L.executionId,iteration:L.iteration,turnId:xe!=null?xe:void 0,agentName:de==null?void 0:de.agentName},b=K,f(K)}else if(rt==="text_complete"){let $=typeof L.id=="string"?L.id:null;if($&&y.has($)){let K=w.get($);K&&fe(K),y.delete($),v.delete($),w.delete($);continue}let z=h;z&&(Ye==="flow"?(fe(z),jt=z):(((Ur=z.content)!=null?Ur:"")===""&&typeof L.text=="string"&&(z.content=L.text),z.streaming=!1,f(z)),h=null),A=null,T=""}else if(rt==="step_complete"){let $=L.stepType,z=L.executionType;if($==="tool"||z==="context")continue;if(L.success===!1){let K=L.error,G=typeof K=="string"&&K!==""?K:K!=null&&typeof K=="object"&&Reflect.has(K,"message")?String((pn=K.message)!=null?pn:"Step failed"):"Step failed";r({type:"error",error:new Error(G)});let De=h;De&&De.streaming&&(De.streaming=!1,f(De)),r({type:"status",status:"idle"});continue}{let K=jt;jt=null;let G=L.stopReason,De=(we=L.result)==null?void 0:we.response;if(K)G&&(K.stopReason=G),De!=null?Kt(K,De):K.streaming!==!1&&(le.delete(K.id),ke.delete(K.id),K.streaming=!1,f(K));else{let tt=De!=null&&De!=="";if(tt||G){let lt=Z();G&&(lt.stopReason=G),tt?fe(lt,De):(lt.streaming=!1,f(lt))}}continue}}else if(rt==="execution_start")Ye=L.kind==="flow"?"flow":"agent",Vt=!0,Ye==="agent"&&(de={executionId:L.executionId,agentId:($o=L.agentId)!=null?$o:"virtual",agentName:(Zr=L.agentName)!=null?Zr:"",status:"running",currentIteration:0,maxTurns:(Nt=L.maxTurns)!=null?Nt:1,startedAt:Ee(L.startedAt)});else if(rt==="turn_start"){let $=typeof L.iteration=="number"?L.iteration:ve;if($!==ve){if(de&&(de.currentIteration=$),Ct==="separate"&&$>1){let z=h;z&&(z.streaming=!1,f(z),Cr.set($-1,z),h=null)}ve=$}xe=typeof L.id=="string"?L.id:null,b=null}else if(rt==="tool_input_delta"){let $=(eo=L.toolCallId)!=null?eo:P.lastId;if($){let z=H.get($);z!=null&&z.toolCall&&(z.toolCall.chunks=(jo=z.toolCall.chunks)!=null?jo:[],z.toolCall.chunks.push((Ya=L.delta)!=null?Ya:""),f(z))}}else{if(rt==="tool_input_complete")continue;if(rt==="turn_complete"){let $=L.stopReason,z=h!=null?h:b;if($&&z!==null){let K=L.id;(!K||((ya=z.agentMetadata)==null?void 0:ya.turnId)===K)&&(z.stopReason=$,f(z))}xe===L.id&&(xe=null)}else if(rt==="media_start"){let $=String(L.id);Ce.set($,{mediaType:typeof L.mediaType=="string"?L.mediaType:void 0,role:typeof L.role=="string"?L.role:void 0,toolCallId:L.toolCallId,parts:[]})}else if(rt==="media_delta"){let $=Ce.get(String(L.id));$&&typeof L.delta=="string"&&$.parts.push(L.delta)}else if(rt==="media_complete"){let $=String(L.id),z=Ce.get($);Ce.delete($);let K=(Vn=(Za=typeof L.mediaType=="string"?L.mediaType:void 0)!=null?Za:z==null?void 0:z.mediaType)!=null?Vn:"application/octet-stream",G=typeof L.data=="string"?L.data:void 0,De=typeof L.url=="string"?L.url:z&&z.parts.length>0?z.parts.join(""):void 0,tt=null;if(G)tt={type:"media",data:G,mediaType:K};else if(De){let Hr=K.toLowerCase();tt={type:Hr==="image"||Hr.startsWith("image/")?"image-url":"file-url",url:De,mediaType:K}}let lt=(Lo=L.toolCallId)!=null?Lo:z==null?void 0:z.toolCallId,bl=tt?[tt]:[],gn=[];for(let Hr of bl){if(!Hr||typeof Hr!="object")continue;let Jt=Hr,hn=typeof Jt.type=="string"?Jt.type:void 0,to=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tr=null,Wr="";if(hn==="media"){let Er=typeof Jt.data=="string"?Jt.data:void 0;if(!Er)continue;Wr=to.length>0?to:"application/octet-stream",Tr=`data:${Wr};base64,${Er}`}else if(hn==="image-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else if(hn==="file-url"){let Er=typeof Jt.url=="string"?Jt.url:void 0;if(!Er)continue;Wr=to,Tr=Er}else continue;if(Tr)if(hn==="image-url"||Wr.startsWith("image/"))gn.push({type:"image",image:Tr,...Wr.includes("/")?{mimeType:Wr}:{}});else if(Wr.startsWith("audio/"))gn.push({type:"audio",audio:Tr,mimeType:Wr});else if(Wr.startsWith("video/"))gn.push({type:"video",video:Tr,mimeType:Wr});else{let Er=Wr||"application/octet-stream";gn.push({type:"file",data:Tr,mimeType:Er,filename:Ub(Er)})}}if(gn.length>0){let Hr=p(),Jt=lt,to={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${Hr}`:String(Hr)}`,role:"assistant",content:"",contentParts:gn,createdAt:new Date().toISOString(),streaming:!1,sequence:Hr,agentMetadata:{executionId:L.executionId,iteration:typeof L.iteration=="number"?L.iteration:ve}};f(to);let Tr=h;Tr&&(Tr.streaming=!1,f(Tr)),h=null,k.current=null}}else if(rt==="execution_complete"){let $=(un=L.kind)!=null?un:Ye;$==="agent"&&de&&(de.status=L.success?"complete":"error",de.completedAt=Ee(L.completedAt),de.stopReason=L.stopReason);let z=h;z&&($==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,f(z)),h=null),A=null,T="",jt=null,r({type:"status",status:"idle",terminal:!0})}else if(rt==="execution_error"){let $=typeof L.error=="string"?L.error:(ar=(it=L.error)==null?void 0:it.message)!=null?ar:"Execution error";r({type:"error",error:new Error($)})}else if(rt!=="ping"){if(rt==="approval_start"){let $=(sr=L.approvalId)!=null?sr:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(Po=de==null?void 0:de.agentId)!=null?Po:"virtual",executionId:(Go=(es=L.executionId)!=null?es:de==null?void 0:de.executionId)!=null?Go:"",toolName:(zn=L.toolName)!=null?zn:"",toolType:L.toolType,description:(U=L.description)!=null?U:`Execute ${(Ro=L.toolName)!=null?Ro:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="step_await"&&L.awaitReason==="approval_required"){let $=(ba=L.approvalId)!=null?ba:`approval-${p()}`,z={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:"pending",agentId:(fo=de==null?void 0:de.agentId)!=null?fo:"virtual",executionId:(Ko=(Io=L.executionId)!=null?Io:de==null?void 0:de.executionId)!=null?Ko:"",toolName:(Ho=L.toolName)!=null?Ho:"",toolType:L.toolType,description:(va=L.description)!=null?va:`Execute ${(mo=L.toolName)!=null?mo:"tool"}`,...typeof L.reason=="string"&&L.reason?{reason:L.reason}:{},parameters:L.parameters}};f(z)}else if(rt==="approval_complete"){let $=L.approvalId;if($){let K={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:$,status:($s=L.decision)!=null?$s:"approved",agentId:(yr=de==null?void 0:de.agentId)!=null?yr:"virtual",executionId:(go=(Ar=L.executionId)!=null?Ar:de==null?void 0:de.executionId)!=null?go:"",toolName:(Mr=L.toolName)!=null?Mr:"",description:($n=L.description)!=null?$n:"",resolvedAt:Date.now()}};f(K)}}else if(rt==="artifact_start"||rt==="artifact_delta"||rt==="artifact_update"||rt==="artifact_complete"){if(rt==="artifact_start"){let $=L.artifactType,z=String(L.id),K=typeof L.title=="string"?L.title:void 0;if(r({type:"artifact_start",id:z,artifactType:$,title:K,component:typeof L.component=="string"?L.component:void 0}),Te.set(z,{markdown:"",title:K}),!ge.has(z)){ge.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:K,artifactType:$,status:"streaming"}})};se.set(z,G),f(G)}}else if(rt==="artifact_delta"){let $=String(L.id),z=typeof L.delta=="string"?L.delta:String((ho=L.delta)!=null?ho:"");r({type:"artifact_delta",id:$,artDelta:z});let K=Te.get($);K&&(K.markdown+=z)}else if(rt==="artifact_update"){let $=L.props&&typeof L.props=="object"&&!Array.isArray(L.props)?L.props:{};r({type:"artifact_update",id:String(L.id),props:$,component:typeof L.component=="string"?L.component:void 0})}else if(rt==="artifact_complete"){let $=String(L.id);r({type:"artifact_complete",id:$});let z=se.get($);if(z){z.streaming=!1;try{let K=JSON.parse((br=z.rawContent)!=null?br:"{}");if(K.props){K.props.status="complete";let G=Te.get($);G!=null&&G.markdown&&(K.props.markdown=G.markdown)}z.rawContent=JSON.stringify(K)}catch{}Te.delete($),f(z),se.delete($)}}}else if(rt==="transcript_insert"){let $=L.message;if(!$||typeof $!="object")continue;let z=String((Wo=$.id)!=null?Wo:`msg-${p()}`),K=$.role,De={id:z,role:K==="user"?"user":K==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:p()};if(f(De),De.rawContent)try{let tt=JSON.parse(De.rawContent),lt=(wa=tt==null?void 0:tt.props)==null?void 0:wa.artifactId;typeof lt=="string"&&ge.add(lt)}catch{}h=null,k.current=null,le.delete(z),ke.delete(z)}else if(rt==="error"){if(L.recoverable===!1&&L.error!=null&&L.error!==""){let $=typeof L.error=="string"?L.error:((jn=L.error)==null?void 0:jn.message)!=null?String(L.error.message):"Execution error";r({type:"error",error:new Error($)});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}else if(rt==="step_error"||rt==="dispatch_error"||rt==="flow_error"){let $=null;if(L.error instanceof Error)$=L.error;else if(rt==="dispatch_error"){let z=(Ca=L.message)!=null?Ca:L.error;z!=null&&z!==""&&($=new Error(String(z)))}else{let z=L.error;typeof z=="string"&&z!==""?$=new Error(z):z!=null&&typeof z=="object"&&Reflect.has(z,"message")&&($=new Error(String((fn=z.message)!=null?fn:z)))}if($){r({type:"error",error:$});let z=h;z&&z.streaming&&(z.streaming=!1,f(z)),r({type:"status",status:"idle"})}}}}}st.length=0};;){let{done:W,value:ce}=await a.read();if(W)break;i+=s.decode(ce,{stream:!0});let Se=i.split(`
13
13
 
14
14
  `);i=(Co=Se.pop())!=null?Co:"";for(let Ae of Se){let Ie=Ae.split(`
15
15
  `),et="message",Qe="",gt=null;for(let ae of Ie)ae.startsWith("event:")?et=ae.replace("event:","").trim():ae.startsWith("data:")?Qe+=ae.replace("data:","").trim():ae.startsWith("id:")&&(gt=ae.slice(3).trim());let pe=()=>{gt!==null&&gt!==""&&r({type:"cursor",id:gt})};if(!Qe){pe();continue}let N;try{N=JSON.parse(Qe)}catch(ae){r({type:"error",error:ae instanceof Error?ae:new Error("Failed to parse chat stream payload")});continue}let ye=et!=="message"?et:(So=N.type)!=null?So:"message";if((Ve=this.onSSEEvent)==null||Ve.call(this,ye,N),this.parseSSEEvent){k.current=h;let ae=await this.handleCustomSSEEvent(N,r,k,f,p,E);if(k.current&&k.current!==h&&(h=k.current),ae){pe();continue}}st.push({payloadType:ye,payload:N}),je(),pe()}}je()}};function uh(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Da(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Pn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var yi="[Image]";function fh(e){return typeof e=="string"?[{type:"text",text:e}]:e}function mh(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function gh(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function hh(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function As(e){return{type:"text",text:e}}function xh(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function yh(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function bh(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var vh=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zb=["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"],en=[...vh,...zb];function $b(e){return vh.includes(e)||e.startsWith("image/")}function bi(e){return $b(e.type)}async function wh(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;bi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Ch(e,t=en,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function jb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Sh(e,t){let r=jb(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var vi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Ah=16e3,Gb=24e3,Kb=4096,Xb=1380533830;function Qb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Xb?new Uint8Array(e,44):new Uint8Array(e)}function Jb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Ms=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let d=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Ah,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){d.getTracks().forEach(b=>b.stop());return}this.mediaStream=d;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:Ah});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let g=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new vi(Gb);if(n!==this.callGeneration){g.destroy(),d.getTracks().forEach(b=>b.stop()),u.close().catch(()=>{});return}this.playback=g,g.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let f=`${Jb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,h=new WebSocket(f,["runtype.bearer",r]);h.binaryType="arraybuffer",this.ws=h,h.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,d,h,n))},h.onmessage=b=>this.handleMessage(b,n),h.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},h.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let k=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${k}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(d){throw this.cleanup(),this.emitError(d),this.emitStatus("error"),d}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(Kb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),d=new Int16Array(c.length);for(let p=0;p<c.length;p++){let u=Math.max(-1,Math.min(1,c[p]));d[p]=u<0?u*32768:u*32767}o.send(d.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=Qb(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var ia=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Rn(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Ms(e.runtype);case"browser":if(!ia.isSupported())throw new Error("Browser speech recognition not supported");return new ia(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function wi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Rn({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Rn({type:"runtype",runtype:e.runtype});if(ia.isSupported())return Rn({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Ts(e){try{return wi(e),!0}catch{return!1}}function Fa(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var In=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Fa(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var d,p;let c=i.error;c==="canceled"||c==="interrupted"?(d=r.onEnd)==null||d.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var la=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function Xl(e){if(!e)return"";let t=Yb(e);return Mh(t!==null?t:e)}function Yb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Mh(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
16
16
  `),t=t.replace(/\n{2,}/g,`
17
17
  `),t.trim()}var Ql=null,Th=e=>{Ql=e},Jl=()=>Ql?Ql():import("./runtype-tts-entry");var tv=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function rv(e,t){return tv.some(r=>e[r]!==t[r])}function Yl(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="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 r.message?`${o}
18
18
 
19
- _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]}),Lh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ph=e=>An(e)||e===vo,Na=class{constructor(t={},r){this.config=t;this.callbacks=r;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 la(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(An(g.name)||g.name===vo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new sa(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(d=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId)!=null?d:this.config.agentId;!r||!o||!this.config.clientToken||Jl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId)!=null?c:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(d&&p&&u)return Jl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:h})=>{let b=new f({host:d,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new h(b,r,{onFallback:k=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${k.message}`)}):b});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"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,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=p.id}if(d){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=p.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,d,p,u,g,f;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(d=(c=t.runtype)==null?void 0:c.host)!=null?d:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!rv(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new sa(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:p,rawContent:u}=t,f={id:s!=null?s:r==="user"?Da():r==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,b={id:c!=null?c:n==="user"?Da():n==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,p,u,g,f;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let n=Da(),a=Pn();this.activeAssistantMessageId=null;let s={id:n,role:"user",content:o||yi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(h){if(this.status==="resuming"||this.reconnecting)return;let b=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!b){let k=Yl(h,this.config.errorMessage);if(k){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:k,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(h instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,h):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(h))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort(),this.teardownReconnect();let t=Pn();this.activeAssistantMessageId=null,this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let p=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!p){let u=Yl(d,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var a,s,i;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(a=this.abortController)==null||a.abort(),r!=null&&r.preserveAssistantId&&r.assistantMessageId&&(this.activeAssistantMessageId=r.assistantMessageId);let o=r!=null&&r.preserveAssistantId?r.assistantMessageId:void 0,n=!1;for(let c of this.messages)c.streaming&&c.id!==o&&(c.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId,r==null?void 0:r.seedContent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(s=this.callbacks).onError)==null||i.call(s,c instanceof Error?c:new Error(String(c)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,u,g,f,h;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(d?b=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let k=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((g=E==null?void 0:E.error)!=null?g:`Approval request failed: ${b.status}`)}k=b.body}else b instanceof ReadableStream&&(k=b);k?await this.connectStream(k,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let k=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(h=(f=this.callbacks).onError)==null||h.call(f,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,u,g,f,h,b,k,E,A,T,y,w;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(u=t.agentMetadata)==null?void 0:u.executionId,a=(g=t.toolCall)==null?void 0:g.name;if(!n||!a){(h=(f=this.callbacks).onError)==null||h.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let H=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,H])=>`${M}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};d.forEach((M,H)=>{let I=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!I)return;let P=v[I],B=Array.isArray(P)?P.join(", "):typeof P=="string"?P:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:B||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(w=(y=this.callbacks).onError)==null||w.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==vo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,p,u;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async g=>{var w,v,M,H,I,P,B;let f=(w=g.toolCall)==null?void 0:w.name,h=(v=g.toolCall)==null?void 0:v.id;if(!f||!h)return null;let b=`${t}:${h}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(b),o.push(b);let k=this.markWebMcpToolRunning(g),E=(H=(M=g.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?H:f;if(f===vo)return{dedupeKey:b,resumeKey:E,output:Vl(),toolMessage:g,startedAt:k,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(f,(I=g.toolCall)==null?void 0:I.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(B=(P=this.callbacks).onError)==null||B.call(P,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,Es(Q?"Aborted by cancel()":Lh(O)),k),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(g,Es("Aborted by cancel()"),k),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:g,startedAt:k,completedAt:Date.now()}})),i=[];try{if(i=s.filter(h=>h!==null),i.length===0)return;let g={};for(let h of i)g[h.resumeKey]=h.output;let f=await this.client.resumeFlow(t,g,{signal:a.signal});if(!f.ok){let h=await f.json().catch(()=>null);throw new Error((c=h==null?void 0:h.error)!=null?c:`Resume failed: ${f.status}`)}for(let h of i)this.webMcpResolvedKeys.add(h.dedupeKey),this.markWebMcpToolComplete(h.toolMessage,h.output,h.startedAt,h.completedAt,((d=h.toolMessage.toolCall)==null?void 0:d.name)===vo?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let h of i)this.markWebMcpToolComplete(h.toolMessage,Es("Aborted by cancel()"),h.startedAt)}finally{for(let g of o)this.webMcpInflightKeys.delete(g);for(let g of n)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var h,b,k,E,A,T,y,w,v,M,H,I;let r=(h=t.agentMetadata)==null?void 0:h.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(k=t.toolCall)==null?void 0:k.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let P=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(B){(y=(T=this.callbacks).onError)==null||y.call(T,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(P)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===vo,p=(w=t.toolCall)==null?void 0:w.args,u=d?null:this.client.executeWebMcpToolCall(o,p,c),g="execute",f=s;try{let P;if(d?P=Vl():u?P=await u:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Es("Aborted by cancel()"),s);return}let B=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;g="resume",await this.resumeWithToolOutput(r,B,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,P,s,f,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(P){let B=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(g==="execute"||B||c.aborted)&&this.markWebMcpToolComplete(t,Es(B||c.aborted?"Aborted by cancel()":Lh(P)),s),B||(I=(H=this.callbacks).onError)==null||I.call(H,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}trackCursor(t){var n,a;let r=(n=this.agentExecution)==null?void 0:n.executionId;if(!r||!this.activeAssistantMessageId||((a=this.agentExecution)==null?void 0:a.status)!=="running")return;let o=this.resumable===null;this.resumable={executionId:r,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var r,o,n;return((r=t.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&((o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((n=t.approval)==null?void 0:n.status)==="pending"})}beginReconnect(){var t,r;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(r=(t=this.callbacks).onReconnect)==null||r.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(o=>{this.reconnecting&&this.resumable&&o.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(kh(),Eh)).then(({createReconnectController:t})=>{let r=t(this.buildReconnectHost());return this.reconnectController=r,r})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:r=>t.setStatus(r),setStreaming:r=>t.setStreaming(r),setReconnecting:r=>{t.reconnecting=r},setAbortController:r=>{t.abortController=r},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(r,o,n)=>t.connectStream(r,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:r=>t.appendMessage(r),nextSequence:()=>t.nextSequence(),emitReconnect:r=>{var o,n;return(n=(o=t.callbacks).onReconnect)==null?void 0:n.call(o,r)},buildErrorContent:r=>Yl(new Error(r),t.config.errorMessage),onError:r=>{var o,n;return(n=(o=t.callbacks).onError)==null?void 0:n.call(o,r)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let r=this.reopenTrailingAssistant();r||(r=Pn(),this.appendMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=r,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:r,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(r.role==="assistant"&&!r.variant)return r.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),r.id;if(r.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var r,o;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((o=(r=this.config).onExecutionState)==null||o.call(r,null))}notifyExecutionState(t){let r=this.config.onExecutionState;if(r){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),r(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var o,n;this.executionStateTimer=null,(n=(o=this.config).onExecutionState)==null||n.call(o,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=Xl(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Xl(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,u,g,f,h,b,k,E,A,T,y,w,v,M,H;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=n.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(g=s.agentMetadata)!=null?g:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let I=n.approval,P=r.approval;s.approval={...I,...P,executionId:P.executionId||I.executionId,toolName:P.toolName||I.toolName,description:P.description||I.description,toolType:(f=P.toolType)!=null?f:I.toolType,reason:(h=P.reason)!=null?h:I.reason,parameters:(b=P.parameters)!=null?b:I.parameters}}let i=(k=r.toolCall)==null?void 0:k.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(A=r.toolCall)==null?void 0:A.id;if(i&&Ph(i)&&c&&d&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let I=`${c}:${d}`,P=this.webMcpInflightKeys.has(I),B=this.webMcpResolvedKeys.has(I),O=(y=n.toolCall)==null?void 0:y.name,Q=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===d&&O!==void 0&&Ph(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(P||B||Q)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Zl=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var ed=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var rd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var od=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var nd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ad=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var sd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var id=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var ld=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var dd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var cd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var pd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var ud=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var fd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var md=[["path",{d:"M20 6 9 17l-5-5"}]];var gd=[["path",{d:"m6 9 6 6 6-6"}]];var hd=[["path",{d:"m15 18-6-6 6-6"}]];var xd=[["path",{d:"m9 18 6-6-6-6"}]];var yd=[["path",{d:"m18 15-6-6-6 6"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var bd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var vd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var wd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Cd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Sd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ad=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Md=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Mi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Td=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Ed=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var kd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ld=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Pd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Rd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Id=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Hd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Wd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Bd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Dd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Fd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Ti=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Nd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Od=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var _d=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Ud=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var qd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Vd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Ei=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var zd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var $d=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Gd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Kd=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var ki=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Xd=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Qd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Jd=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Yd=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Zd=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var ec=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var tc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var rc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var oc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var nc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var ac=[["path",{d:"M5 12h14"}]];var sc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var ic=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var lc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var dc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var cc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var pc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var uc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var fc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var mc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var gc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var hc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var xc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var yc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var bc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var vc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var wc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Cc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Sc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Ac=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Mc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Li=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Tc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Ec=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var kc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Lc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Pi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Pc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Rc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Ic=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Wc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Bc=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Dc=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Fc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Nc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Oc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ri=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var _c=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Uc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var qc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Vc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var zc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var $c=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var jc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Gc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var ov={activity:Zl,"arrow-down":ed,"arrow-up":nd,"arrow-up-right":od,bot:dd,"chevron-down":gd,"chevron-up":yd,"chevron-right":xd,"chevron-left":hd,check:md,clipboard:vd,"clipboard-copy":bd,copy:Cd,file:Id,"file-code":Ld,"file-spreadsheet":Pd,"file-text":Rd,"image-plus":zd,loader:Xd,"loader-circle":ki,mic:oc,paperclip:dc,"refresh-cw":xc,search:vc,send:wc,"shield-alert":Ac,"shield-check":Mc,"shield-x":Li,square:Pc,"thumbs-down":Bc,"thumbs-up":Dc,upload:Uc,"volume-2":Vc,x:jc,user:qc,mail:Jd,phone:fc,calendar:ud,clock:wd,building:cd,"map-pin":Yd,lock:Qd,key:Gd,"credit-card":Sd,"at-sign":ad,hash:_d,globe:Od,link:Kd,"circle-check":Ci,"circle-x":Si,"triangle-alert":Ri,info:jd,ban:sd,shield:Tc,"arrow-left":td,"arrow-right":rd,"external-link":Ed,ellipsis:Mi,"ellipsis-vertical":Ai,menu:ec,house:Ei,plus:gc,minus:ac,pencil:pc,trash:Oc,"trash-2":Nc,save:bc,download:Md,share:Sc,funnel:Ti,settings:Cc,"rotate-cw":yc,maximize:Zd,minimize:nc,"shopping-cart":kc,"shopping-bag":Ec,package:lc,truck:_c,tag:Wc,gift:Nd,receipt:hc,wallet:$c,store:Ic,"dollar-sign":Ad,percent:uc,play:mc,pause:cc,"volume-x":zc,camera:fd,image:$d,film:Wd,headphones:Ud,"message-circle":tc,"message-square":rc,bell:id,heart:qd,star:Rc,eye:kd,"eye-off":Td,bookmark:ld,"calendar-days":pd,history:Vd,timer:Fc,folder:Fd,"folder-open":Dd,files:Hd,sparkles:Pi,zap:Gc,sun:Hc,moon:ic,flag:Bd,monitor:sc,smartphone:Lc},he=(e,t=24,r="currentColor",o=2)=>{let n=ov[e];return n?nv(n,t,r,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function nv(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),n.appendChild(c)}),n}var Ii={allowedTypes:en,maxFileSize:10*1024*1024,maxFiles:4};function av(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sv(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var da=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ii.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ii.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ii.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ii.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let p=Ch(d,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,u);continue}try{let u=await wh(d),g=bi(d)?URL.createObjectURL(d):null,f={id:av(),file:d,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=bi(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=sv(t.file.type),c=he(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Sh(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=he("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Rh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];Rh(a)&&Rh(n)?r[o]=ks(a,n):r[o]=n}return r}var Gr="min(440px, calc(100vw - 24px))",Hi="440px",iv={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:Gr,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:iv,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 Ih(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Wi(e){var t,r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w;return e?{...Ht,...e,theme:Ih(Ht.theme,e.theme),darkTheme:Ih(Ht.darkTheme,e.darkTheme),launcher:{...Ht.launcher,...e.launcher,dock:{...(t=Ht.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Ht.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Ht.copy,...e.copy},sendButton:{...Ht.sendButton,...e.sendButton},statusIndicator:{...Ht.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le;let v=(oe=Ht.features)==null?void 0:oe.artifacts,M=(se=e.features)==null?void 0:se.artifacts,H=(ge=Ht.features)==null?void 0:ge.scrollToBottom,I=(Te=e.features)==null?void 0:Te.scrollToBottom,P=(qe=Ht.features)==null?void 0:qe.scrollBehavior,B=(j=e.features)==null?void 0:j.scrollBehavior,O=(ee=Ht.features)==null?void 0:ee.streamAnimation,Q=(Ee=e.features)==null?void 0:Ee.streamAnimation,me=(te=Ht.features)==null?void 0:te.askUserQuestion,ue=(le=e.features)==null?void 0:le.askUserQuestion,Z=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Le=H===void 0&&I===void 0?void 0:{...H,...I},We=P===void 0&&B===void 0?void 0:{...P,...B},ie=O===void 0&&Q===void 0?void 0:{...O,...Q},Me=me===void 0&&ue===void 0?void 0:{...me,...ue,styles:{...me==null?void 0:me.styles,...ue==null?void 0:ue.styles}};return{...Ht.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...We!==void 0?{scrollBehavior:We}:{},...Z!==void 0?{artifacts:Z}:{},...ie!==void 0?{streamAnimation:ie}:{},...Me!==void 0?{askUserQuestion:Me}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ht.layout,...e.layout,header:{...(s=Ht.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Ht.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(u=(p=Ht.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(b=(h=Ht.layout)==null?void 0:h.messages)==null?void 0:b.timestamp,...(E=(k=e.layout)==null?void 0:k.messages)==null?void 0:E.timestamp}},slots:{...(A=Ht.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Ht.markdown,...e.markdown,options:{...(y=Ht.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Ht.messageActions,...e.messageActions}}:Ht}var Kc={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"}},Xc={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"}},Qc={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:Gr,maxWidth:Hi,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 Oa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Oa(e,o):o}function Bi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Oa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Jc(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function Hh(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=Hh(a,n):r[o]=n}return r}function lv(e,t){return t?Hh(e,t):e}function _a(e,t={}){var n,a,s,i,c,d,p,u,g,f,h,b,k;let r={palette:Kc,semantic:Xc,components:Qc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...r.semantic.colors.feedback,...(h=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:h.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:lv(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Jc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Di(e){var b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe,X,st,je,Ce,ve,Ye,Vt,xe,de,Cr,Ct,xr,Co,So,Ve,W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn;let t=Bi(e),r={};for(let[we,$o]of Object.entries(t)){let Zr=we.replace(/\./g,"-");r[`--persona-${Zr}`]=$o.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(k=r["--persona-semantic-colors-secondary"])!=null?k:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(I=r["--persona-semantic-colors-divider"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(P=r["--persona-components-voice-recording-indicator"])!=null?P:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(B=r["--persona-components-voice-recording-background"])!=null?B:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ue=r["--persona-components-approval-requested-border"])!=null?ue:r["--persona-border"],r["--persona-approval-text"]=(Z=r["--persona-components-approval-requested-text"])!=null?Z:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Le=r["--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)",r["--persona-approval-approve-bg"]=(We=r["--persona-components-approval-approve-background"])!=null?We:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(ie=r["--persona-components-approval-deny-background"])!=null?ie:r["--persona-container"],r["--persona-attachment-image-bg"]=(Me=r["--persona-components-attachment-image-background"])!=null?Me:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(oe=r["--persona-components-attachment-image-border"])!=null?oe:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(se=r["--persona-semantic-typography-fontFamily"])!=null?se:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ge=r["--persona-semantic-typography-fontSize"])!=null?ge:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Te=r["--persona-semantic-typography-fontWeight"])!=null?Te:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(qe=r["--persona-semantic-typography-lineHeight"])!=null?qe:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(j=r["--persona-palette-radius-sm"])!=null?j:"0.125rem",r["--persona-radius-md"]=(ee=r["--persona-palette-radius-md"])!=null?ee:"0.375rem",r["--persona-radius-lg"]=(Ee=r["--persona-palette-radius-lg"])!=null?Ee:"0.5rem",r["--persona-radius-xl"]=(te=r["--persona-palette-radius-xl"])!=null?te:"0.75rem",r["--persona-radius-full"]=(le=r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-radius"]=(nt=(ke=r["--persona-components-launcher-borderRadius"])!=null?ke:r["--persona-palette-radius-full"])!=null?nt:"9999px",r["--persona-launcher-bg"]=(yt=r["--persona-components-launcher-background"])!=null?yt:r["--persona-primary"],r["--persona-launcher-fg"]=(Kt=r["--persona-components-launcher-foreground"])!=null?Kt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(jt=r["--persona-components-launcher-border"])!=null?jt:r["--persona-border"],r["--persona-button-primary-bg"]=(ct=r["--persona-components-button-primary-background"])!=null?ct:r["--persona-primary"],r["--persona-button-primary-fg"]=(fe=r["--persona-components-button-primary-foreground"])!=null?fe:r["--persona-text-inverse"],r["--persona-button-radius"]=(st=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?st:"9999px",r["--persona-panel-radius"]=(Ce=(je=r["--persona-components-panel-borderRadius"])!=null?je:r["--persona-radius-xl"])!=null?Ce:"0.75rem",r["--persona-panel-border"]=(ve=r["--persona-components-panel-border"])!=null?ve:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Vt=(Ye=r["--persona-components-panel-shadow"])!=null?Ye:r["--persona-palette-shadows-xl"])!=null?Vt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(xe=r["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Cr=(de=r["--persona-components-input-borderRadius"])!=null?de:r["--persona-radius-lg"])!=null?Cr:"0.5rem",r["--persona-message-user-radius"]=(xr=(Ct=r["--persona-components-message-user-borderRadius"])!=null?Ct:r["--persona-radius-lg"])!=null?xr:"0.5rem",r["--persona-message-assistant-radius"]=(So=(Co=r["--persona-components-message-assistant-borderRadius"])!=null?Co:r["--persona-radius-lg"])!=null?So:"0.5rem",r["--persona-header-bg"]=(Ve=r["--persona-components-header-background"])!=null?Ve:r["--persona-surface"],r["--persona-header-border"]=(W=r["--persona-components-header-border"])!=null?W:r["--persona-divider"],r["--persona-header-icon-bg"]=(ce=r["--persona-components-header-iconBackground"])!=null?ce:r["--persona-primary"],r["--persona-header-icon-fg"]=(Se=r["--persona-components-header-iconForeground"])!=null?Se:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ae=r["--persona-components-header-titleForeground"])!=null?Ae:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ie=r["--persona-components-header-subtitleForeground"])!=null?Ie:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(et=r["--persona-components-header-actionIconForeground"])!=null?et:r["--persona-muted"];let o=(Qe=e.components)==null?void 0:Qe.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(gt=e.components)==null?void 0:gt.introCard;r["--persona-intro-card-bg"]=(pe=r["--persona-components-introCard-background"])!=null?pe:r["--persona-surface"],r["--persona-intro-card-radius"]=(N=r["--persona-components-introCard-borderRadius"])!=null?N:"1rem",r["--persona-intro-card-padding"]=(ye=r["--persona-components-introCard-padding"])!=null?ye:"1.5rem",r["--persona-intro-card-shadow"]=(mt=(ae=n==null?void 0:n.shadow)!=null?ae:r["--persona-components-introCard-shadow"])!=null?mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ke=r["--persona-components-input-background"])!=null?Ke:r["--persona-surface"],r["--persona-input-placeholder"]=(Lt=r["--persona-components-input-placeholder"])!=null?Lt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Et=r["--persona-components-message-user-background"])!=null?Et:r["--persona-accent"],r["--persona-message-user-text"]=(bt=r["--persona-components-message-user-text"])!=null?bt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(It=r["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Qt=r["--persona-components-message-assistant-background"])!=null?Qt:r["--persona-surface"],r["--persona-message-assistant-text"]=(Ft=r["--persona-components-message-assistant-text"])!=null?Ft:r["--persona-text"],r["--persona-message-assistant-border"]=(tr=r["--persona-components-message-assistant-border"])!=null?tr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(Ao=r["--persona-components-message-assistant-shadow"])!=null?Ao:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(io=(Uo=r["--persona-components-scrollToBottom-background"])!=null?Uo:r["--persona-button-primary-bg"])!=null?io:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(on=(lo=r["--persona-components-scrollToBottom-foreground"])!=null?lo:r["--persona-button-primary-fg"])!=null?on:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(zt=r["--persona-components-scrollToBottom-border"])!=null?zt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(co=r["--persona-components-scrollToBottom-size"])!=null?co:"40px",r["--persona-scroll-to-bottom-radius"]=(Rr=(Fr=(qo=r["--persona-components-scrollToBottom-borderRadius"])!=null?qo:r["--persona-button-radius"])!=null?Fr:r["--persona-radius-full"])!=null?Rr:"9999px",r["--persona-scroll-to-bottom-shadow"]=(po=(Nr=r["--persona-components-scrollToBottom-shadow"])!=null?Nr:r["--persona-palette-shadows-sm"])!=null?po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Mo=r["--persona-components-scrollToBottom-padding"])!=null?Mo:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(nn=r["--persona-components-scrollToBottom-gap"])!=null?nn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(an=(Qr=r["--persona-components-scrollToBottom-fontSize"])!=null?Qr:r["--persona-palette-typography-fontSize-sm"])!=null?an:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(St=r["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",r["--persona-tool-bubble-shadow"]=(To=r["--persona-components-toolBubble-shadow"])!=null?To:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Eo=r["--persona-components-reasoningBubble-shadow"])!=null?Eo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Vo=r["--persona-components-composer-shadow"])!=null?Vo:"none",r["--persona-md-inline-code-bg"]=(uo=r["--persona-components-markdown-inlineCode-background"])!=null?uo:r["--persona-container"],r["--persona-md-inline-code-color"]=(ht=r["--persona-components-markdown-inlineCode-foreground"])!=null?ht:r["--persona-text"],r["--persona-md-link-color"]=(ko=(On=r["--persona-components-markdown-link-foreground"])!=null?On:r["--persona-accent"])!=null?ko:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(_n=r["--persona-components-markdown-codeBlock-background"])!=null?_n:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Ir=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Ir:r["--persona-border"],r["--persona-md-code-block-text-color"]=(xa=r["--persona-components-markdown-codeBlock-textColor"])!=null?xa:"inherit",r["--persona-md-table-header-bg"]=(sn=r["--persona-components-markdown-table-headerBackground"])!=null?sn:r["--persona-container"],r["--persona-md-table-border-color"]=(zo=r["--persona-components-markdown-table-borderColor"])!=null?zo:r["--persona-border"],r["--persona-md-hr-color"]=(ln=r["--persona-components-markdown-hr-color"])!=null?ln:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(dn=r["--persona-components-markdown-blockquote-borderColor"])!=null?dn:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Un=r["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(cn=r["--persona-components-collapsibleWidget-container"])!=null?cn:r["--persona-surface"],r["--cw-surface"]=(vt=r["--persona-components-collapsibleWidget-surface"])!=null?vt:r["--persona-surface"],r["--cw-border"]=(Or=r["--persona-components-collapsibleWidget-border"])!=null?Or:r["--persona-border"],r["--persona-message-border"]=(_r=r["--persona-components-message-border"])!=null?_r:r["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(r["--persona-icon-btn-bg"]=u.background),u.border&&(r["--persona-icon-btn-border"]=u.border),u.color&&(r["--persona-icon-btn-color"]=u.color),u.padding&&(r["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(r["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(r["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(r["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(r["--persona-label-btn-bg"]=g.background),g.border&&(r["--persona-label-btn-border"]=g.border),g.color&&(r["--persona-label-btn-color"]=g.color),g.padding&&(r["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(r["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(r["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let h=p==null?void 0:p.artifact;if(h!=null&&h.toolbar){let we=h.toolbar;we.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,r["--persona-dropdown-bg"]=(Sr=r["--persona-dropdown-bg"])!=null?Sr:we.copyMenuBackground),we.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,r["--persona-dropdown-border"]=(At=r["--persona-dropdown-border"])!=null?At:we.copyMenuBorder),we.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,r["--persona-dropdown-shadow"]=(Jr=r["--persona-dropdown-shadow"])!=null?Jr:we.copyMenuShadow),we.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Yr=r["--persona-dropdown-radius"])!=null?Yr:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ur=r["--persona-dropdown-item-hover-bg"])!=null?Ur:we.copyMenuItemHoverBackground),we.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(h!=null&&h.tab){let we=h.tab;we.background&&(r["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(r["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(r["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(r["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(r["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(r["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(r["--persona-artifact-tab-list-padding"]=we.listPadding)}if(h!=null&&h.pane){let we=h.pane;if(we.toolbarBackground){let $o=(pn=Oa(e,we.toolbarBackground))!=null?pn:we.toolbarBackground;r["--persona-artifact-toolbar-bg"]=$o}}return r}var Wh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var dv={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"}}},Bh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ls=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},cv=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ls()},Yc=e=>cv(e),pv=e=>_a(e),uv=e=>{var r;let t=_a(void 0,{validate:!1});return _a({...e,palette:{...t.palette,colors:{...dv.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ua=e=>{let t=Yc(e),r=Bh(e==null?void 0:e.theme),o=Bh(e==null?void 0:e.darkTheme);return t==="dark"?uv(ks(r!=null?r:{},o!=null?o:{})):pv(r)},fv=e=>Di(e),Hn=(e,t)=>{let r=Ua(t),o=fv(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Fi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ls())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ls());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var Dh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(g,f,h={}){g=p(g);let b=u(f),k=d(g,b,h),E=n(k,()=>i(k,g,b,A=>A.morphStyle==="innerHTML"?(a(A,g,b),Array.from(g.childNodes)):o(A,g,b)));return k.pantry.remove(),E}function o(g,f,h){let b=u(f);return a(g,b,h,f,f.nextSibling),Array.from(b.childNodes)}function n(g,f){var T;if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:b,selectionStart:k,selectionEnd:E}=h,A=f();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(h=g.target.querySelector(`[id="${b}"]`),h==null||h.focus()),h&&!h.selectionEnd&&E&&h.setSelectionRange(k,E),A}let a=(function(){function g(y,w,v,M=null,H=null){w instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(w=w.content,v=v.content),M||(M=w.firstChild);for(let I of v.childNodes){if(M&&M!=H){let B=h(y,I,M,H);if(B){B!==M&&k(y,M,B),s(B,I,y),M=B.nextSibling;continue}}if(I instanceof Element){let B=I.getAttribute("id");if(y.persistentIds.has(B)){let O=E(w,B,M,y);s(O,I,y),M=O.nextSibling;continue}}let P=f(w,I,M,y);P&&(M=P.nextSibling)}for(;M&&M!=H;){let I=M;M=M.nextSibling,b(y,I)}}function f(y,w,v,M){if(M.callbacks.beforeNodeAdded(w)===!1)return null;if(M.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,v),s(H,w,M),M.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,v),M.callbacks.afterNodeAdded(H),H}}let h=(function(){function y(M,H,I,P){let B=null,O=H.nextSibling,Q=0,me=I;for(;me&&me!=P;){if(v(me,H)){if(w(M,me,H))return me;B===null&&(M.idMap.has(me)||(B=me))}if(B===null&&O&&v(me,O)&&(Q++,O=O.nextSibling,Q>=2&&(B=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return B||null}function w(M,H,I){let P=M.idMap.get(H),B=M.idMap.get(I);if(!B||!P)return!1;for(let O of P)if(B.has(O))return!0;return!1}function v(M,H){var B,O,Q;let I=M,P=H;return I.nodeType===P.nodeType&&I.tagName===P.tagName&&(!((B=I.getAttribute)!=null&&B.call(I,"id"))||((O=I.getAttribute)==null?void 0:O.call(I,"id"))===((Q=P.getAttribute)==null?void 0:Q.call(P,"id")))}return y})();function b(y,w){var v;if(y.idMap.has(w))T(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(v=w.parentNode)==null||v.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function k(y,w,v){let M=w;for(;M&&M!==v;){let H=M;M=M.nextSibling,b(y,H)}return M}function E(y,w,v,M){var I,P;let H=((P=(I=M.target).getAttribute)==null?void 0:P.call(I,"id"))===w&&M.target||M.target.querySelector(`[id="${w}"]`)||M.pantry.querySelector(`[id="${w}"]`);return A(H,M),T(y,H,v),H}function A(y,w){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=w.idMap.get(y);M&&(M.delete(v),M.size||w.idMap.delete(y))}}function T(y,w,v){if(y.moveBefore)try{y.moveBefore(w,v)}catch{y.insertBefore(w,v)}else y.insertBefore(w,v)}return g})(),s=(function(){function g(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(f(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function f(A,T,y){let w=T.nodeType;if(w===1){let v=A,M=T,H=v.attributes,I=M.attributes;for(let P of I)k(P.name,v,"update",y)||v.getAttribute(P.name)!==P.value&&v.setAttribute(P.name,P.value);for(let P=H.length-1;0<=P;P--){let B=H[P];if(B&&!M.hasAttribute(B.name)){if(k(B.name,v,"remove",y))continue;v.removeAttribute(B.name)}}E(v,y)||h(v,M,y)}(w===8||w===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function h(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let w=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==w&&(k("value",A,"update",y)||(A.setAttribute("value",w),A.value=w)):k("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let w=T.value,v=A.value;if(k("value",A,"update",y))return;w!==v&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function b(A,T,y,w){let v=T[y],M=A[y];if(v!==M){let H=k(y,A,"update",w);H||(A[y]=T[y]),v?H||A.setAttribute(y,""):k(y,A,"remove",w)||A.removeAttribute(y)}}function k(A,T,y,w){return A==="value"&&w.ignoreActiveValue&&T===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function i(g,f,h,b){if(g.head.block){let k=f.querySelector("head"),E=h.querySelector("head");if(k&&E){let A=c(k,E,g);return Promise.all(A).then(()=>{let T=Object.assign(g,{head:{block:!1,ignore:!0}});return b(T)})}}return b(g)}function c(g,f,h){let b=[],k=[],E=[],A=[],T=new Map;for(let w of f.children)T.set(w.outerHTML,w);for(let w of g.children){let v=T.has(w.outerHTML),M=h.head.shouldReAppend(w),H=h.head.shouldPreserve(w);v||H?M?k.push(w):(T.delete(w.outerHTML),E.push(w)):h.head.style==="append"?M&&(k.push(w),A.push(w)):h.head.shouldRemove(w)!==!1&&k.push(w)}A.push(...T.values());let y=[];for(let w of A){let v=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,H=new Promise(function(I){M=I});v.addEventListener("load",function(){M()}),y.push(H)}g.appendChild(v),h.callbacks.afterNodeAdded(v),b.push(v)}}for(let w of k)h.callbacks.beforeNodeRemoved(w)!==!1&&(g.removeChild(w),h.callbacks.afterNodeRemoved(w));return h.head.afterHeadMorphed(g,{added:b,kept:E,removed:k}),y}let d=(function(){function g(y,w,v){let{persistentIds:M,idMap:H}=A(y,w),I=f(v),P=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(P))throw`Do not understand how to morph style ${P}`;return{target:y,newContent:w,config:I,morphStyle:P,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:H,persistentIds:M,pantry:h(),activeElementAndParents:b(y),callbacks:I.callbacks,head:I.head}}function f(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function h(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let w=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(w.push(v),v!==y);)v=v.parentElement;return w}function k(y){var v;let w=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&w.push(y),w}function E(y,w,v,M){for(let H of M){let I=H.getAttribute("id");if(w.has(I)){let P=H;for(;P;){let B=y.get(P);if(B==null&&(B=new Set,y.set(P,B)),B.add(I),P===v)break;P=P.parentElement}}}}function A(y,w){let v=k(y),M=k(w),H=T(v,M),I=new Map;E(I,H,y,v);let P=w.__idiomorphRoot||w;return E(I,H,P,M),{persistentIds:H,idMap:I}}function T(y,w){let v=new Set,M=new Map;for(let{id:I,tagName:P}of y)M.has(I)?v.add(I):M.set(I,P);let H=new Set;for(let{id:I,tagName:P}of w)H.has(I)?v.add(I):M.get(I)===P&&H.add(I);for(let I of v)H.delete(I);return H}return g})(),{normalizeElement:p,normalizeParent:u}=(function(){let g=new WeakSet;function f(E){return E instanceof Document?E.documentElement:E}function h(E){if(E==null)return document.createElement("div");if(typeof E=="string")return h(k(E));if(g.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let w=y.querySelectorAll(A);for(let v=0;v<w.length;v++)T.push(w[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function k(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return g.add(y),y;{let w=y.firstChild;return w&&g.add(w),w}}else{let w=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return g.add(w),w}}return{normalizeElement:f,normalizeParent:h}})();return{morph:r,defaults:t}})();var Ni=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Dh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var Fh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Oi={index:-1,draft:""};function Nh(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Oi}}}function Oh(e,t){var r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(d=e.llmContent)==null?void 0:d.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(h=(f=e.toolCall)==null?void 0:f.status)!=null?h:"",(k=(b=e.toolCall)==null?void 0:b.name)!=null?k:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(I=e.toolCall)!=null&&I.args?JSON.stringify(e.toolCall.args).length:0,(O=(B=(P=e.reasoning)==null?void 0:P.chunks)==null?void 0:B.length)!=null?O:0,(Z=(ue=(me=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?Z:0,(Me=(ie=(We=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?Me:"",(se=(oe=e.contentParts)==null?void 0:oe.length)!=null?se:0,(ge=e.stopReason)!=null?ge:"",t].join("\0")}function _h(){return new Map}function Uh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function qh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function Vh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function _i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wn(e,t){return Oo(e)-e.scrollTop<=t}function Ui(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function qi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function zh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function $h(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function jh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var or={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},wr=1e5,Bn=wr+1;var Ps={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},mv=["pre","code","a","script","style"],Vi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ps.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ps.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ps.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ps.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ps.buffer}},Kh=[{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"}],Rs=new Map;for(let e of Kh)Rs.set(e.name,e);var ca=e=>{Rs.set(e.name,e)},tp=e=>{Kh.some(t=>t.name===e)||Rs.delete(e)},rp=()=>Array.from(Rs.keys()),qa=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Rs.get(e))!=null?o:null},zi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
19
+ _Details: ${r.message}_`:o}var Es=e=>({isError:!0,content:[{type:"text",text:e}]}),Lh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ph=e=>An(e)||e===vo,Na=class{constructor(t={},r){this.config=t;this.callbacks=r;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 la(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,d,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let g=t.message.toolCall,f=!!(g!=null&&g.name)&&(An(g.name)||g.name===vo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&f&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let g=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":g||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((d=this.agentExecution)==null?void 0:d.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new sa(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c,d;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(d=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId)!=null?d:this.config.agentId;!r||!o||!this.config.clientToken||Jl().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Ts((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=In.isSupported()?new In({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let d=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId)!=null?c:this.config.agentId,u=this.config.clientToken,g=t.browserFallback!==!1;if(d&&p&&u)return Jl().then(({RuntypeSpeechEngine:f,FallbackSpeechEngine:h})=>{let b=new f({host:d,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return g&&r?new h(b,r,{onFallback:k=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${k.message}`)}):b});if(g&&r)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=Rn(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"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,c,d)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!d});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!d});this.pendingVoiceUserMessageId=p.id}if(d){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!d,voiceProcessing:!d});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!d,voiceProcessing:!d});this.pendingVoiceAssistantMessageId=p.id}d&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,d;(d=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||d.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,d;this.voiceStatus=i,this.voiceActive=i==="listening",(d=(c=this.callbacks).onVoiceStatusChanged)==null||d.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,d,p,u,g,f;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(d=(c=t.runtype)==null?void 0:c.host)!=null?d:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((g=t.browser)==null?void 0:g.language)||"en-US",continuous:(f=t.browser)==null?void 0:f.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!rv(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new sa(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:d=!1,voiceProcessing:p,rawContent:u}=t,f={id:s!=null?s:r==="user"?Da():r==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:d,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(f),f}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:d,sequence:p,streaming:u=!1,voiceProcessing:g,rawContent:f}=o,b={id:c!=null?c:n==="user"?Da():n==="assistant"?Pn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:d!=null?d:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:u,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...g!==void 0&&{voiceProcessing:g},...f!==void 0&&{rawContent:f}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,d={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(d),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var d,p,u,g,f;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(d=this.abortController)==null||d.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let n=Da(),a=Pn();this.activeAssistantMessageId=null;let s={id:n,role:"user",content:o||yi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(h){if(this.status==="resuming"||this.reconnecting)return;let b=h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"));if(!b){let k=Yl(h,this.config.errorMessage);if(k){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:k,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(h instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,h):(f=(g=this.callbacks).onError)==null||f.call(g,new Error(String(h))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort(),this.teardownReconnect();let t=Pn();this.activeAssistantMessageId=null,this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;let p=d instanceof Error&&(d.name==="AbortError"||d.message.includes("aborted")||d.message.includes("abort"));if(!p){let u=Yl(d,this.config.errorMessage);if(u){let g={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(g)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(d instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,d):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(d))))}}async connectStream(t,r){var a,s,i;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(a=this.abortController)==null||a.abort(),r!=null&&r.preserveAssistantId&&r.assistantMessageId&&(this.activeAssistantMessageId=r.assistantMessageId);let o=r!=null&&r.preserveAssistantId?r.assistantMessageId:void 0,n=!1;for(let c of this.messages)c.streaming&&c.id!==o&&(c.streaming=!1,n=!0);n&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId,r==null?void 0:r.seedContent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(s=this.callbacks).onError)==null||i.call(s,c instanceof Error?c:new Error(String(c)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,u,g,f,h;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,d=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(d?b=await d({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let k=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((g=E==null?void 0:E.error)!=null?g:`Approval request failed: ${b.status}`)}k=b.body}else b instanceof ReadableStream&&(k=b);k?await this.connectStream(k,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let k=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(h=(f=this.callbacks).onError)==null||h.call(f,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,u,g,f,h,b,k,E,A,T,y,w;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(u=t.agentMetadata)==null?void 0:u.executionId,a=(g=t.toolCall)==null?void 0:g.name;if(!n||!a){(h=(f=this.callbacks).onError)==null||h.call(f,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let H=typeof((k=M[0])==null?void 0:k.question)=="string"?M[0].question:"";H&&(s={[H]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,d=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(d.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,H])=>`${M}: ${Array.isArray(H)?H.join(", "):H}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};d.forEach((M,H)=>{let I=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!I)return;let P=v[I],B=Array.isArray(P)?P.join(", "):typeof P=="string"?P:"";this.appendMessage({id:`ask-user-q-${i}-${H}`,role:"assistant",content:I,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${H}`,role:"user",content:B||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(w=(y=this.callbacks).onError)==null||w.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==vo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,d,p,u;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async g=>{var w,v,M,H,I,P,B;let f=(w=g.toolCall)==null?void 0:w.name,h=(v=g.toolCall)==null?void 0:v.id;if(!f||!h)return null;let b=`${t}:${h}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(g))return null;this.webMcpInflightKeys.add(b),o.push(b);let k=this.markWebMcpToolRunning(g),E=(H=(M=g.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?H:f;if(f===vo)return{dedupeKey:b,resumeKey:E,output:Vl(),toolMessage:g,startedAt:k,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(f,(I=g.toolCall)==null?void 0:I.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let Q=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return Q||(B=(P=this.callbacks).onError)==null||B.call(P,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(g,Es(Q?"Aborted by cancel()":Lh(O)),k),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(g,Es("Aborted by cancel()"),k),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:g,startedAt:k,completedAt:Date.now()}})),i=[];try{if(i=s.filter(h=>h!==null),i.length===0)return;let g={};for(let h of i)g[h.resumeKey]=h.output;let f=await this.client.resumeFlow(t,g,{signal:a.signal});if(!f.ok){let h=await f.json().catch(()=>null);throw new Error((c=h==null?void 0:h.error)!=null?c:`Resume failed: ${f.status}`)}for(let h of i)this.webMcpResolvedKeys.add(h.dedupeKey),this.markWebMcpToolComplete(h.toolMessage,h.output,h.startedAt,h.completedAt,((d=h.toolMessage.toolCall)==null?void 0:d.name)===vo?{suggestRepliesResolved:!0}:void 0);f.body&&await this.connectStream(f.body,{allowReentry:!0})}catch(g){if(!(g instanceof Error&&(g.name==="AbortError"||g.message.includes("aborted")||g.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,g instanceof Error?g:new Error(String(g)));else for(let h of i)this.markWebMcpToolComplete(h.toolMessage,Es("Aborted by cancel()"),h.startedAt)}finally{for(let g of o)this.webMcpInflightKeys.delete(g);for(let g of n)this.webMcpResolveControllers.delete(g);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var h,b,k,E,A,T,y,w,v,M,H,I;let r=(h=t.agentMetadata)==null?void 0:h.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(k=t.toolCall)==null?void 0:k.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let P=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(P)||this.webMcpResolvedKeys.has(P))return;this.webMcpInflightKeys.add(P);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(P)}catch(B){(y=(T=this.callbacks).onError)==null||y.call(T,B instanceof Error?B:new Error(String(B)))}finally{this.webMcpInflightKeys.delete(P)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let d=o===vo,p=(w=t.toolCall)==null?void 0:w.args,u=d?null:this.client.executeWebMcpToolCall(o,p,c),g="execute",f=s;try{let P;if(d?P=Vl():u?P=await u:P={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},f=Date.now(),c.aborted){this.markWebMcpToolComplete(t,Es("Aborted by cancel()"),s);return}let B=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;g="resume",await this.resumeWithToolOutput(r,B,P,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,P,s,f,d?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(P){let B=P instanceof Error&&(P.name==="AbortError"||P.message.includes("aborted")||P.message.includes("abort"));(g==="execute"||B||c.aborted)&&this.markWebMcpToolComplete(t,Es(B||c.aborted?"Aborted by cancel()":Lh(P)),s),B||(I=(H=this.callbacks).onError)==null||I.call(H,P instanceof Error?P:new Error(String(P)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.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(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}trackCursor(t){var n,a;let r=(n=this.agentExecution)==null?void 0:n.executionId;if(!r||!this.activeAssistantMessageId||((a=this.agentExecution)==null?void 0:a.status)!=="running")return;let o=this.resumable===null;this.resumable={executionId:r,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(o)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var r,o,n;return((r=t.agentMetadata)==null?void 0:r.awaitingLocalTool)===!0&&((o=t.agentMetadata)==null?void 0:o.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((n=t.approval)==null?void 0:n.status)==="pending"})}beginReconnect(){var t,r;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(r=(t=this.callbacks).onReconnect)==null||r.call(t,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(o=>{this.reconnecting&&this.resumable&&o.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(kh(),Eh)).then(({createReconnectController:t})=>{let r=t(this.buildReconnectHost());return this.reconnectController=r,r})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:r=>t.setStatus(r),setStreaming:r=>t.setStreaming(r),setReconnecting:r=>{t.reconnecting=r},setAbortController:r=>{t.abortController=r},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(r,o,n)=>t.connectStream(r,{assistantMessageId:o,allowReentry:!0,preserveAssistantId:!0,seedContent:n}),appendMessage:r=>t.appendMessage(r),nextSequence:()=>t.nextSequence(),emitReconnect:r=>{var o,n;return(n=(o=t.callbacks).onReconnect)==null?void 0:n.call(o,r)},buildErrorContent:r=>Yl(new Error(r),t.config.errorMessage),onError:r=>{var o,n;return(n=(o=t.callbacks).onError)==null?void 0:n.call(o,r)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let r=this.reopenTrailingAssistant();r||(r=Pn(),this.appendMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=r,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:r,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let r=this.messages[t];if(r.role==="assistant"&&!r.variant)return r.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),r.id;if(r.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var r,o;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((o=(r=this.config).onExecutionState)==null||o.call(r,null))}notifyExecutionState(t){let r=this.config.onExecutionState;if(r){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),r(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var o,n;this.executionStateTimer=null,(n=(o=this.config).onExecutionState)==null||n.call(o,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=Xl(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Fa(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Xl(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,u,g,f,h,b,k,E,A,T,y,w,v,M,H;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=n.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(g=s.agentMetadata)!=null?g:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let I=n.approval,P=r.approval;s.approval={...I,...P,executionId:P.executionId||I.executionId,toolName:P.toolName||I.toolName,description:P.description||I.description,toolType:(f=P.toolType)!=null?f:I.toolType,reason:(h=P.reason)!=null?h:I.reason,parameters:(b=P.parameters)!=null?b:I.parameters}}let i=(k=r.toolCall)==null?void 0:k.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,d=(A=r.toolCall)==null?void 0:A.id;if(i&&Ph(i)&&c&&d&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let I=`${c}:${d}`,P=this.webMcpInflightKeys.has(I),B=this.webMcpResolvedKeys.has(I),O=(y=n.toolCall)==null?void 0:y.name,Q=((w=n.agentMetadata)==null?void 0:w.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===d&&O!==void 0&&Ph(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(P||B||Q)&&(s.agentMetadata={...(H=s.agentMetadata)!=null?H:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,d;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(d=o.sequence)!=null?d:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var Zl=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var ed=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var td=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var rd=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var od=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var nd=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var ad=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var sd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var id=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var ld=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var dd=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var cd=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var pd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var ud=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var fd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var md=[["path",{d:"M20 6 9 17l-5-5"}]];var gd=[["path",{d:"m6 9 6 6 6-6"}]];var hd=[["path",{d:"m15 18-6-6 6-6"}]];var xd=[["path",{d:"m9 18 6-6-6-6"}]];var yd=[["path",{d:"m18 15-6-6-6 6"}]];var Ci=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var Si=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var bd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var vd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var wd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var Cd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var Sd=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var Ad=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var Md=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var Ai=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var Mi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var Td=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var Ed=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var kd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Ld=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var Pd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Rd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Id=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Hd=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Wd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Bd=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Dd=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var Fd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var Ti=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Nd=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Od=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var _d=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Ud=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var qd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Vd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Ei=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var zd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var $d=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var jd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Gd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Kd=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var ki=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var Xd=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Qd=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var Jd=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Yd=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var Zd=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var ec=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var tc=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var rc=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var oc=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var nc=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var ac=[["path",{d:"M5 12h14"}]];var sc=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var ic=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var lc=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var dc=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var cc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var pc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var uc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var fc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var mc=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var gc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var hc=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var xc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var yc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var bc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var vc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var wc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var Cc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var Sc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var Ac=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var Mc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Li=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var Tc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var Ec=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var kc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var Lc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Pi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var Pc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Rc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Ic=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Hc=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Wc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Bc=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Dc=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var Fc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Nc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Oc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ri=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var _c=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Uc=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var qc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Vc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var zc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var $c=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var jc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Gc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var ov={activity:Zl,"arrow-down":ed,"arrow-up":nd,"arrow-up-right":od,bot:dd,"chevron-down":gd,"chevron-up":yd,"chevron-right":xd,"chevron-left":hd,check:md,clipboard:vd,"clipboard-copy":bd,copy:Cd,file:Id,"file-code":Ld,"file-spreadsheet":Pd,"file-text":Rd,"image-plus":zd,loader:Xd,"loader-circle":ki,mic:oc,paperclip:dc,"refresh-cw":xc,search:vc,send:wc,"shield-alert":Ac,"shield-check":Mc,"shield-x":Li,square:Pc,"thumbs-down":Bc,"thumbs-up":Dc,upload:Uc,"volume-2":Vc,x:jc,user:qc,mail:Jd,phone:fc,calendar:ud,clock:wd,building:cd,"map-pin":Yd,lock:Qd,key:Gd,"credit-card":Sd,"at-sign":ad,hash:_d,globe:Od,link:Kd,"circle-check":Ci,"circle-x":Si,"triangle-alert":Ri,info:jd,ban:sd,shield:Tc,"arrow-left":td,"arrow-right":rd,"external-link":Ed,ellipsis:Mi,"ellipsis-vertical":Ai,menu:ec,house:Ei,plus:gc,minus:ac,pencil:pc,trash:Oc,"trash-2":Nc,save:bc,download:Md,share:Sc,funnel:Ti,settings:Cc,"rotate-cw":yc,maximize:Zd,minimize:nc,"shopping-cart":kc,"shopping-bag":Ec,package:lc,truck:_c,tag:Wc,gift:Nd,receipt:hc,wallet:$c,store:Ic,"dollar-sign":Ad,percent:uc,play:mc,pause:cc,"volume-x":zc,camera:fd,image:$d,film:Wd,headphones:Ud,"message-circle":tc,"message-square":rc,bell:id,heart:qd,star:Rc,eye:kd,"eye-off":Td,bookmark:ld,"calendar-days":pd,history:Vd,timer:Fc,folder:Fd,"folder-open":Dd,files:Hd,sparkles:Pi,zap:Gc,sun:Hc,moon:ic,flag:Bd,monitor:sc,smartphone:Lc},he=(e,t=24,r="currentColor",o=2)=>{let n=ov[e];return n?nv(n,t,r,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function nv(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([d,p])=>{d!=="stroke"&&c.setAttribute(d,String(p))}),n.appendChild(c)}),n}var Ii={allowedTypes:en,maxFileSize:10*1024*1024,maxFiles:4};function av(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function sv(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var da=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ii.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ii.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ii.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:Ii.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let d of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,d,"count");continue}let p=Ch(d,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,d,u);continue}try{let u=await wh(d),g=bi(d)?URL.createObjectURL(d):null,f={id:av(),file:d,previewUrl:g,contentPart:u};this.attachments.push(f),this.renderPreview(f)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=bi(t.file),o=S("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=S("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=S("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=sv(t.file.type),c=he(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let d=S("span");d.textContent=Sh(t.file.type,t.file.name),d.style.fontSize="8px",d.style.fontWeight="600",d.style.color="var(--persona-muted, #6b7280)",d.style.textTransform="uppercase",d.style.lineHeight="1",s.appendChild(d),o.appendChild(s)}let n=S("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=he("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var Rh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function ks(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];Rh(a)&&Rh(n)?r[o]=ks(a,n):r[o]=n}return r}var Gr="min(440px, calc(100vw - 24px))",Hi="440px",iv={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:Gr,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:iv,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 Ih(e,t){if(!(!e&&!t))return e?t?ks(e,t):e:t}function Wi(e){var t,r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w;return e?{...Ht,...e,theme:Ih(Ht.theme,e.theme),darkTheme:Ih(Ht.darkTheme,e.darkTheme),launcher:{...Ht.launcher,...e.launcher,dock:{...(t=Ht.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Ht.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Ht.copy,...e.copy},sendButton:{...Ht.sendButton,...e.sendButton},statusIndicator:{...Ht.statusIndicator,...e.statusIndicator},voiceRecognition:{...Ht.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,se,ge,Te,qe,j,ee,Ee,te,le;let v=(oe=Ht.features)==null?void 0:oe.artifacts,M=(se=e.features)==null?void 0:se.artifacts,H=(ge=Ht.features)==null?void 0:ge.scrollToBottom,I=(Te=e.features)==null?void 0:Te.scrollToBottom,P=(qe=Ht.features)==null?void 0:qe.scrollBehavior,B=(j=e.features)==null?void 0:j.scrollBehavior,O=(ee=Ht.features)==null?void 0:ee.streamAnimation,Q=(Ee=e.features)==null?void 0:Ee.streamAnimation,me=(te=Ht.features)==null?void 0:te.askUserQuestion,ue=(le=e.features)==null?void 0:le.askUserQuestion,Z=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Le=H===void 0&&I===void 0?void 0:{...H,...I},We=P===void 0&&B===void 0?void 0:{...P,...B},ie=O===void 0&&Q===void 0?void 0:{...O,...Q},Me=me===void 0&&ue===void 0?void 0:{...me,...ue,styles:{...me==null?void 0:me.styles,...ue==null?void 0:ue.styles}};return{...Ht.features,...e.features,...Le!==void 0?{scrollToBottom:Le}:{},...We!==void 0?{scrollBehavior:We}:{},...Z!==void 0?{artifacts:Z}:{},...ie!==void 0?{streamAnimation:ie}:{},...Me!==void 0?{askUserQuestion:Me}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Ht.suggestionChips,suggestionChipsConfig:{...Ht.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Ht.layout,...e.layout,header:{...(s=Ht.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Ht.layout)==null?void 0:c.messages,...(d=e.layout)==null?void 0:d.messages,avatar:{...(u=(p=Ht.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(f=(g=e.layout)==null?void 0:g.messages)==null?void 0:f.avatar},timestamp:{...(b=(h=Ht.layout)==null?void 0:h.messages)==null?void 0:b.timestamp,...(E=(k=e.layout)==null?void 0:k.messages)==null?void 0:E.timestamp}},slots:{...(A=Ht.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Ht.markdown,...e.markdown,options:{...(y=Ht.markdown)==null?void 0:y.options,...(w=e.markdown)==null?void 0:w.options}},messageActions:{...Ht.messageActions,...e.messageActions}}:Ht}var Kc={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"}},Xc={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"}},Qc={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:Gr,maxWidth:Hi,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 Oa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Oa(e,o):o}function Bi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Oa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function Jc(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function Hh(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=Hh(a,n):r[o]=n}return r}function lv(e,t){return t?Hh(e,t):e}function _a(e,t={}){var n,a,s,i,c,d,p,u,g,f,h,b,k;let r={palette:Kc,semantic:Xc,components:Qc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(d=e==null?void 0:e.palette)==null?void 0:d.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(g=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:g.interactive},feedback:{...r.semantic.colors.feedback,...(h=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:h.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(k=e==null?void 0:e.semantic)==null?void 0:k.typography}},components:lv(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=Jc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Di(e){var b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge,Te,qe,j,ee,Ee,te,le,ke,nt,yt,Kt,jt,ct,fe,X,st,je,Ce,ve,Ye,Vt,xe,de,Cr,Ct,xr,Co,So,Ve,W,ce,Se,Ae,Ie,et,Qe,gt,pe,N,ye,ae,mt,Ke,Lt,Et,bt,It,Qt,Ft,tr,Ao,Uo,io,lo,on,zt,co,qo,Fr,Rr,Nr,po,Mo,nn,Qr,an,St,To,Eo,Vo,uo,ht,On,ko,_n,Ir,xa,sn,zo,ln,dn,Un,qn,cn,vt,Or,_r,Sr,At,Jr,Yr,Ur,pn;let t=Bi(e),r={};for(let[we,$o]of Object.entries(t)){let Zr=we.replace(/\./g,"-");r[`--persona-${Zr}`]=$o.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(k=r["--persona-semantic-colors-secondary"])!=null?k:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(w=r["--persona-semantic-colors-text"])!=null?w:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(H=r["--persona-semantic-colors-border"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(I=r["--persona-semantic-colors-divider"])!=null?I:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(P=r["--persona-components-voice-recording-indicator"])!=null?P:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(B=r["--persona-components-voice-recording-background"])!=null?B:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(Q=r["--persona-components-voice-speaking-icon"])!=null?Q:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ue=r["--persona-components-approval-requested-border"])!=null?ue:r["--persona-border"],r["--persona-approval-text"]=(Z=r["--persona-components-approval-requested-text"])!=null?Z:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Le=r["--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)",r["--persona-approval-approve-bg"]=(We=r["--persona-components-approval-approve-background"])!=null?We:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(ie=r["--persona-components-approval-deny-background"])!=null?ie:r["--persona-container"],r["--persona-attachment-image-bg"]=(Me=r["--persona-components-attachment-image-background"])!=null?Me:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(oe=r["--persona-components-attachment-image-border"])!=null?oe:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(se=r["--persona-semantic-typography-fontFamily"])!=null?se:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(ge=r["--persona-semantic-typography-fontSize"])!=null?ge:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Te=r["--persona-semantic-typography-fontWeight"])!=null?Te:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(qe=r["--persona-semantic-typography-lineHeight"])!=null?qe:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(j=r["--persona-palette-radius-sm"])!=null?j:"0.125rem",r["--persona-radius-md"]=(ee=r["--persona-palette-radius-md"])!=null?ee:"0.375rem",r["--persona-radius-lg"]=(Ee=r["--persona-palette-radius-lg"])!=null?Ee:"0.5rem",r["--persona-radius-xl"]=(te=r["--persona-palette-radius-xl"])!=null?te:"0.75rem",r["--persona-radius-full"]=(le=r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-radius"]=(nt=(ke=r["--persona-components-launcher-borderRadius"])!=null?ke:r["--persona-palette-radius-full"])!=null?nt:"9999px",r["--persona-launcher-bg"]=(yt=r["--persona-components-launcher-background"])!=null?yt:r["--persona-primary"],r["--persona-launcher-fg"]=(Kt=r["--persona-components-launcher-foreground"])!=null?Kt:r["--persona-text-inverse"],r["--persona-launcher-border"]=(jt=r["--persona-components-launcher-border"])!=null?jt:r["--persona-border"],r["--persona-button-primary-bg"]=(ct=r["--persona-components-button-primary-background"])!=null?ct:r["--persona-primary"],r["--persona-button-primary-fg"]=(fe=r["--persona-components-button-primary-foreground"])!=null?fe:r["--persona-text-inverse"],r["--persona-button-radius"]=(st=(X=r["--persona-components-button-primary-borderRadius"])!=null?X:r["--persona-palette-radius-full"])!=null?st:"9999px",r["--persona-panel-radius"]=(Ce=(je=r["--persona-components-panel-borderRadius"])!=null?je:r["--persona-radius-xl"])!=null?Ce:"0.75rem",r["--persona-panel-border"]=(ve=r["--persona-components-panel-border"])!=null?ve:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Vt=(Ye=r["--persona-components-panel-shadow"])!=null?Ye:r["--persona-palette-shadows-xl"])!=null?Vt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(xe=r["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(Cr=(de=r["--persona-components-input-borderRadius"])!=null?de:r["--persona-radius-lg"])!=null?Cr:"0.5rem",r["--persona-message-user-radius"]=(xr=(Ct=r["--persona-components-message-user-borderRadius"])!=null?Ct:r["--persona-radius-lg"])!=null?xr:"0.5rem",r["--persona-message-assistant-radius"]=(So=(Co=r["--persona-components-message-assistant-borderRadius"])!=null?Co:r["--persona-radius-lg"])!=null?So:"0.5rem",r["--persona-header-bg"]=(Ve=r["--persona-components-header-background"])!=null?Ve:r["--persona-surface"],r["--persona-header-border"]=(W=r["--persona-components-header-border"])!=null?W:r["--persona-divider"],r["--persona-header-icon-bg"]=(ce=r["--persona-components-header-iconBackground"])!=null?ce:r["--persona-primary"],r["--persona-header-icon-fg"]=(Se=r["--persona-components-header-iconForeground"])!=null?Se:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ae=r["--persona-components-header-titleForeground"])!=null?Ae:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(Ie=r["--persona-components-header-subtitleForeground"])!=null?Ie:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(et=r["--persona-components-header-actionIconForeground"])!=null?et:r["--persona-muted"];let o=(Qe=e.components)==null?void 0:Qe.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(gt=e.components)==null?void 0:gt.introCard;r["--persona-intro-card-bg"]=(pe=r["--persona-components-introCard-background"])!=null?pe:r["--persona-surface"],r["--persona-intro-card-radius"]=(N=r["--persona-components-introCard-borderRadius"])!=null?N:"1rem",r["--persona-intro-card-padding"]=(ye=r["--persona-components-introCard-padding"])!=null?ye:"1.5rem",r["--persona-intro-card-shadow"]=(mt=(ae=n==null?void 0:n.shadow)!=null?ae:r["--persona-components-introCard-shadow"])!=null?mt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Ke=r["--persona-components-input-background"])!=null?Ke:r["--persona-surface"],r["--persona-input-placeholder"]=(Lt=r["--persona-components-input-placeholder"])!=null?Lt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(Et=r["--persona-components-message-user-background"])!=null?Et:r["--persona-accent"],r["--persona-message-user-text"]=(bt=r["--persona-components-message-user-text"])!=null?bt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(It=r["--persona-components-message-user-shadow"])!=null?It:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Qt=r["--persona-components-message-assistant-background"])!=null?Qt:r["--persona-surface"],r["--persona-message-assistant-text"]=(Ft=r["--persona-components-message-assistant-text"])!=null?Ft:r["--persona-text"],r["--persona-message-assistant-border"]=(tr=r["--persona-components-message-assistant-border"])!=null?tr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(Ao=r["--persona-components-message-assistant-shadow"])!=null?Ao:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(io=(Uo=r["--persona-components-scrollToBottom-background"])!=null?Uo:r["--persona-button-primary-bg"])!=null?io:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(on=(lo=r["--persona-components-scrollToBottom-foreground"])!=null?lo:r["--persona-button-primary-fg"])!=null?on:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(zt=r["--persona-components-scrollToBottom-border"])!=null?zt:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(co=r["--persona-components-scrollToBottom-size"])!=null?co:"40px",r["--persona-scroll-to-bottom-radius"]=(Rr=(Fr=(qo=r["--persona-components-scrollToBottom-borderRadius"])!=null?qo:r["--persona-button-radius"])!=null?Fr:r["--persona-radius-full"])!=null?Rr:"9999px",r["--persona-scroll-to-bottom-shadow"]=(po=(Nr=r["--persona-components-scrollToBottom-shadow"])!=null?Nr:r["--persona-palette-shadows-sm"])!=null?po:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(Mo=r["--persona-components-scrollToBottom-padding"])!=null?Mo:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(nn=r["--persona-components-scrollToBottom-gap"])!=null?nn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(an=(Qr=r["--persona-components-scrollToBottom-fontSize"])!=null?Qr:r["--persona-palette-typography-fontSize-sm"])!=null?an:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(St=r["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",r["--persona-tool-bubble-shadow"]=(To=r["--persona-components-toolBubble-shadow"])!=null?To:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(Eo=r["--persona-components-reasoningBubble-shadow"])!=null?Eo:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(Vo=r["--persona-components-composer-shadow"])!=null?Vo:"none",r["--persona-md-inline-code-bg"]=(uo=r["--persona-components-markdown-inlineCode-background"])!=null?uo:r["--persona-container"],r["--persona-md-inline-code-color"]=(ht=r["--persona-components-markdown-inlineCode-foreground"])!=null?ht:r["--persona-text"],r["--persona-md-link-color"]=(ko=(On=r["--persona-components-markdown-link-foreground"])!=null?On:r["--persona-accent"])!=null?ko:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let d=r["--persona-components-markdown-prose-fontFamily"];d&&d!=="inherit"&&(r["--persona-md-prose-font-family"]=d),r["--persona-md-code-block-bg"]=(_n=r["--persona-components-markdown-codeBlock-background"])!=null?_n:r["--persona-container"],r["--persona-md-code-block-border-color"]=(Ir=r["--persona-components-markdown-codeBlock-borderColor"])!=null?Ir:r["--persona-border"],r["--persona-md-code-block-text-color"]=(xa=r["--persona-components-markdown-codeBlock-textColor"])!=null?xa:"inherit",r["--persona-md-table-header-bg"]=(sn=r["--persona-components-markdown-table-headerBackground"])!=null?sn:r["--persona-container"],r["--persona-md-table-border-color"]=(zo=r["--persona-components-markdown-table-borderColor"])!=null?zo:r["--persona-border"],r["--persona-md-hr-color"]=(ln=r["--persona-components-markdown-hr-color"])!=null?ln:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(dn=r["--persona-components-markdown-blockquote-borderColor"])!=null?dn:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(Un=r["--persona-components-markdown-blockquote-background"])!=null?Un:"transparent",r["--persona-md-blockquote-text-color"]=(qn=r["--persona-components-markdown-blockquote-textColor"])!=null?qn:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(cn=r["--persona-components-collapsibleWidget-container"])!=null?cn:r["--persona-surface"],r["--cw-surface"]=(vt=r["--persona-components-collapsibleWidget-surface"])!=null?vt:r["--persona-surface"],r["--cw-border"]=(Or=r["--persona-components-collapsibleWidget-border"])!=null?Or:r["--persona-border"],r["--persona-message-border"]=(_r=r["--persona-components-message-border"])!=null?_r:r["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(r["--persona-icon-btn-bg"]=u.background),u.border&&(r["--persona-icon-btn-border"]=u.border),u.color&&(r["--persona-icon-btn-color"]=u.color),u.padding&&(r["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(r["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(r["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(r["--persona-icon-btn-active-border"]=u.activeBorder));let g=p==null?void 0:p.labelButton;g&&(g.background&&(r["--persona-label-btn-bg"]=g.background),g.border&&(r["--persona-label-btn-border"]=g.border),g.color&&(r["--persona-label-btn-color"]=g.color),g.padding&&(r["--persona-label-btn-padding"]=g.padding),g.borderRadius&&(r["--persona-label-btn-radius"]=g.borderRadius),g.hoverBackground&&(r["--persona-label-btn-hover-bg"]=g.hoverBackground),g.fontSize&&(r["--persona-label-btn-font-size"]=g.fontSize),g.gap&&(r["--persona-label-btn-gap"]=g.gap));let f=p==null?void 0:p.toggleGroup;f&&(f.gap&&(r["--persona-toggle-group-gap"]=f.gap),f.borderRadius&&(r["--persona-toggle-group-radius"]=f.borderRadius));let h=p==null?void 0:p.artifact;if(h!=null&&h.toolbar){let we=h.toolbar;we.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=we.iconHoverColor),we.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=we.iconHoverBackground),we.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=we.iconPadding),we.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=we.iconBorderRadius),we.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=we.iconBorder),we.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=we.toggleGroupGap),we.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=we.toggleBorderRadius),we.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=we.copyBackground),we.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=we.copyBorder),we.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=we.copyColor),we.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=we.copyBorderRadius),we.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=we.copyPadding),we.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=we.copyMenuBackground,r["--persona-dropdown-bg"]=(Sr=r["--persona-dropdown-bg"])!=null?Sr:we.copyMenuBackground),we.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=we.copyMenuBorder,r["--persona-dropdown-border"]=(At=r["--persona-dropdown-border"])!=null?At:we.copyMenuBorder),we.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=we.copyMenuShadow,r["--persona-dropdown-shadow"]=(Jr=r["--persona-dropdown-shadow"])!=null?Jr:we.copyMenuShadow),we.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=we.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(Yr=r["--persona-dropdown-radius"])!=null?Yr:we.copyMenuBorderRadius),we.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=we.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(Ur=r["--persona-dropdown-item-hover-bg"])!=null?Ur:we.copyMenuItemHoverBackground),we.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=we.iconBackground),we.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=we.toolbarBorder)}if(h!=null&&h.tab){let we=h.tab;we.background&&(r["--persona-artifact-tab-bg"]=we.background),we.activeBackground&&(r["--persona-artifact-tab-active-bg"]=we.activeBackground),we.activeBorder&&(r["--persona-artifact-tab-active-border"]=we.activeBorder),we.borderRadius&&(r["--persona-artifact-tab-radius"]=we.borderRadius),we.textColor&&(r["--persona-artifact-tab-color"]=we.textColor),we.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=we.hoverBackground),we.listBackground&&(r["--persona-artifact-tab-list-bg"]=we.listBackground),we.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=we.listBorderColor),we.listPadding&&(r["--persona-artifact-tab-list-padding"]=we.listPadding)}if(h!=null&&h.pane){let we=h.pane;if(we.toolbarBackground){let $o=(pn=Oa(e,we.toolbarBackground))!=null?pn:we.toolbarBackground;r["--persona-artifact-toolbar-bg"]=$o}}return r}var Wh={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var dv={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"}}},Bh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ls=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},cv=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":Ls()},Yc=e=>cv(e),pv=e=>_a(e),uv=e=>{var r;let t=_a(void 0,{validate:!1});return _a({...e,palette:{...t.palette,colors:{...dv.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ua=e=>{let t=Yc(e),r=Bh(e==null?void 0:e.theme),o=Bh(e==null?void 0:e.darkTheme);return t==="dark"?uv(ks(r!=null?r:{},o!=null?o:{})):pv(r)},fv=e=>Di(e),Hn=(e,t)=>{let r=Ua(t),o=fv(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Fi=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(Ls())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(Ls());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var Dh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:g=>g.getAttribute("im-preserve")==="true",shouldReAppend:g=>g.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(g,f,h={}){g=p(g);let b=u(f),k=d(g,b,h),E=n(k,()=>i(k,g,b,A=>A.morphStyle==="innerHTML"?(a(A,g,b),Array.from(g.childNodes)):o(A,g,b)));return k.pantry.remove(),E}function o(g,f,h){let b=u(f);return a(g,b,h,f,f.nextSibling),Array.from(b.childNodes)}function n(g,f){var T;if(!g.config.restoreFocus)return f();let h=document.activeElement;if(!(h instanceof HTMLInputElement||h instanceof HTMLTextAreaElement))return f();let{id:b,selectionStart:k,selectionEnd:E}=h,A=f();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(h=g.target.querySelector(`[id="${b}"]`),h==null||h.focus()),h&&!h.selectionEnd&&E&&h.setSelectionRange(k,E),A}let a=(function(){function g(y,w,v,M=null,H=null){w instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(w=w.content,v=v.content),M||(M=w.firstChild);for(let I of v.childNodes){if(M&&M!=H){let B=h(y,I,M,H);if(B){B!==M&&k(y,M,B),s(B,I,y),M=B.nextSibling;continue}}if(I instanceof Element){let B=I.getAttribute("id");if(y.persistentIds.has(B)){let O=E(w,B,M,y);s(O,I,y),M=O.nextSibling;continue}}let P=f(w,I,M,y);P&&(M=P.nextSibling)}for(;M&&M!=H;){let I=M;M=M.nextSibling,b(y,I)}}function f(y,w,v,M){if(M.callbacks.beforeNodeAdded(w)===!1)return null;if(M.idMap.has(w)){let H=document.createElement(w.tagName);return y.insertBefore(H,v),s(H,w,M),M.callbacks.afterNodeAdded(H),H}else{let H=document.importNode(w,!0);return y.insertBefore(H,v),M.callbacks.afterNodeAdded(H),H}}let h=(function(){function y(M,H,I,P){let B=null,O=H.nextSibling,Q=0,me=I;for(;me&&me!=P;){if(v(me,H)){if(w(M,me,H))return me;B===null&&(M.idMap.has(me)||(B=me))}if(B===null&&O&&v(me,O)&&(Q++,O=O.nextSibling,Q>=2&&(B=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return B||null}function w(M,H,I){let P=M.idMap.get(H),B=M.idMap.get(I);if(!B||!P)return!1;for(let O of P)if(B.has(O))return!0;return!1}function v(M,H){var B,O,Q;let I=M,P=H;return I.nodeType===P.nodeType&&I.tagName===P.tagName&&(!((B=I.getAttribute)!=null&&B.call(I,"id"))||((O=I.getAttribute)==null?void 0:O.call(I,"id"))===((Q=P.getAttribute)==null?void 0:Q.call(P,"id")))}return y})();function b(y,w){var v;if(y.idMap.has(w))T(y.pantry,w,null);else{if(y.callbacks.beforeNodeRemoved(w)===!1)return;(v=w.parentNode)==null||v.removeChild(w),y.callbacks.afterNodeRemoved(w)}}function k(y,w,v){let M=w;for(;M&&M!==v;){let H=M;M=M.nextSibling,b(y,H)}return M}function E(y,w,v,M){var I,P;let H=((P=(I=M.target).getAttribute)==null?void 0:P.call(I,"id"))===w&&M.target||M.target.querySelector(`[id="${w}"]`)||M.pantry.querySelector(`[id="${w}"]`);return A(H,M),T(y,H,v),H}function A(y,w){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=w.idMap.get(y);M&&(M.delete(v),M.size||w.idMap.delete(y))}}function T(y,w,v){if(y.moveBefore)try{y.moveBefore(w,v)}catch{y.insertBefore(w,v)}else y.insertBefore(w,v)}return g})(),s=(function(){function g(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(f(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function f(A,T,y){let w=T.nodeType;if(w===1){let v=A,M=T,H=v.attributes,I=M.attributes;for(let P of I)k(P.name,v,"update",y)||v.getAttribute(P.name)!==P.value&&v.setAttribute(P.name,P.value);for(let P=H.length-1;0<=P;P--){let B=H[P];if(B&&!M.hasAttribute(B.name)){if(k(B.name,v,"remove",y))continue;v.removeAttribute(B.name)}}E(v,y)||h(v,M,y)}(w===8||w===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function h(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let w=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==w&&(k("value",A,"update",y)||(A.setAttribute("value",w),A.value=w)):k("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let w=T.value,v=A.value;if(k("value",A,"update",y))return;w!==v&&(A.value=w),A.firstChild&&A.firstChild.nodeValue!==w&&(A.firstChild.nodeValue=w)}}function b(A,T,y,w){let v=T[y],M=A[y];if(v!==M){let H=k(y,A,"update",w);H||(A[y]=T[y]),v?H||A.setAttribute(y,""):k(y,A,"remove",w)||A.removeAttribute(y)}}function k(A,T,y,w){return A==="value"&&w.ignoreActiveValue&&T===document.activeElement?!0:w.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return g})();function i(g,f,h,b){if(g.head.block){let k=f.querySelector("head"),E=h.querySelector("head");if(k&&E){let A=c(k,E,g);return Promise.all(A).then(()=>{let T=Object.assign(g,{head:{block:!1,ignore:!0}});return b(T)})}}return b(g)}function c(g,f,h){let b=[],k=[],E=[],A=[],T=new Map;for(let w of f.children)T.set(w.outerHTML,w);for(let w of g.children){let v=T.has(w.outerHTML),M=h.head.shouldReAppend(w),H=h.head.shouldPreserve(w);v||H?M?k.push(w):(T.delete(w.outerHTML),E.push(w)):h.head.style==="append"?M&&(k.push(w),A.push(w)):h.head.shouldRemove(w)!==!1&&k.push(w)}A.push(...T.values());let y=[];for(let w of A){let v=document.createRange().createContextualFragment(w.outerHTML).firstChild;if(h.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,H=new Promise(function(I){M=I});v.addEventListener("load",function(){M()}),y.push(H)}g.appendChild(v),h.callbacks.afterNodeAdded(v),b.push(v)}}for(let w of k)h.callbacks.beforeNodeRemoved(w)!==!1&&(g.removeChild(w),h.callbacks.afterNodeRemoved(w));return h.head.afterHeadMorphed(g,{added:b,kept:E,removed:k}),y}let d=(function(){function g(y,w,v){let{persistentIds:M,idMap:H}=A(y,w),I=f(v),P=I.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(P))throw`Do not understand how to morph style ${P}`;return{target:y,newContent:w,config:I,morphStyle:P,ignoreActive:I.ignoreActive,ignoreActiveValue:I.ignoreActiveValue,restoreFocus:I.restoreFocus,idMap:H,persistentIds:M,pantry:h(),activeElementAndParents:b(y),callbacks:I.callbacks,head:I.head}}function f(y){let w=Object.assign({},t);return Object.assign(w,y),w.callbacks=Object.assign({},t.callbacks,y.callbacks),w.head=Object.assign({},t.head,y.head),w}function h(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let w=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(w.push(v),v!==y);)v=v.parentElement;return w}function k(y){var v;let w=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&w.push(y),w}function E(y,w,v,M){for(let H of M){let I=H.getAttribute("id");if(w.has(I)){let P=H;for(;P;){let B=y.get(P);if(B==null&&(B=new Set,y.set(P,B)),B.add(I),P===v)break;P=P.parentElement}}}}function A(y,w){let v=k(y),M=k(w),H=T(v,M),I=new Map;E(I,H,y,v);let P=w.__idiomorphRoot||w;return E(I,H,P,M),{persistentIds:H,idMap:I}}function T(y,w){let v=new Set,M=new Map;for(let{id:I,tagName:P}of y)M.has(I)?v.add(I):M.set(I,P);let H=new Set;for(let{id:I,tagName:P}of w)H.has(I)?v.add(I):M.get(I)===P&&H.add(I);for(let I of v)H.delete(I);return H}return g})(),{normalizeElement:p,normalizeParent:u}=(function(){let g=new WeakSet;function f(E){return E instanceof Document?E.documentElement:E}function h(E){if(E==null)return document.createElement("div");if(typeof E=="string")return h(k(E));if(g.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let w=y.querySelectorAll(A);for(let v=0;v<w.length;v++)T.push(w[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function k(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return g.add(y),y;{let w=y.firstChild;return w&&g.add(w),w}}else{let w=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return g.add(w),w}}return{normalizeElement:f,normalizeParent:h}})();return{morph:r,defaults:t}})();var Ni=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;Dh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-tool-elapsed"))return a instanceof HTMLElement&&a.getAttribute("data-tool-elapsed")===n.getAttribute("data-tool-elapsed")?!1:void 0;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",d=(i=a.textContent)!=null?i:"";if(c!==d)return}return!1}}}}})};var Fh=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Oi={index:-1,draft:""};function Nh(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Oi}}}function Oh(e,t){var r,o,n,a,s,i,c,d,p,u,g,f,h,b,k,E,A,T,y,w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me,oe,se,ge;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(d=e.llmContent)==null?void 0:d.length)!=null?p:0,(g=(u=e.approval)==null?void 0:u.status)!=null?g:"",(h=(f=e.toolCall)==null?void 0:f.status)!=null?h:"",(k=(b=e.toolCall)==null?void 0:b.name)!=null?k:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(w=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:w[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((H=e.toolCall)==null?void 0:H.args)=="string"?e.toolCall.args.length:(I=e.toolCall)!=null&&I.args?JSON.stringify(e.toolCall.args).length:0,(O=(B=(P=e.reasoning)==null?void 0:P.chunks)==null?void 0:B.length)!=null?O:0,(Z=(ue=(me=(Q=e.reasoning)==null?void 0:Q.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ue.length)!=null?Z:0,(Me=(ie=(We=(Le=e.reasoning)==null?void 0:Le.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?Me:"",(se=(oe=e.contentParts)==null?void 0:oe.length)!=null?se:0,(ge=e.stopReason)!=null?ge:"",t].join("\0")}function _h(){return new Map}function Uh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function qh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function Vh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function _i(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Oo(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wn(e,t){return Oo(e)-e.scrollTop<=t}function Ui(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:d=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!d||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function qi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function zh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function $h(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function jh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var or={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},wr=1e5,Bn=wr+1;var Ps={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},mv=["pre","code","a","script","style"],Vi=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:Ps.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:Ps.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:Ps.speed,duration:(n=e==null?void 0:e.duration)!=null?n:Ps.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:Ps.buffer}},Kh=[{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"}],Rs=new Map;for(let e of Kh)Rs.set(e.name,e);var ca=e=>{Rs.set(e.name,e)},tp=e=>{Kh.some(t=>t.name===e)||Rs.delete(e)},rp=()=>Array.from(Rs.keys()),qa=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Rs.get(e))!=null?o:null},zi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
20
20
  `);return a<0?"":e.slice(0,a)}return e},gv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},hv=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},Zc=/\s/,xv=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},yv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(Zc.test(a[i])){let d=i;for(;d<a.length&&Zc.test(a[d]);)d+=1;s.appendChild(o.createTextNode(a.slice(i,d))),i=d}else{let d=o.createElement("span");d.className="persona-stream-word-group";let p=i;for(;p<a.length&&!Zc.test(a[p]);)d.appendChild(gv(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(d),i=p}n.replaceChild(s,e)},bv=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let d of i)d&&(/^\s+$/.test(d)?s.appendChild(o.createTextNode(d)):(s.appendChild(hv(o,d,t,r.value)),r.value+=1));n.replaceChild(s,e)},Is=(e,t,r,o)=>{var u,g;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((u=o==null?void 0:o.skipTags)!=null?u:mv).map(f=>f.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)xv(c,a)||i.push(c),c=s.nextNode();let d={value:(g=o==null?void 0:o.startIndex)!=null?g:0},p=t==="char"?yv:bv;for(let f of i)p(f,r,d);return n.innerHTML},$i=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Hs=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},Gh=new WeakMap,vv=(e,t)=>{var a;if(!e.styles)return;let r=Gh.get(t);if(r||(r=new Set,Gh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},ep=new WeakMap,wv=(e,t)=>{if(!e.onAttach)return;let r=ep.get(t);if(r||(r=new Map,ep.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Xh=e=>{let t=ep.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},ji=(e,t)=>{vv(e,t),wv(e,t)};function op(e,t=wr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ws=0,Dn=null;function np(e=document){var r;if(Ws++,Ws===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;Dn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ws=Math.max(0,Ws-1),Ws===0&&Dn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=Dn.originalOverflow,n.style.position=Dn.originalPosition,n.style.top=Dn.originalTop,n.style.width=Dn.originalWidth,a.scrollTo(0,Dn.scrollY),Dn=null}}}var Bs={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Fn=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Kr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Bs.side,width:(n=t==null?void 0:t.width)!=null?n:Bs.width,animate:(a=t==null?void 0:t.animate)!=null?a:Bs.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Bs.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Bs.maxHeight}};var wo={"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 Cv="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Gi=(e,t={})=>{var k,E,A,T,y,w;let{showClose:r=!0,wrapperClassName:o=Cv,buttonSize:n,iconSize:a="28px"}=t,s=(k=e==null?void 0:e.launcher)!=null?k:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=S("div",o),d=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,u=(y=s.closeButtonIconName)!=null?y:"x",g=(w=s.closeButtonIconText)!=null?w:"\xD7",f=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),h=Tt("button",{className:gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!f&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":d},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Pr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:f?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=he(u,a,"currentColor",1);if(b?(b.style.display="block",h.appendChild(b)):h.textContent=g,c.appendChild(h),p&&d){let v=null,M=()=>{if(v)return;let I=h.ownerDocument,P=I.body;if(!P)return;v=No(I,"div","persona-clear-chat-tooltip"),v.textContent=d;let B=No(I,"div");B.className="persona-clear-chat-tooltip-arrow",v.appendChild(B);let O=h.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(Bn),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",P.appendChild(v)},H=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",H),h.addEventListener("focus",M),h.addEventListener("blur",H),c._cleanupTooltip=()=>{H(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",H),h.removeEventListener("focus",M),h.removeEventListener("blur",H)}}return{button:h,wrapper:c}},Sv="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Ki=(e,t={})=>{var v,M,H,I,P,B,O,Q,me,ue,Z,Le,We;let{wrapperClassName:r=Sv,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(H=o!=null?o:s.size)!=null?H:"32px",c=(I=s.iconName)!=null?I:"refresh-cw",d=(P=s.iconColor)!=null?P:"",p=(B=s.backgroundColor)!=null?B:"",u=(O=s.borderWidth)!=null?O:"",g=(Q=s.borderColor)!=null?Q:"",f=(me=s.borderRadius)!=null?me:"",h=(ue=s.paddingX)!=null?ue:"",b=(Z=s.paddingY)!=null?Z:"",k=(Le=s.tooltipText)!=null?Le:"Clear chat",E=(We=s.showTooltip)!=null?We:!0,A=S("div",r),T=!!(u||g),y=Tt("button",{className:gs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!f&&"persona-rounded-full"),attrs:{type:"button","aria-label":k},style:{height:i,width:i,color:d||Pr.actionIconColor,backgroundColor:p||void 0,border:T?`${u||"0px"} solid ${g||"transparent"}`:void 0,borderRadius:f||void 0,paddingLeft:h||void 0,paddingRight:h||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),w=he(c,n,"currentColor",1);if(w&&(w.style.display="block",y.appendChild(w)),A.appendChild(y),E&&k){let ie=null,Me=()=>{if(ie)return;let se=y.ownerDocument,ge=se.body;if(!ge)return;ie=No(se,"div","persona-clear-chat-tooltip"),ie.textContent=k;let Te=No(se,"div");Te.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Te);let qe=y.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(Bn),ie.style.left=`${qe.left+qe.width/2}px`,ie.style.top=`${qe.top-8}px`,ie.style.transform="translate(-50%, -100%)",ge.appendChild(ie)},oe=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};A.addEventListener("mouseenter",Me),A.addEventListener("mouseleave",oe),y.addEventListener("focus",Me),y.addEventListener("blur",oe),A._cleanupTooltip=()=>{oe(),A.removeEventListener("mouseenter",Me),A.removeEventListener("mouseleave",oe),y.removeEventListener("focus",Me),y.removeEventListener("blur",oe)}}return{button:y,wrapper:A}};var Pr={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))"},tn=e=>{var w,v,M,H,I,P,B,O,Q,me,ue,Z,Le,We,ie,Me;let{config:t,showClose:r=!0}=e,o=Tt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),n=(w=t==null?void 0:t.launcher)!=null?w:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(H=n.headerIconHidden)!=null?H:!1,c=n.headerIconName,d=Tt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let oe=parseFloat(a)||24,se=he(c,oe*.6,"currentColor",1);se?d.replaceChildren(se):d.textContent=(P=(I=t==null?void 0:t.launcher)==null?void 0:I.agentIconText)!=null?P:"\u{1F4AC}"}else if((B=t==null?void 0:t.launcher)!=null&&B.iconUrl){let oe=S("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=a,oe.style.width=a,d.replaceChildren(oe)}else d.textContent=(Q=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?Q:"\u{1F4AC}";let p=S("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Tt("span",{className:"persona-text-base persona-font-semibold",text:(ue=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ue:"Chat Assistant",style:{color:Pr.titleColor}}),g=Tt("span",{className:"persona-text-xs",text:(Le=(Z=t==null?void 0:t.launcher)==null?void 0:Z.subtitle)!=null?Le:"Here to help you get answers fast",style:{color:Pr.subtitleColor}});p.append(u,g),i?o.append(p):o.append(d,p);let f=(We=n.clearChat)!=null?We:{},h=(ie=f.enabled)!=null?ie:!0,b=(Me=f.placement)!=null?Me:"inline",k=null,E=null;if(h){let se=Ki(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});k=se.button,E=se.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":h&&b==="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:T,wrapper:y}=Gi(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:d,headerTitle:u,headerSubtitle:g,closeButton:T,closeButtonWrapper:y,clearChatButton:k,clearChatButtonWrapper:E}},pa=(e,t,r)=>{var s,i,c,d;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(d=(c=o.clearChat)==null?void 0:c.placement)!=null?d:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Nn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=S("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(Bn)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let f of t){if(f.dividerBefore){let k=document.createElement("hr");s.appendChild(k)}let h=document.createElement("button");if(h.type="button",h.setAttribute("role","menuitem"),h.setAttribute("data-dropdown-item-id",f.id),f.destructive&&h.setAttribute("data-destructive",""),f.icon){let k=he(f.icon,16,"currentColor",1.5);k&&h.appendChild(k)}let b=document.createElement("span");b.textContent=f.label,h.appendChild(b),h.addEventListener("click",k=>{k.stopPropagation(),p(),r(f.id)}),s.appendChild(h)}let i=null;function c(){if(!a)return;let f=o.getBoundingClientRect();s.style.top=`${f.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-f.right}px`,s.style.left="auto"):(s.style.left=`${f.left}px`,s.style.right="auto")}function d(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let f=h=>{!s.contains(h.target)&&!o.contains(h.target)&&p()};document.addEventListener("click",f,!0),i=()=>document.removeEventListener("click",f,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function u(){s.classList.contains("persona-hidden")?d():p()}function g(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:d,hide:p,toggle:u,destroy:g}}function pr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=S("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let d=he(t,o!=null?o:16,"currentColor",n!=null?n:2);if(d&&c.appendChild(d),s&&c.addEventListener("click",s),i)for(let[p,u]of Object.entries(i))c.setAttribute(p,u);return c}function Ds(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,d="persona-label-btn";o!=="default"&&(d+=" persona-label-btn--"+o),d+=" persona-label-btn--"+n,s&&(d+=" "+s);let p=S("button",d);if(p.type="button",p.setAttribute("aria-label",r),t){let g=he(t,a!=null?a:14,"currentColor",2);g&&p.appendChild(g)}let u=S("span");if(u.textContent=r,p.appendChild(u),i&&p.addEventListener("click",i),c)for(let[g,f]of Object.entries(c))p.setAttribute(g,f);return p}function Qh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=S("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let u;p.icon?u=pr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(u=S("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),u.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:u}),a.appendChild(u)}function d(p){s=p,c()}return{element:a,setSelected:d}}function Xi(e){var f,h;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,d=S("div","persona-combo-btn"+(i?" "+i:""));d.style.position="relative",d.style.display="inline-flex",d.style.alignItems="center",d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0"),d.setAttribute("aria-haspopup","true"),d.setAttribute("aria-expanded","false"),d.setAttribute("aria-label",t);let p=S("span","persona-combo-btn-label");p.textContent=t,d.appendChild(p);let u=he(r,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",d.appendChild(u)),c&&(d.style.borderRadius=(f=c.borderRadius)!=null?f:"10px",d.style.padding=(h=c.padding)!=null?h:"6px 4px 6px 12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.addEventListener("mouseenter",()=>{var b,k;d.style.backgroundColor=(b=c.background)!=null?b:"",d.style.borderColor=(k=c.border)!=null?k:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}));let g=Nn({items:o,onSelect:b=>{d.setAttribute("aria-expanded","false"),n(b)},anchor:d,position:a,portal:s});return s||d.appendChild(g.element),d.addEventListener("click",b=>{b.stopPropagation();let k=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",k?"false":"true"),g.toggle()}),d.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),d.click())}),{element:d,setLabel:b=>{p.textContent=b,d.setAttribute("aria-label",b)},open:()=>{d.setAttribute("aria-expanded","true"),g.show()},close:()=>{d.setAttribute("aria-expanded","false"),g.hide()},toggle:()=>{let b=!g.element.classList.contains("persona-hidden");d.setAttribute("aria-expanded",b?"false":"true"),g.toggle()},destroy:()=>{g.destroy(),d.remove()}}}var ap=e=>{var o;let t=tn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function Av(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=S("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",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=he(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=S("div","persona-relative");c.appendChild(i);let d=Nn({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(d.element),i.addEventListener("click",p=>{p.stopPropagation(),d.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var sp=e=>{var A,T,y,w,v,M,H,I,P;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=S("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 c=n==null?void 0:n.titleMenu,d,p;if(c)d=Xi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,d.style.color=Pr.titleColor,p=(y=d.querySelector(".persona-combo-btn-label"))!=null?y:d;else{if(d=S("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=S("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Pr.titleColor,p.textContent=(w=s.title)!=null?w:"Chat Assistant",d.appendChild(p),Av(d,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){d.style.cursor="pointer",d.setAttribute("role","button"),d.setAttribute("tabindex","0");let O=n.onTitleClick;d.addEventListener("click",Q=>{Q.target.closest("button")||O()}),d.addEventListener("keydown",Q=>{(Q.key==="Enter"||Q.key===" ")&&(Q.preventDefault(),O())})}let B=n==null?void 0:n.titleRowHover;B&&(d.style.borderRadius=(M=B.borderRadius)!=null?M:"10px",d.style.padding=(H=B.padding)!=null?H:"6px 4px 6px 12px",d.style.margin="-6px 0 -6px -12px",d.style.border="1px solid transparent",d.style.transition="background-color 0.15s ease, border-color 0.15s ease",d.style.width="fit-content",d.style.flex="none",d.addEventListener("mouseenter",()=>{var O,Q;d.style.backgroundColor=(O=B.background)!=null?O:"",d.style.borderColor=(Q=B.border)!=null?Q:""}),d.addEventListener("mouseleave",()=>{d.style.backgroundColor="",d.style.borderColor="transparent"}))}i.appendChild(d);let u=(I=s.closeButtonSize)!=null?I:"32px",g=S("div",""),f=S("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");f.style.height=u,f.style.width=u,f.type="button",f.setAttribute("aria-label","Close chat"),f.style.display=r?"":"none",f.style.color=s.closeButtonColor||Pr.actionIconColor;let h=(P=s.closeButtonIconName)!=null?P:"x",b=he(h,"28px","currentColor",1);b?f.appendChild(b):f.textContent="\xD7",o&&f.addEventListener("click",o),g.appendChild(f),i.appendChild(g);let k=S("div");k.style.display="none";let E=S("span");return E.style.display="none",{header:i,iconHolder:k,headerTitle:p,headerSubtitle:E,closeButton:f,closeButtonWrapper:g,clearChatButton:null,clearChatButtonWrapper:null}},Qi={default:ap,minimal:sp},ip=e=>{var t;return(t=Qi[e])!=null?t:Qi.default},Va=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let d=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=S("div");p.style.display="none";let u=S("span"),g=S("span"),f=S("button");f.style.display="none";let h=S("div");return h.style.display="none",{header:d,iconHolder:p,headerTitle:u,headerSubtitle:g,closeButton:f,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=ip(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var Ji=e=>{var s,i;let t=S("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},Yi=e=>{var w,v,M,H,I,P,B,O,Q,me,ue,Z;let t=(w=e==null?void 0:e.sendButton)!=null?w:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(H=t.stopIconName)!=null?H:"square",s=(I=t.tooltipText)!=null?I:"Send message",i=(P=t.stopTooltipText)!=null?P:"Stop generating",c=(O=(B=e==null?void 0:e.copy)==null?void 0:B.sendButtonLabel)!=null?O:"Send",d=(me=(Q=e==null?void 0:e.copy)==null?void 0:Q.stopButtonLabel)!=null?me:"Stop",p=(ue=t.showTooltip)!=null?ue:!1,u=(Z=t.size)!=null?Z:"40px",g=t.backgroundColor,f=t.textColor,h=S("div","persona-send-button-wrapper"),b=Tt("button",{className:gs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!g&&"persona-bg-persona-primary",!r&&!f&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?u:void 0,height:r?u:void 0,minWidth:r?u:void 0,minHeight:r?u:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?f||"var(--persona-button-primary-fg, #ffffff)":f||void 0,backgroundColor:r&&g||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),k=null,E=null;if(r){let Le=parseFloat(u)||24,We=(f==null?void 0:f.trim())||"currentColor";n?(k=he(n,Le,We,2),k?b.appendChild(k):b.textContent=o):b.textContent=o,E=he(a,Le,We,2)}else b.textContent=c;let A=null;p&&s&&(A=S("div","persona-send-button-tooltip"),A.textContent=s,h.appendChild(A)),b.setAttribute("aria-label",s),h.appendChild(b);let T="send";return{button:b,wrapper:h,setMode:Le=>{if(Le===T)return;T=Le;let We=Le==="stop"?i:s;if(b.setAttribute("aria-label",We),A&&(A.textContent=We),r){if(k&&E){let ie=Le==="stop"?E:k;b.replaceChildren(ie)}}else b.textContent=Le==="stop"?d:c}}},Zi=e=>{var A,T,y,w,v,M,H,I,P,B,O,Q;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(w=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?w:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,d=parseFloat(c)||24,p=(I=t.backgroundColor)!=null?I:(H=e==null?void 0:e.sendButton)==null?void 0:H.backgroundColor,u=(B=t.iconColor)!=null?B:(P=e==null?void 0:e.sendButton)==null?void 0:P.textColor,g=S("div","persona-send-button-wrapper"),f=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=he(i,d,u||"currentColor",1.5);b?f.appendChild(b):f.textContent="\u{1F3A4}",g.appendChild(f);let k=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((Q=t.showTooltip)!=null?Q:!1)&&k){let me=S("div","persona-send-button-tooltip");me.textContent=k,g.appendChild(me)}return{button:f,wrapper:g}},el=e=>{var h,b,k,E,A,T,y,w;let t=(h=e==null?void 0:e.attachments)!=null?h:{};if(t.enabled!==!0)return null;let r=(k=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?k:"40px",o=S("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=S("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:en).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),d=S("div","persona-send-button-wrapper"),p=Tt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=he(a,c,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),d.appendChild(p);let g=(w=t.buttonTooltipText)!=null?w:"Attach file",f=S("div","persona-send-button-tooltip");return f.textContent=g,d.appendChild(f),{button:p,wrapper:d,input:n,previewsContainer:o}},tl=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=S("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let d=S("a");d.href=t.idleLink,d.target="_blank",d.rel="noopener noreferrer",d.textContent=a,d.style.color="inherit",d.style.textDecoration="none",o.appendChild(d)}else o.textContent=a;return o},rl=()=>Tt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var za=e=>{var h,b,k,E,A,T;let{config:t}=e,r=Tt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),o=rl(),n=Tt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:a,attachAutoResize:s}=Ji(t);s();let i=Yi(t),c=Zi(t),d=el(t),p=tl(t);d&&(d.previewsContainer.style.gap="8px",n.append(d.previewsContainer,d.input)),n.append(a);let u=Tt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),g=S("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),f=S("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return d&&g.append(d.wrapper),c&&f.append(c.wrapper),f.append(i.wrapper),u.append(g,f),n.append(u),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(k=d==null?void 0:d.button)!=null?k:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(T=d==null?void 0:d.previewsContainer)!=null?T:null,actionsRow:u,leftActions:g,rightActions:f,setSendButtonMode:i.setMode}};var Jh=()=>{let e=Tt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=S("span","persona-pill-peek__icon"),r=he("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=S("span","persona-pill-peek__text"),n=S("span","persona-pill-peek__caret"),a=he("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Yh=e=>{var h,b,k,E,A,T;let{config:t}=e,r=Tt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=rl();o.style.display="none";let n=tl(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=Ji(t);a.style.maxHeight="100px",s();let i=Yi(t),c=Zi(t),d=el(t);d&&d.previewsContainer.classList.add("persona-pill-composer__previews");let p=Tt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),u=S("div","persona-widget-composer__left-actions persona-pill-composer__left");d&&u.append(d.wrapper);let g=S("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&g.append(c.wrapper),g.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(d==null?void 0:d.button)&&y.target!==(d==null?void 0:d.wrapper)&&a.focus()}),d&&p.append(d.input),p.append(u,a,g),d&&r.append(d.previewsContainer),r.append(p,o,n);let f=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(h=c==null?void 0:c.button)!=null?h:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(k=d==null?void 0:d.button)!=null?k:null,attachmentButtonWrapper:(E=d==null?void 0:d.wrapper)!=null?E:null,attachmentInput:(A=d==null?void 0:d.input)!=null?A:null,attachmentPreviewsContainer:(T=d==null?void 0:d.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:g,setSendButtonMode:i.setMode}};var Zh=e=>{var p,u,g,f,h,b,k,E,A,T,y,w,v,M,H,I,P;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,r=nr(e);if(Fn(e)){let B=(f=(g=e==null?void 0:e.launcher)==null?void 0:g.composerBar)!=null?f:{},O=S("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(h=B.expandedSize)!=null?h:"anchored",O.style.zIndex=String((k=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?k:wr);let Q=S("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Q.style.width="100%",O.appendChild(Q);let me=S("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=B.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:wr),{wrapper:O,panel:Q,pillRoot:me}}if(r){let B=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=S("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return B.appendChild(O),{wrapper:B,panel:O}}if(!t){let B=S("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=S("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Q=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?w:"100%";return B.style.width=Q,O.style.width="100%",B.appendChild(O),{wrapper:B,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&wo[n.position]?wo[n.position]:wo["bottom-right"],s=S("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((H=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?H:wr);let i=S("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(P=(I=e==null?void 0:e.launcher)==null?void 0:I.width)!=null?P:e==null?void 0:e.launcherWidth,d=c!=null?c:Gr;return i.style.width=d,i.style.maxWidth=d,s.appendChild(i),{wrapper:s,panel:i}},Mv=(e,t)=>{var y,w,v,M,H,I,P,B,O;let r=S("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Gi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(w=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:w.enabled)!=null?v:!0,s=null,i=null;if(a){let Q=Ki(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=Q.button,i=Q.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=Tt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),d=Tt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});d.style.setProperty("scrollbar-gutter","stable");let p=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(H=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?H:"Hello \u{1F44B}"}),u=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(I=e==null?void 0:e.copy)==null?void 0:I.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),g=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,u),f=S("div","persona-flex persona-flex-col persona-gap-3"),h=(B=e==null?void 0:e.layout)==null?void 0:B.contentMaxWidth;h&&(f.style.maxWidth=h,f.style.marginLeft="auto",f.style.marginRight="auto",f.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(g.style.display="none",d.classList.remove("persona-gap-6"),d.classList.add("persona-gap-3")),d.append(g,f);let k=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=Yh({config:e}),{root:A,textNode:T}=Jh();return r.append(c,n,d,k),i&&r.appendChild(i),{container:r,body:d,messagesWrapper:f,composerOverlay:k,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:u,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:S("span"),headerTitle:S("span"),headerSubtitle:S("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},ex=(e,t=!0)=>{var k,E,A,T,y,w,v,M,H;if(Fn(e))return Mv(e,t);let r=Tt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),o=(k=e==null?void 0:e.layout)==null?void 0:k.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Va(e,o,{showClose:t}):tn({config:e,showClose:t}),s=Tt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});s.style.setProperty("scrollbar-gutter","stable");let i=Tt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=Tt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(w=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?w:"Ask anything about your account or products."}),d=Tt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=S("div","persona-flex persona-flex-col persona-gap-3"),u=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(d.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(d,p);let f=za({config:e}),h=((H=e==null?void 0:e.layout)==null?void 0:H.showFooter)!==!1;n?pa(r,a,e):(a.header.style.display="none",pa(r,a,e)),r.append(s);let b=Tt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return h||(f.footer.style.display="none"),r.append(f.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,suggestions:f.suggestions,textarea:f.textarea,sendButton:f.sendButton,sendButtonWrapper:f.sendButtonWrapper,micButton:f.micButton,micButtonWrapper:f.micButtonWrapper,composerForm:f.composerForm,statusText:f.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:f.footer,attachmentButton:f.attachmentButton,attachmentButtonWrapper:f.attachmentButtonWrapper,attachmentInput:f.attachmentInput,attachmentPreviewsContainer:f.attachmentPreviewsContainer,actionsRow:f.actionsRow,leftActions:f.leftActions,rightActions:f.rightActions,setSendButtonMode:f.setSendButtonMode}};var lp=(e,t)=>{let r=S("button");r.type="button",r.innerHTML=`
21
21
  <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>
22
22
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />