@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.
- package/dist/animations/glyph-cycle.d.cts +1 -1
- package/dist/animations/glyph-cycle.d.ts +1 -1
- package/dist/animations/{types-8RICZWQe.d.cts → types-CSmiKRVa.d.cts} +5 -0
- package/dist/animations/{types-8RICZWQe.d.ts → types-CSmiKRVa.d.ts} +5 -0
- package/dist/animations/wipe.d.cts +1 -1
- package/dist/animations/wipe.d.ts +1 -1
- package/dist/codegen.cjs +4 -4
- package/dist/codegen.js +4 -4
- package/dist/index.cjs +2 -2
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +10 -1
- package/dist/index.d.ts +10 -1
- package/dist/index.global.js +2 -2
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +5 -0
- package/dist/smart-dom-reader.d.ts +5 -0
- package/dist/theme-editor-preview.cjs +2 -2
- package/dist/theme-editor-preview.d.cts +5 -0
- package/dist/theme-editor-preview.d.ts +5 -0
- package/dist/theme-editor-preview.js +2 -2
- package/dist/theme-editor.d.cts +5 -0
- package/dist/theme-editor.d.ts +5 -0
- package/package.json +4 -2
- package/src/client.ts +7 -2
- package/src/generated/runtype-openapi-contract.ts +10 -1
- package/src/utils/morph.test.ts +47 -0
- package/src/utils/morph.ts +18 -0
|
@@ -8,14 +8,14 @@ ${e}`:"")+(n.description?`
|
|
|
8
8
|
${n.description}`:"");return window.confirm(t)},Mf=n=>{if(n==null)return"";try{let e=JSON.stringify(n,null,2);return e.length>500?e.slice(0,500)+"\u2026":e}catch{return String(n)}},kf=n=>{if(n===void 0)return"{}";try{let e=JSON.stringify(n);return e===void 0?"{}":e}catch{return"{}"}},Lf=n=>{if(n===void 0)return"";try{return JSON.stringify(n)}catch{return String(n)}};var Pf="agent_",If="flow_";function Mu(n){return n.startsWith(Pf)?{kind:"agentId",agentId:n}:n.startsWith(If)?{kind:"flowId",flowId:n}:null}function ku(n,e){let t=n.trim();if(!t)throw new Error("[Persona] `target` is empty.");let r=t.indexOf(":");if(r>0){let a=t.slice(0,r),i=t.slice(r+1);if(a==="runtype"){let c=Mu(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=e==null?void 0:e[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=Mu(t);if(o)return o;let s=e==null?void 0:e.default;if(s)return{kind:"payload",payload:s(t).payload};throw new Error(`[Persona] target "${t}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${t}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var fo=require("partial-json");var v=(n,e)=>{let t=document.createElement(n);return e&&(t.className=e),t},Ir=(n,e,t)=>{let r=n.createElement(e);return t&&(r.className=t),r};var Mt=(n,e={},...t)=>{let r=document.createElement(n);if(e.className&&(r.className=e.className),e.text!==void 0&&(r.textContent=e.text),e.attrs)for(let[s,a]of Object.entries(e.attrs))r.setAttribute(s,a);if(e.style){let s=r.style,a=e.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=t.filter(s=>s!=null);return o.length>0&&r.append(...o),r},zs=(...n)=>n.filter(Boolean).join(" ");var Li="ask_user_question",js=8,ds="data-persona-ask-sheet-for",Rf="Other",Wf="Other\u2026",Pu="Type your own answer here",Iu="Send",Hf="Next",Bf="Back",Df="Submit all",Nf="Skip",Ff=3,Pi="data-ask-current-index",Ii="data-ask-question-count",Ru="data-ask-answers",Ri="data-ask-grouped",Wu="data-ask-layout",Of=n=>n.layout==="pills"?"pills":"rows",_f=n=>n.getAttribute(Wu)==="pills"?"pills":"rows",Lu=!1,Hu=n=>n.replace(/["\\]/g,"\\$&"),_o=n=>n.variant==="tool"&&!!n.toolCall&&n.toolCall.name===Li,Wi=n=>{var e,t;return(t=(e=n==null?void 0:n.features)==null?void 0:e.askUserQuestion)!=null?t:{}},ps=n=>{let e=n.toolCall;if(!e)return{payload:null,complete:!1};let t=e.status==="complete";if(e.args&&typeof e.args=="object")return{payload:e.args,complete:t};let r=e.chunks;if(!r||r.length===0)return{payload:null,complete:t};try{let o=r.join(""),s=(0,fo.parse)(o,fo.STR|fo.OBJ|fo.ARR);if(s&&typeof s=="object")return{payload:s,complete:t}}catch{}return{payload:null,complete:t}},Vs=n=>{let e=Array.isArray(n==null?void 0:n.questions)?n.questions:[];return e.length>js&&!Lu&&(Lu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${e.length} questions; truncating to ${js}.`)),e.slice(0,js)},$f=n=>{var e;return(e=Vs(n)[0])!=null?e:null},Uf=(n,e)=>{var t;return(t=Vs(n)[e])!=null?t:null},qf=(n,e)=>{let t=e.styles;t&&(t.sheetBackground&&n.style.setProperty("--persona-ask-sheet-bg",t.sheetBackground),t.sheetBorder&&n.style.setProperty("--persona-ask-sheet-border",t.sheetBorder),t.sheetShadow&&n.style.setProperty("--persona-ask-sheet-shadow",t.sheetShadow),t.pillBackground&&n.style.setProperty("--persona-ask-pill-bg",t.pillBackground),t.pillBackgroundSelected&&n.style.setProperty("--persona-ask-pill-bg-selected",t.pillBackgroundSelected),t.pillTextColor&&n.style.setProperty("--persona-ask-pill-fg",t.pillTextColor),t.pillTextColorSelected&&n.style.setProperty("--persona-ask-pill-fg-selected",t.pillTextColorSelected),t.pillBorderRadius&&n.style.setProperty("--persona-ask-pill-radius",t.pillBorderRadius),t.customInputBackground&&n.style.setProperty("--persona-ask-input-bg",t.customInputBackground))},Bu=(n,e,t)=>{if(n!=="rows")return null;let r=v("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),e){let o=v("span","persona-ask-row-check");r.appendChild(o)}else{let o=v("span","persona-ask-row-badge");o.textContent=String(t+1),r.appendChild(o)}return r},zf=(n,e,t,r)=>{let s=v("button",t==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(e)),s.setAttribute("data-option-label",n.label),t==="rows"){let a=v("span","persona-ask-row-content"),i=v("span","persona-ask-row-label");if(i.textContent=n.label,a.appendChild(i),n.description){let c=v("span","persona-ask-row-description");c.textContent=n.description,a.appendChild(c)}s.appendChild(a);let d=Bu(t,r,e);d&&s.appendChild(d)}else s.textContent=n.label,n.description&&(s.title=n.description);return s},jf=n=>{let t=v("span",n==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return t.setAttribute("aria-hidden","true"),t},Vf=(n,e,t,r)=>{var p,g,h;let s=v("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(n!=null&&n.multiSelect),d=(Array.isArray(n==null?void 0:n.options)?n.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(d.length===0&&!t){for(let m=0;m<Ff;m++)s.appendChild(jf(r));return s}if(d.forEach((m,y)=>{s.appendChild(zf(m,y,r,a))}),(n==null?void 0:n.allowFreeText)!==!1){let m=r==="rows"?Rf:Wf;if(r==="rows"){let y=v("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");y.setAttribute("data-ask-user-action","focus-free-text"),y.setAttribute("data-option-index",String(d.length)),y.setAttribute("data-ask-other-row","true");let w=v("span","persona-ask-row-content"),E=document.createElement("input");E.type="text",E.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",E.placeholder=(p=e.freeTextPlaceholder)!=null?p:Pu,E.setAttribute("data-ask-free-text-input","true"),E.setAttribute("aria-label",(g=e.freeTextLabel)!=null?g:m),w.appendChild(E),y.appendChild(w);let B=Bu(r,a,d.length);B&&y.appendChild(B),s.appendChild(y)}else{let y=v("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");y.type="button",y.setAttribute("data-ask-user-action","open-free-text"),y.textContent=(h=e.freeTextLabel)!=null?h:m,s.appendChild(y)}}return s},Du=(n,e)=>{var s,a;let r=v("div",e==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=n.freeTextPlaceholder)!=null?s:Pu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),e!=="rows"){let i=v("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=n.submitLabel)!=null?a:Iu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Kf=n=>{var r;let e=v("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");e.setAttribute("data-ask-multi-actions","true");let t=v("button","persona-ask-multi-submit persona-pointer-events-auto");return t.type="button",t.textContent=(r=n.submitLabel)!=null?r:Iu,t.setAttribute("data-ask-user-action","submit-multi"),t.disabled=!0,e.appendChild(t),e},Gf=(n,e,t)=>{var c,p,g,h;let r=v("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=v("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=t.backLabel)!=null?c:Bf,o.setAttribute("data-ask-user-action","back"),o.disabled=n===0,r.appendChild(o);let s=v("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=v("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=t.skipLabel)!=null?p:Nf,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=v("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=n===e-1;return i.textContent=d?(g=t.submitAllLabel)!=null?g:Df:(h=t.nextLabel)!=null?h:Hf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},$o=n=>{let e=n.getAttribute(Ru);if(!e)return{};try{let t=JSON.parse(e);return t&&typeof t=="object"?t:{}}catch{return{}}},Nu=(n,e)=>{n.setAttribute(Ru,JSON.stringify(e))},tr=n=>{var t;let e=Number((t=n.getAttribute(Pi))!=null?t:"0");return Number.isFinite(e)?Math.max(0,Math.floor(e)):0},Qf=(n,e)=>{n.setAttribute(Pi,String(Math.max(0,Math.floor(e))))},us=n=>{var t;let e=Number((t=n.getAttribute(Ii))!=null?t:"1");return Number.isFinite(e)?Math.max(1,Math.floor(e)):1},ho=n=>n.getAttribute(Ri)==="true",Xf=(n,e)=>{var o;let t=(o=n.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!t||typeof t!="object")return{};let r={};return e.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(t,i)){let d=t[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Jf=(n,e)=>{var r;let t=(r=n.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof t!="number"||!Number.isFinite(t)?0:Math.max(0,Math.min(e-1,Math.floor(t)))},ka=(n,e)=>{let{payload:t}=ps(e),r=Vs(t),o=$o(n),s={},a=new Set;return r.forEach((i,d)=>{let c=typeof(i==null?void 0:i.question)=="string"?i.question:"";c&&(a.has(c)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${c}"; later answer wins.`),a.add(c),Object.prototype.hasOwnProperty.call(o,d)&&(s[c]=o[d]))}),s},Fu=n=>{let e=$o(n),t=tr(n),r=e[t],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=n.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var g;let c=(g=d.getAttribute("data-option-label"))!=null?g:"",p=o.has(c);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var c;return(c=d.getAttribute("data-option-label"))!=null?c:""})),i=n.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Ou=n=>{if(!ho(n))return;let e=$o(n),t=tr(n),r=e[t],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=n.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=n.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Hi=(n,e,t)=>{let r=Wi(t),o=_f(n),{payload:s,complete:a}=ps(e),i=ho(n),d=tr(n),c=us(n),p=i?Uf(s,d):$f(s),g=!!(p!=null&&p.multiSelect),h=n.querySelector('[data-ask-step-inline="true"]');h&&(h.textContent=i?`${d+1}/${c}`:"");let m=n.querySelector('[data-ask-stepper="true"]');m&&m.remove();let y=n.querySelector('[data-ask-question="true"]');if(y){let T=typeof(p==null?void 0:p.question)=="string"?p.question:"";y.textContent=T,y.classList.toggle("persona-ask-question-skeleton",!T&&!a)}let w=n.querySelector('[data-ask-pill-list="true"]');if(w){let T=Vf(p,r,a,o);w.replaceWith(T)}if(o!=="rows"){let T=n.querySelector('[data-ask-free-text-row="true"]');T&&T.replaceWith(Du(r,o))}let E=n.querySelector('[data-ask-multi-actions="true"]');!i&&g&&!E?n.appendChild(Kf(r)):(!g||i)&&E&&E.remove(),n.setAttribute("data-multi-select",g?"true":"false");let B=n.querySelector('[data-ask-nav-row="true"]');if(i){let T=Gf(d,c,r);B?B.replaceWith(T):n.appendChild(T)}else B&&B.remove();Fu(n),Ou(n)},Yf=(n,e,t)=>{let r=Wi(e),o=Of(r),s=n.toolCall.id,a=Vs(t),i=Math.max(1,a.length),d=i>1,c=Xf(n,a),p=d?Jf(n,i):0,g=v("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));g.setAttribute(ds,s),g.setAttribute("data-tool-call-id",s),g.setAttribute("data-message-id",n.id),g.setAttribute(Ii,String(i)),g.setAttribute(Pi,String(p)),g.setAttribute(Ri,d?"true":"false"),g.setAttribute(Wu,o),Nu(g,c),g.setAttribute("role","group"),g.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&g.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),qf(g,r);let h=v("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=v("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",h.appendChild(m);let y=v("span","persona-ask-sheet-step-inline");y.setAttribute("data-ask-step-inline","true"),y.textContent="",h.appendChild(y),g.appendChild(h);let E=v("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return E.setAttribute("data-ask-pill-list","true"),E.setAttribute("role","group"),g.appendChild(E),o!=="rows"&&g.appendChild(Du(r,o)),Hi(g,n,e),requestAnimationFrame(()=>{requestAnimationFrame(()=>g.classList.remove("persona-ask-sheet-enter"))}),g},Zf=(n,e,t)=>{let{payload:r}=ps(e),o=Math.max(1,Vs(r).length);o>us(n)&&(n.setAttribute(Ii,String(o)),o>1&&!ho(n)&&n.setAttribute(Ri,"true")),Hi(n,e,t)};var La=(n,e,t)=>{if(!t||!_o(n)||Wi(e).enabled===!1)return;let o=n.toolCall.id;t.querySelectorAll(`[${ds}]`).forEach(c=>{c.getAttribute(ds)!==o&&c.remove()});let a=t.querySelector(`[${ds}="${Hu(o)}"]`);if(a){Zf(a,n,e);return}let{payload:i}=ps(n),d=Yf(n,e,i);t.appendChild(d)},ms=(n,e)=>{if(!n)return;let t=e?`[${ds}="${Hu(e)}"]`:`[${ds}]`;n.querySelectorAll(t).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Bi=n=>Array.from(n.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(e=>e.getAttribute("data-option-label")).filter(e=>typeof e=="string"&&e.length>0),yo=(n,e)=>{let t=$o(n),r=tr(n);typeof e=="string"&&e.length===0||Array.isArray(e)&&e.length===0?delete t[r]:t[r]=e,Nu(n,t),Fu(n),Ou(n)},Pa=(n,e,t,r)=>{let o=us(n),s=Math.max(0,Math.min(o-1,r));Qf(n,s),Hi(n,e,t)};var zr="suggest_replies";var eh={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},_u={name:zr,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown: do not add further commentary after calling this tool; end your turn.`,parametersSchema:eh,origin:"sdk",annotations:{readOnlyHint:!0}},Di=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),Ni=n=>{var e;return n.variant==="tool"&&((e=n.toolCall)==null?void 0:e.name)===zr},th=n=>{let e=n;if(typeof e=="string")try{e=JSON.parse(e)}catch{return[]}let t=e==null?void 0:e.suggestions;if(!Array.isArray(t))return[];let r=t.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},$u=n=>{var e;for(let t=n.length-1;t>=0;t--){let r=n[t];if(r.role==="user")return null;if(!Ni(r))continue;let o=th((e=r.toolCall)==null?void 0:e.args);return o.length>0?o:null}return null},Uu=n=>{var t;let e=(t=n==null?void 0:n.features)==null?void 0:t.suggestReplies;return(e==null?void 0:e.expose)===!0&&e.enabled!==!1};var nh={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:js,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},rh={name:Li,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:nh,origin:"sdk",annotations:{readOnlyHint:!0}},Fi=n=>{var r;let e=[],t=(r=n==null?void 0:n.features)==null?void 0:r.askUserQuestion;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1&&e.push(rh),Uu(n)&&e.push(_u),e};var gs=require("partial-json"),qu=n=>n.replace(/\\n/g,`
|
|
9
9
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),bo=n=>{if(n===null)return"null";if(n===void 0)return"";if(typeof n=="string")return n;if(typeof n=="number"||typeof n=="boolean")return String(n);try{return JSON.stringify(n,null,2)}catch{return String(n)}},oh=n=>{var a,i;let e=(a=n.completedAt)!=null?a:Date.now(),t=(i=n.startedAt)!=null?i:e,o=(n.durationMs!==void 0?n.durationMs:Math.max(0,e-t))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},zu=n=>n.status==="complete"?oh(n):n.status==="pending"?"Waiting":"",sh=n=>{var o,s,a;let t=(typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((o=n.completedAt)!=null?o:Date.now())-((a=(s=n.startedAt)!=null?s:n.completedAt)!=null?a:Date.now())))/1e3;return t<.1?"Used tool for <0.1 seconds":`Used tool for ${t>=10?Math.round(t).toString():t.toFixed(1).replace(/\.0$/,"")} seconds`};var ju=n=>n.status==="complete"?sh(n):"Using tool...",Ia=n=>{let e=n/1e3;return e<.1?"<0.1s":e>=10?`${Math.round(e)}s`:`${e.toFixed(1).replace(/\.0$/,"")}s`},Gs=n=>{var t,r,o;let e=typeof n.duration=="number"?n.duration:typeof n.durationMs=="number"?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ia(e)},Ra=n=>{var t,r,o;let e=n.durationMs!==void 0?n.durationMs:Math.max(0,((t=n.completedAt)!=null?t:Date.now())-((o=(r=n.startedAt)!=null?r:n.completedAt)!=null?o:Date.now()));return Ia(e)},Oi=(n,e,t)=>{var s;if(!e)return t;let r=((s=n.name)==null?void 0:s.trim())||"tool",o=Gs(n);return e.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},Wa=(n,e)=>{let t=n.replace(/\{toolName\}/g,e),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(t))!==null;)a.index>s&&Ks(r,t.slice(s,a.index),[]),a[1]!==void 0?Ks(r,a[1],["bold"]):a[2]!==void 0?Ks(r,a[2],["italic"]):a[3]!==void 0&&Ks(r,a[3],["dim"]),s=a.index+a[0].length;return s<t.length&&Ks(r,t.slice(s),[]),r},Ks=(n,e,t)=>{let r=e.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&n.push({text:r[o],styles:t}),o<r.length-1&&n.push({text:"{duration}",styles:t,isDuration:!0})},ah=()=>{let n=null,e=0,t=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
10
10
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
11
|
-
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Vu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Ku=()=>{var e;let n=ah();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Gu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,gs.parse)(t,gs.STR|gs.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?qu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=qu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Qu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Xu="4.6.0";var Xs=Xu;var lh="https://api.runtype.com/v1/dispatch",Ha="https://api.runtype.com";function ch(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _i=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function dh(n){switch(n){case"json":return Gu;case"regex-json":return Ku;case"xml":return Qu;default:return Vu}}var Ju=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ph(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Ju(t);if(!Ju(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Qs(n);return Qs(e)!==null&&a===null?e:n}var Js=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:lh,this.headers={"Content-Type":"application/json","X-Persona-Version":Xs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:dh(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Ma(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=ku(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(_i).map(M=>{var P,C,k;return{id:M.id,role:M.role,content:(k=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?k:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},h=c.clientTools,m=!!(h&&h.length>0),y=m?Tu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&w&&this.lastSentClientToolsFingerprint===y,B=!1,T=null,I;for(let M=0;;M++){let C={...g,...m&&(B||!E)&&h?{clientTools:h}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),I=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&m){let k=await I.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}T=k!=null?k:{error:"Chat request failed"}}break}if(!I.ok){let M=T!=null?T:await I.json().catch(()=>({error:"Chat request failed"}));if(I.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw t({type:"error",error:P}),P}if(!I.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(I.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ha}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(_i).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let g=new Date(c.createdAt).getTime(),h=new Date(p.createdAt).getTime();return g-h}).map(c=>{var p,g,h;return{role:c.role,content:(h=(g=(p=c.contentParts)!=null?p:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Fi(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let g=await p({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(_i).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return p-g}).map(d=>{var c,p,g;return{role:d.role,content:(g=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Fi(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=g,o(g),g},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var fn,hr,yr,qe;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,g=L=>{let ge=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Me=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,Le=L.tools?L.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...L,reasoning:ge,toolCall:Me,tools:Le}},h=L=>{if(L.role!=="assistant"||L.variant)return!0;let ge=Array.isArray(L.contentParts)&&L.contentParts.length>0,Me=typeof L.rawContent=="string"&&L.rawContent.trim()!=="";return typeof L.content=="string"&&L.content.trim()!==""||ge||Me||!!L.stopReason},m=L=>{h(L)&&t({type:"message",message:g(L)})},y=null,w=null,E={current:null},B={current:null},T=null,I="",M=new Map,P=new Map,C=new Map,k=new Map,q=new Map,_={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},O=L=>{if(L==null)return null;try{return String(L)}catch{return null}},F=L=>{var ge,Me,Le,He,nt;return O((nt=(He=(Le=(Me=(ge=L.stepId)!=null?ge:L.step_id)!=null?Me:L.step)!=null?Le:L.parentId)!=null?He:L.flowStepId)!=null?nt:L.flow_step_id)},Z=L=>{var ge,Me,Le,He,nt,Xe,yt;return O((yt=(Xe=(nt=(He=(Le=(Me=(ge=L.callId)!=null?ge:L.call_id)!=null?Me:L.requestId)!=null?Le:L.request_id)!=null?He:L.toolCallId)!=null?nt:L.tool_call_id)!=null?Xe:L.stepId)!=null?yt:L.step_id)},ke=r,pe=!1,ee=()=>{if(y)return y;let L,ge="",Me=T;return!pe&&ke?(L=ke,pe=!0,ge=o!=null?o:""):ke&&Me?L=`${ke}_${Me}`:L=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:L,role:"assistant",content:ge,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(y),y},Pe=(L,ge)=>{_.lastId=ge,L&&_.byStep.set(L,ge)},Ie=(L,ge)=>{var nt;let Me=(nt=L.reasoningId)!=null?nt:L.id,Le=F(L);if(Me){let Xe=String(Me);return Pe(Le,Xe),Xe}if(Le){let Xe=_.byStep.get(Le);if(Xe)return _.lastId=Xe,Xe}if(_.lastId&&!ge)return _.lastId;if(!ge)return null;let He=`reason-${p()}`;return Pe(Le,He),He},ie=L=>{let ge=k.get(L);if(ge)return ge;let Me={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:L,status:"streaming",chunks:[]}};return k.set(L,Me),m(Me),Me},he=(L,ge)=>{R.lastId=ge,L&&R.byCall.set(L,ge)},re=new Set,oe=new Map,de=new Set,Ae=new Map,$e=L=>{if(!L)return!1;let ge=L.replace(/_+/g,"_").replace(/^_|_$/g,"");return ge==="emit_artifact_markdown"||ge==="emit_artifact_component"},K=(L,ge)=>{var nt;let Me=(nt=L.toolId)!=null?nt:L.id,Le=Z(L);if(Me){let Xe=String(Me);return he(Le,Xe),Xe}if(Le){let Xe=R.byCall.get(Le);if(Xe)return R.lastId=Xe,Xe}if(R.lastId&&!ge)return R.lastId;if(!ge)return null;let He=`tool-${p()}`;return he(Le,He),He},J=L=>{let ge=q.get(L);if(ge)return ge;let Me={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:L,status:"pending"}};return q.set(L,Me),m(Me),Me},Se=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ge=Number(L);if(!Number.isNaN(ge)&&Number.isFinite(ge))return ge;let Me=Date.parse(L);if(!Number.isNaN(Me))return Me}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},le=new Map,Te=new Map,Ye=new Map,tt=(L,ge,Me)=>{var yt;let Le=Ye.get(L);Le||(Le=[],Ye.set(L,Le));let He=0,nt=Le.length;for(;He<nt;){let fe=He+nt>>>1;Le[fe].seq<ge?He=fe+1:nt=fe}((yt=Le[He])==null?void 0:yt.seq)===ge?Le[He]={seq:ge,text:Me}:Le.splice(He,0,{seq:ge,text:Me});let Xe="";for(let fe=0;fe<Le.length;fe++)Xe+=Le[fe].text;return Xe},Wt=(L,ge)=>{let Me=Y(ge),Le=Te.get(L.id),He=ph(Le,Me);L.rawContent=He;let nt=le.get(L.id),Xe=ce=>{var Ge;let ft=(Ge=L.content)!=null?Ge:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(L.content=ce)},yt=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(L.id),Te.delete(L.id),L.streaming=!1,m(L)};if(!nt){Xe(Me),yt();return}let fe=Qs(He);if(fe!==null&&fe.trim()!==""){Xe(fe),yt();return}let D=ce=>{var Pt;let ft=typeof ce=="string"?ce:(Pt=ce==null?void 0:ce.text)!=null?Pt:null;if(ft!==null&&ft.trim()!=="")return ft;let Ge=nt.getExtractedText();return Ge!==null&&Ge.trim()!==""?Ge:Me},ve;try{ve=nt.processChunk(He)}catch{Xe(Me),yt();return}if(ve instanceof Promise){ve.then(ce=>{Xe(D(ce)),yt()}).catch(()=>{Xe(Me),yt()});return}Xe(D(ve)),yt()},ht=null,ot=(L,ge,Me,Le)=>{var fe;L.rawContent=ge,le.has(L.id)||le.set(L.id,this.createStreamParser());let He=le.get(L.id),nt=ge.trim().startsWith("{")||ge.trim().startsWith("[");if(nt&&Te.set(L.id,ge),He.__isPlainTextParser===!0){L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L);return}let yt=He.processChunk(ge);if(yt instanceof Promise)yt.then(D=>{var ce;let ve=typeof D=="string"?D:(ce=D==null?void 0:D.text)!=null?ce:null;ve!==null&&ve.trim()!==""?(L.content=ve,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}).catch(()=>{L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L)});else{let D=typeof yt=="string"?yt:(fe=yt==null?void 0:yt.text)!=null?fe:null;D!==null&&D.trim()!==""?(L.content=D,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}},me=(L,ge)=>{var fe,D;let Me=ge!=null?ge:L.content;if(Me==null||Me===""){L.streaming=!1,m(L);return}let Le=Te.get(L.id),He=Le!=null?Le:Y(Me);L.rawContent=He;let nt=le.get(L.id),Xe=null,yt=!1;if(nt&&(Xe=nt.getExtractedText(),Xe===null&&(Xe=Qs(He)),Xe===null)){let ve=nt.processChunk(He);ve instanceof Promise?(yt=!0,ve.then(ce=>{var Ge;let ft=typeof ce=="string"?ce:(Ge=ce==null?void 0:ce.text)!=null?Ge:null;ft!==null&&(L.content=ft,L.streaming=!1,le.delete(L.id),Te.delete(L.id),m(L))}).catch(()=>{})):Xe=typeof ve=="string"?ve:(fe=ve==null?void 0:ve.text)!=null?fe:null}if(!yt){Xe!==null&&Xe.trim()!==""?L.content=Xe:Te.has(L.id)||(L.content=Y(Me));let ve=le.get(L.id);if(ve){let ce=(D=ve.close)==null?void 0:D.call(ve);ce instanceof Promise&&ce.catch(()=>{}),le.delete(L.id)}Te.delete(L.id),L.streaming=!1,m(L)}},X=(L,ge,Me)=>{let Le=P.get(L);if(Le)return Le;let He={id:`nested-${ge}-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:L,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ge}};return P.set(L,He),m(He),He},lt=[],Ve,Ee=new Map,xe=0,Ze="agent",jt=!1,be=null,ue=null,xn=new Map,At=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo,Ce,Nr,Qn,_t,Xn,Fr,ks,Xo,Ls,Eo,Ar,to,ct,rn,on,Sr,Ps,Or,Mo,Tr,$,Jo,lr,Er,_r,Mr,cr,Yo,ha,hn,An,dr,Sn,ko,pr,yn,kr,Zo,Lo,es,no;for(let ro=0;ro<lt.length;ro++){let st=lt[ro].payloadType,x=lt[ro].payload;if(!jt&&Ze!=="flow"&&typeof x.stepType=="string"&&(Ze="flow"),st==="reasoning_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j),X(V,j,"reasoning");continue}let Q=(L=Ie(x,!0))!=null?L:`reason-${p()}`,G=ie(Q);G.reasoning=(ge=G.reasoning)!=null?ge:{id:Q,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:Se((Me=x.startedAt)!=null?Me:x.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),G.streaming=!0,G.reasoning.status="streaming",m(G)}else if(st==="reasoning_delta"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let Ne=P.get(V),rt=(Xe=(nt=(He=x.reasoningText)!=null?He:x.text)!=null?nt:x.delta)!=null?Xe:"";rt&&x.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),m(Ne));continue}let j=(fe=(yt=Ie(x,!1))!=null?yt:Ie(x,!0))!=null?fe:`reason-${p()}`,Q=ie(j);Q.reasoning=(D=Q.reasoning)!=null?D:{id:j,status:"streaming",chunks:[]},Q.reasoning.startedAt=(ce=Q.reasoning.startedAt)!=null?ce:Se((ve=x.startedAt)!=null?ve:x.timestamp);let G=(Pt=(Ge=(ft=x.reasoningText)!=null?ft:x.text)!=null?Ge:x.delta)!=null?Pt:"";if(G&&x.hidden!==!0){let Ne=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Ne!==void 0){let rt=tt(j,Ne,String(G));Q.reasoning.chunks=[rt]}else Q.reasoning.chunks.push(String(G))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=Se((kt=x.completedAt)!=null?kt:x.timestamp);let Ne=(wt=Q.reasoning.startedAt)!=null?wt:Date.now();Q.reasoning.durationMs=Math.max(0,((Ht=Q.reasoning.completedAt)!=null?Ht:Date.now())-Ne)}Q.streaming=Q.reasoning.status!=="complete",m(Q)}else if(st==="reasoning_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let rt=P.get(V);if(rt.reasoning){let dt=typeof x.text=="string"?x.text:"";dt&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(dt),rt.reasoning.status="complete",rt.streaming=!1,m(rt)}M.delete(V),P.delete(V);continue}let j=(Ot=(Xt=Ie(x,!1))!=null?Xt:Ie(x,!0))!=null?Ot:`reason-${p()}`,Q=typeof x.text=="string"?x.text:"";!k.get(j)&&(Q||x.scope==="loop")&&ie(j);let G=k.get(j);if(G!=null&&G.reasoning){(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),Q&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(Q),G.reasoning.status="complete",G.reasoning.completedAt=Se((en=x.completedAt)!=null?en:x.timestamp);let rt=(br=G.reasoning.startedAt)!=null?br:Date.now();G.reasoning.durationMs=Math.max(0,((Wr=G.reasoning.completedAt)!=null?Wr:Date.now())-rt),G.streaming=!1,m(G)}let Ne=F(x);Ne&&_.byStep.delete(Ne)}else if(st==="tool_start"){y&&(y.streaming=!1,m(y),y=null),typeof x.iteration=="number"&&(xe=x.iteration);let V=(or=(rr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?rr:K(x,!0))!=null?or:`tool-${p()}`,j=(Kr=x.toolName)!=null?Kr:x.name;if($e(j)){re.add(V);continue}he(Z(x),V);let Q=J(V),G=(Vt=Q.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=j!=null?j:G.name,G.status="running",x.parameters!==void 0?G.args=x.parameters:x.args!==void 0&&(G.args=x.args),G.startedAt=(Hr=G.startedAt)!=null?Hr:Se((sr=x.startedAt)!=null?sr:x.timestamp),G.completedAt=void 0,G.durationMs=void 0,Q.toolCall=G,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(Q)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(x,!1))!=null?Bn:K(x,!0))!=null?Ln:`tool-${p()}`;if(re.has(V))continue;let j=J(V),Q=(Dn=j.toolCall)!=null?Dn:{id:V,status:"running"};Q.startedAt=(vr=Q.startedAt)!=null?vr:Se((ar=x.startedAt)!=null?ar:x.timestamp);let G=(Qr=(Vn=(Gr=x.text)!=null?Gr:x.delta)!=null?Vn:x.message)!=null?Qr:"";G&&(Q.chunks=(St=Q.chunks)!=null?St:[],Q.chunks.push(String(G))),Q.status="running",j.toolCall=Q,j.streaming=!0;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Br=j.agentMetadata)!=null?Br:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:x.executionId,iteration:(xr=Ne==null?void 0:Ne.iteration)!=null?xr:x.iteration}),m(j)}else if(st==="tool_complete"){let V=(bt=(ir=K(x,!1))!=null?ir:K(x,!0))!=null?bt:`tool-${p()}`;if(re.has(V)){re.delete(V);continue}let j=J(V),Q=(Co=j.toolCall)!=null?Co:{id:V,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=Se((Cr=x.completedAt)!=null?Cr:x.timestamp);let G=(Ao=x.duration)!=null?Ao:x.executionTime;if(typeof G=="number")Q.durationMs=G;else{let dt=(Pn=Q.startedAt)!=null?Pn:Date.now();Q.durationMs=Math.max(0,((Qo=Q.completedAt)!=null?Qo:Date.now())-dt)}j.toolCall=Q,j.streaming=!1;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Jr=j.agentMetadata)!=null?Jr:{executionId:(Xr=Ne==null?void 0:Ne.executionId)!=null?Xr:x.executionId,iteration:(Dr=Ne==null?void 0:Ne.iteration)!=null?Dr:x.iteration}),m(j);let rt=Z(x);rt&&R.byCall.delete(rt)}else if(st==="await"&&x.toolName){let V=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,j=(Yr=V!=null?V:x.toolId)!=null?Yr:`local-${p()}`,Q=J(j),G=x.toolName,Ne=x.origin==="webmcp"&&!cs(G)?`webmcp:${G}`:G,rt=cs(Ne),dt=(So=Q.toolCall)!=null?So:{id:j,status:"pending"};dt.name=Ne,dt.args=x.parameters,dt.status=rt?"running":"complete",dt.chunks=(To=dt.chunks)!=null?To:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:Se((xt=(Zr=x.startedAt)!=null?Zr:x.timestamp)!=null?xt:x.awaitedAt),rt?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(Fn=dt.completedAt)!=null?Fn:dt.startedAt,Q.toolCall=dt,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tt=x.executionId)!=null?Tt:(Cn=Q.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},m(Q)}else if(st==="text_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j);continue}let Q=y;Q&&(Ze==="flow"?(me(Q),ht=Q):(Q.streaming=!1,m(Q)),y=null),T=typeof x.id=="string"?x.id:T,I=""}else if(st==="text_delta"){let V=typeof x.id=="string"?x.id:null,j=V?M.get(V):void 0;if(V&&j){let G=typeof x.delta=="string"?x.delta:"",Ne=((Kn=C.get(V))!=null?Kn:"")+G;if(C.set(V,Ne),Ne.trim()==="")continue;let rt=X(V,j);rt.agentMetadata={...rt.agentMetadata,executionId:x.executionId,parentToolId:j},ot(rt,Ne,G,void 0);continue}if(T=typeof x.id=="string"?x.id:T,Ze==="flow"){let G=typeof x.delta=="string"?x.delta:"";if(I+=G,I.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:x.executionId,iteration:x.iteration},ot(Ne,I,G,void 0),w=Ne;continue}let Q=ee();Q.content+=(Gn=x.delta)!=null?Gn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:be!=null?be:void 0,agentName:ue==null?void 0:ue.agentName},w=Q,m(Q)}else if(st==="text_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)){let Q=P.get(V);Q&&me(Q),M.delete(V),C.delete(V),P.delete(V);continue}let j=y;j&&(Ze==="flow"?(me(j),ht=j):(((On=j.content)!=null?On:"")===""&&typeof x.text=="string"&&(j.content=x.text),j.streaming=!1,m(j)),y=null),T=null,I=""}else if(st==="step_complete"){let V=x.stepType,j=x.executionType;if(V==="tool"||j==="context")continue;if(x.success===!1){let Q=x.error,G=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&"message"in Q?String((eo=Q.message)!=null?eo:"Step failed"):"Step failed";t({type:"error",error:new Error(G)});let Ne=y;Ne&&Ne.streaming&&(Ne.streaming=!1,m(Ne)),t({type:"status",status:"idle"});continue}{let Q=ht;ht=null;let G=x.stopReason,Ne=(Ce=x.result)==null?void 0:Ce.response;if(Q)G&&(Q.stopReason=G),Ne!=null?Wt(Q,Ne):Q.streaming!==!1&&(le.delete(Q.id),Te.delete(Q.id),Q.streaming=!1,m(Q));else{let rt=Ne!=null&&Ne!=="";if(rt||G){let dt=ee();G&&(dt.stopReason=G),rt?me(dt,Ne):(dt.streaming=!1,m(dt))}}continue}}else if(st==="execution_start")Ze=x.kind==="flow"?"flow":"agent",jt=!0,Ze==="agent"&&(ue={executionId:x.executionId,agentId:(Nr=x.agentId)!=null?Nr:"virtual",agentName:(Qn=x.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=x.maxTurns)!=null?_t:1,startedAt:Se(x.startedAt)});else if(st==="turn_start"){let V=typeof x.iteration=="number"?x.iteration:xe;if(V!==xe){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let j=y;j&&(j.streaming=!1,m(j),xn.set(V-1,j),y=null)}xe=V}be=typeof x.id=="string"?x.id:null,w=null}else if(st==="tool_input_delta"){let V=(Xn=x.toolCallId)!=null?Xn:R.lastId;if(V){let j=q.get(V);j!=null&&j.toolCall&&(j.toolCall.chunks=(Fr=j.toolCall.chunks)!=null?Fr:[],j.toolCall.chunks.push((ks=x.delta)!=null?ks:""),m(j))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=x.stopReason,j=y!=null?y:w;if(V&&j!==null){let Q=x.id;(!Q||((Xo=j.agentMetadata)==null?void 0:Xo.turnId)===Q)&&(j.stopReason=V,m(j))}be===x.id&&(be=null)}else if(st==="media_start"){let V=String(x.id);Ee.set(V,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Ee.get(String(x.id));V&&typeof x.delta=="string"&&V.parts.push(x.delta)}else if(st==="media_complete"){let V=String(x.id),j=Ee.get(V);Ee.delete(V);let Q=(Eo=(Ls=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ls:j==null?void 0:j.mediaType)!=null?Eo:"application/octet-stream",G=typeof x.data=="string"?x.data:void 0,Ne=typeof x.url=="string"?x.url:j&&j.parts.length>0?j.parts.join(""):void 0,rt=null;if(G)rt={type:"media",data:G,mediaType:Q};else if(Ne){let In=Q.toLowerCase();rt={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:Q}}let dt=(Ar=x.toolCallId)!=null?Ar:j==null?void 0:j.toolCallId,hi=rt?[rt]:[],oo=[];for(let In of hi){if(!In||typeof In!="object")continue;let Jt=In,so=typeof Jt.type=="string"?Jt.type:void 0,Jn=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tn=null,Rn="";if(so==="media"){let En=typeof Jt.data=="string"?Jt.data:void 0;if(!En)continue;Rn=Jn.length>0?Jn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(so==="image-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else if(so==="file-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else continue;if(Tn)if(so==="image-url"||Rn.startsWith("image/"))oo.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))oo.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))oo.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";oo.push({type:"file",data:Tn,mimeType:En,filename:ch(En)})}}if(oo.length>0){let In=p(),Jt=dt,Jn={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:oo,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:xe}};m(Jn);let Tn=y;Tn&&(Tn.streaming=!1,m(Tn)),y=null,E.current=null}}else if(st==="execution_complete"){let V=(to=x.kind)!=null?to:Ze;V==="agent"&&ue&&(ue.status=x.success?"complete":"error",ue.completedAt=Se(x.completedAt),ue.stopReason=x.stopReason);let j=y;j&&(V==="flow"&&j.streaming!==!1?me(j):(j.streaming=!1,m(j)),y=null),T=null,I="",ht=null,t({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof x.error=="string"?x.error:(rn=(ct=x.error)==null?void 0:ct.message)!=null?rn:"Execution error";t({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(on=x.approvalId)!=null?on:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(Sr=ue==null?void 0:ue.agentId)!=null?Sr:"virtual",executionId:(Or=(Ps=x.executionId)!=null?Ps:ue==null?void 0:ue.executionId)!=null?Or:"",toolName:(Mo=x.toolName)!=null?Mo:"",toolType:x.toolType,description:($=x.description)!=null?$:`Execute ${(Tr=x.toolName)!=null?Tr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="step_await"&&x.awaitReason==="approval_required"){let V=(Jo=x.approvalId)!=null?Jo:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(lr=ue==null?void 0:ue.agentId)!=null?lr:"virtual",executionId:(_r=(Er=x.executionId)!=null?Er:ue==null?void 0:ue.executionId)!=null?_r:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Yo=x.description)!=null?Yo:`Execute ${(cr=x.toolName)!=null?cr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="approval_complete"){let V=x.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(ha=x.decision)!=null?ha:"approved",agentId:(hn=ue==null?void 0:ue.agentId)!=null?hn:"virtual",executionId:(dr=(An=x.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?dr:"",toolName:(Sn=x.toolName)!=null?Sn:"",description:(ko=x.description)!=null?ko:"",resolvedAt:Date.now()}};m(Q)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=x.artifactType,j=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:j,artifactType:V,title:Q,component:typeof x.component=="string"?x.component:void 0}),Ae.set(j,{markdown:"",title:Q}),!de.has(j)){de.add(j);let G={id:`artifact-ref-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:j,title:Q,artifactType:V,status:"streaming"}})};oe.set(j,G),m(G)}}else if(st==="artifact_delta"){let V=String(x.id),j=typeof x.delta=="string"?x.delta:String((pr=x.delta)!=null?pr:"");t({type:"artifact_delta",id:V,artDelta:j});let Q=Ae.get(V);Q&&(Q.markdown+=j)}else if(st==="artifact_update"){let V=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:V,component:typeof x.component=="string"?x.component:void 0})}else if(st==="artifact_complete"){let V=String(x.id);t({type:"artifact_complete",id:V});let j=oe.get(V);if(j){j.streaming=!1;try{let Q=JSON.parse((yn=j.rawContent)!=null?yn:"{}");if(Q.props){Q.props.status="complete";let G=Ae.get(V);G!=null&&G.markdown&&(Q.props.markdown=G.markdown)}j.rawContent=JSON.stringify(Q)}catch{}Ae.delete(V),m(j),oe.delete(V)}}}else if(st==="transcript_insert"){let V=x.message;if(!V||typeof V!="object")continue;let j=String((kr=V.id)!=null?kr:`msg-${p()}`),Q=V.role,Ne={id:j,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:p()};if(m(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),dt=(Zo=rt==null?void 0:rt.props)==null?void 0:Zo.artifactId;typeof dt=="string"&&de.add(dt)}catch{}y=null,E.current=null,le.delete(j),Te.delete(j)}else if(st==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let V=typeof x.error=="string"?x.error:((Lo=x.error)==null?void 0:Lo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(V)});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(x.error instanceof Error)V=x.error;else if(st==="dispatch_error"){let j=(es=x.message)!=null?es:x.error;j!=null&&j!==""&&(V=new Error(String(j)))}else{let j=x.error;typeof j=="string"&&j!==""?V=new Error(j):j!=null&&typeof j=="object"&&"message"in j&&(V=new Error(String((no=j.message)!=null?no:j)))}if(V){t({type:"error",error:V});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:L,value:ge}=await s.read();if(L)break;i+=a.decode(ge,{stream:!0});let Me=i.split(`
|
|
11
|
+
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>n,processChunk:async r=>{if(r.length<=e)return n!==null?{text:n,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=t(r);return s!==null&&(n=s),e=r.length,n!==null?{text:n,raw:r}:null},close:async()=>{}}},Qs=n=>{try{let e=JSON.parse(n);if(e&&typeof e=="object"&&typeof e.text=="string")return e.text}catch{return null}return null},Vu=()=>{let n={processChunk:e=>null,getExtractedText:()=>null};return n.__isPlainTextParser=!0,n},Ku=()=>{var e;let n=ah();return{processChunk:async t=>{let r=t.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:n.processChunk(t)},getExtractedText:n.getExtractedText.bind(n),close:(e=n.close)==null?void 0:e.bind(n)}},Gu=()=>{let n=null,e=0;return{getExtractedText:()=>n,processChunk:t=>{let r=t.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(t.length<=e)return n!==null||n===""?{text:n||"",raw:t}:null;try{let o=(0,gs.parse)(t,gs.STR|gs.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?n=typeof o.text=="string"?qu(o.text):"":o.type==="init"&&o.form?n="":typeof o.text=="string"&&(n=qu(o.text)))}catch{}return e=t.length,n!==null?{text:n,raw:t}:null},close:()=>{}}};var Qu=()=>{let n=null;return{processChunk:e=>{if(!e.trim().startsWith("<"))return null;let r=e.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(n=r[1],{text:n,raw:e}):null},getExtractedText:()=>n}};var Xu="4.6.1";var Xs=Xu;var lh="https://api.runtype.com/v1/dispatch",Ha="https://api.runtype.com";function ch(n){var s,a;let e=n.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[e];if(r)return`attachment.${r}`;let o=e.indexOf("/");if(o>0){let i=(a=(s=e.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _i=n=>!!(n.contentParts&&n.contentParts.length>0||n.llmContent&&n.llmContent.trim().length>0||n.rawContent&&n.rawContent.trim().length>0||n.content&&n.content.trim().length>0);function dh(n){switch(n){case"json":return Gu;case"regex-json":return Ku;case"xml":return Qu;default:return Vu}}var Ju=n=>n.startsWith("{")||n.startsWith("[")||n.startsWith("<");function ph(n,e){if(!n)return e;let t=n.trim(),r=e.trim();if(t.length===0)return e;if(r.length===0)return n;let o=Ju(t);if(!Ju(r))return n;if(!o||r===t||r.startsWith(t))return e;let a=Qs(n);return Qs(e)!==null&&a===null?e:n}var Js=class{constructor(e={}){this.config=e;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var t,r,o,s;if(e.target&&(e.agentId||e.flowId||e.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(t=e.apiUrl)!=null?t:lh,this.headers={"Content-Type":"application/json","X-Persona-Version":Xs,...e.headers},this.debug=!!e.debug,this.createStreamParser=(r=e.streamParser)!=null?r:dh(e.parserType),this.contextProviders=(o=e.contextProviders)!=null?o:[],this.requestMiddleware=e.requestMiddleware,this.customFetch=e.customFetch,this.parseSSEEvent=e.parseSSEEvent,this.getHeaders=e.getHeaders,this.webMcpBridge=((s=e.webmcp)==null?void 0:s.enabled)===!0?new Ma(e.webmcp):null}updateConfig(e){this.config=e}setSSEEventCallback(e){this.onSSEEvent=e}setWebMcpConfirmHandler(e){var t;(t=this.webMcpBridge)==null||t.setConfirmHandler(e)}isWebMcpOperational(){var e;return((e=this.webMcpBridge)==null?void 0:e.isOperational())===!0}executeWebMcpToolCall(e,t,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(e,t,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:e,flowId:t,target:r,targetProviders:o}=this.config;if(!r)return{agentId:e,flowId:t};let s=ku(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(e){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/${e}`}getClientSession(){return this.clientSession}async initSession(){var e,t;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(t=(e=this.config).onSessionInit)==null||t.call(e,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let e=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,t=this.routing(),r=(c=t.agentId)!=null?c:t.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...e&&{sessionId:e}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var t;return`${((t=this.config.apiUrl)==null?void 0:t.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/client/feedback`}async sendFeedback(e){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(e.type)&&!e.messageId)throw new Error(`messageId is required for ${e.type} feedback type`);if(e.type==="csat"&&(e.rating===void 0||e.rating<1||e.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(e.type==="nps"&&(e.rating===void 0||e.rating<0||e.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",e);let o={...e,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:e,type:t})}async submitCSATFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:e,comment:t})}async submitNPSFeedback(e,t){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:e,comment:t})}async dispatch(e,t){return this.isClientTokenMode()?this.dispatchClientToken(e,t):this.isAgentMode()?this.dispatchAgent(e,t):this.dispatchProxy(e,t)}async dispatchClientToken(e,t){var o,s,a,i;let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:M}),M}let c=await this.buildPayload(e.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,g={sessionId:d.sessionId,messages:e.messages.filter(_i).map(M=>{var P,C,k;return{id:M.id,role:M.role,content:(k=(C=(P=M.contentParts)!=null?P:M.llmContent)!=null?C:M.rawContent)!=null?k:M.content}}),...e.assistantMessageId&&{assistantMessageId:e.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...c.inputs&&Object.keys(c.inputs).length>0&&{inputs:c.inputs},...c.context&&{context:c.context}},h=c.clientTools,m=!!(h&&h.length>0),y=m?Tu(h):void 0,w=this.clientToolsFingerprintSessionId===d.sessionId,E=m&&w&&this.lastSentClientToolsFingerprint===y,B=!1,T=null,I;for(let M=0;;M++){let C={...g,...m&&(B||!E)&&h?{clientTools:h}:{},...y?{clientToolsFingerprint:y}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",C),I=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xs},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&m){let k=await I.json().catch(()=>null);if((k==null?void 0:k.error)==="client_tools_resend_required"){B=!0,this.lastSentClientToolsFingerprint=null;continue}T=k!=null?k:{error:"Chat request failed"}}break}if(!I.ok){let M=T!=null?T:await I.json().catch(()=>({error:"Chat request failed"}));if(I.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let C=new Error("Session expired. Please refresh to continue.");throw t({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw t({type:"error",error:C}),C}let P=new Error(M.error||"Failed to send message");throw t({type:"error",error:P}),P}if(!I.body){let M=new Error("No response body received");throw t({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=y!=null?y:null,this.clientToolsFingerprintSessionId=d.sessionId,t({type:"status",status:"connected"});try{await this.streamResponse(I.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}catch(d){let c=d instanceof Error?d:new Error(String(d));throw!c.message.includes("Session expired")&&!c.message.includes("Message limit")&&t({type:"error",error:c}),c}}async dispatchProxy(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t)}finally{t({type:"status",status:"idle"})}}async dispatchAgent(e,t){let r=new AbortController;e.signal&&e.signal.addEventListener("abort",()=>r.abort()),t({type:"status",status:"connecting"});let o=await this.buildAgentPayload(e.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw t({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw t({type:"error",error:i}),i}t({type:"status",status:"connected"});try{await this.streamResponse(a.body,t,e.assistantMessageId)}finally{t({type:"status",status:"idle"})}}async processStream(e,t,r,o){t({type:"status",status:"connected"});try{await this.streamResponse(e,t,r,o)}finally{t({type:"status",status:"idle"})}}async resolveApproval(e,t){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ha}/v1/agents/${e.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:e.executionId,approvalId:e.approvalId,decision:t,streamResponse:!0})})}async resumeFlow(e,t,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||Ha}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:e,toolOutputs:t,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(e){var a,i,d;let t=this.routing().agentId;if(!this.config.agent&&!t)throw new Error("Agent configuration required for agent mode");let r=e.slice().filter(_i).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let g=new Date(c.createdAt).getTime(),h=new Date(p.createdAt).getTime();return g-h}).map(c=>{var p,g,h;return{role:c.role,content:(h=(g=(p=c.contentParts)!=null?p:c.llmContent)!=null?g:c.rawContent)!=null?h:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:t},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...Fi(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let g=await p({messages:e,config:this.config});g&&typeof g=="object"&&Object.assign(c,g)}catch(g){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",g)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(e){var a,i;let t=e.slice().filter(_i).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),g=new Date(c.createdAt).getTime();return p-g}).map(d=>{var c,p,g;return{role:d.role,content:(g=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?g:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:t,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...Fi(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:e,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let c=d;return o.clientTools!==void 0&&!("clientTools"in c)&&(c.clientTools=o.clientTools),c}}catch(d){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",d)}return o}async handleCustomSSEEvent(e,t,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(e);if(i===null)return!1;let d=p=>{let g={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=g,o(g),g},c=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,o(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=c(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,t({type:"status",status:"idle"})),i.error&&(a.current=null,t({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(e,t,r,o){var fn,hr,yr,qe;let s=e.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,g=L=>{let ge=L.reasoning?{...L.reasoning,chunks:[...L.reasoning.chunks]}:void 0,Me=L.toolCall?{...L.toolCall,chunks:L.toolCall.chunks?[...L.toolCall.chunks]:void 0}:void 0,Le=L.tools?L.tools.map(He=>({...He,chunks:He.chunks?[...He.chunks]:void 0})):void 0;return{...L,reasoning:ge,toolCall:Me,tools:Le}},h=L=>{if(L.role!=="assistant"||L.variant)return!0;let ge=Array.isArray(L.contentParts)&&L.contentParts.length>0,Me=typeof L.rawContent=="string"&&L.rawContent.trim()!=="";return typeof L.content=="string"&&L.content.trim()!==""||ge||Me||!!L.stopReason},m=L=>{h(L)&&t({type:"message",message:g(L)})},y=null,w=null,E={current:null},B={current:null},T=null,I="",M=new Map,P=new Map,C=new Map,k=new Map,q=new Map,_={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},O=L=>{if(L==null)return null;try{return String(L)}catch{return null}},F=L=>{var ge,Me,Le,He,nt;return O((nt=(He=(Le=(Me=(ge=L.stepId)!=null?ge:L.step_id)!=null?Me:L.step)!=null?Le:L.parentId)!=null?He:L.flowStepId)!=null?nt:L.flow_step_id)},Z=L=>{var ge,Me,Le,He,nt,Xe,yt;return O((yt=(Xe=(nt=(He=(Le=(Me=(ge=L.callId)!=null?ge:L.call_id)!=null?Me:L.requestId)!=null?Le:L.request_id)!=null?He:L.toolCallId)!=null?nt:L.tool_call_id)!=null?Xe:L.stepId)!=null?yt:L.step_id)},ke=r,pe=!1,ee=()=>{if(y)return y;let L,ge="",Me=T;return!pe&&ke?(L=ke,pe=!0,ge=o!=null?o:""):ke&&Me?L=`${ke}_${Me}`:L=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,y={id:L,role:"assistant",content:ge,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},m(y),y},Pe=(L,ge)=>{_.lastId=ge,L&&_.byStep.set(L,ge)},Ie=(L,ge)=>{var nt;let Me=(nt=L.reasoningId)!=null?nt:L.id,Le=F(L);if(Me){let Xe=String(Me);return Pe(Le,Xe),Xe}if(Le){let Xe=_.byStep.get(Le);if(Xe)return _.lastId=Xe,Xe}if(_.lastId&&!ge)return _.lastId;if(!ge)return null;let He=`reason-${p()}`;return Pe(Le,He),He},ie=L=>{let ge=k.get(L);if(ge)return ge;let Me={id:`reason-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:L,status:"streaming",chunks:[]}};return k.set(L,Me),m(Me),Me},he=(L,ge)=>{R.lastId=ge,L&&R.byCall.set(L,ge)},re=new Set,oe=new Map,de=new Set,Ae=new Map,$e=L=>{if(!L)return!1;let ge=L.replace(/_+/g,"_").replace(/^_|_$/g,"");return ge==="emit_artifact_markdown"||ge==="emit_artifact_component"},K=(L,ge)=>{var nt;let Me=(nt=L.toolId)!=null?nt:L.id,Le=Z(L);if(Me){let Xe=String(Me);return he(Le,Xe),Xe}if(Le){let Xe=R.byCall.get(Le);if(Xe)return R.lastId=Xe,Xe}if(R.lastId&&!ge)return R.lastId;if(!ge)return null;let He=`tool-${p()}`;return he(Le,He),He},J=L=>{let ge=q.get(L);if(ge)return ge;let Me={id:`tool-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:L,status:"pending"}};return q.set(L,Me),m(Me),Me},Se=L=>{if(typeof L=="number"&&Number.isFinite(L))return L;if(typeof L=="string"){let ge=Number(L);if(!Number.isNaN(ge)&&Number.isFinite(ge))return ge;let Me=Date.parse(L);if(!Number.isNaN(Me))return Me}return Date.now()},Y=L=>{if(typeof L=="string")return L;if(L==null)return"";try{return JSON.stringify(L)}catch{return String(L)}},le=new Map,Te=new Map,Ye=new Map,tt=(L,ge,Me)=>{var yt;let Le=Ye.get(L);Le||(Le=[],Ye.set(L,Le));let He=0,nt=Le.length;for(;He<nt;){let fe=He+nt>>>1;Le[fe].seq<ge?He=fe+1:nt=fe}((yt=Le[He])==null?void 0:yt.seq)===ge?Le[He]={seq:ge,text:Me}:Le.splice(He,0,{seq:ge,text:Me});let Xe="";for(let fe=0;fe<Le.length;fe++)Xe+=Le[fe].text;return Xe},Wt=(L,ge)=>{let Me=Y(ge),Le=Te.get(L.id),He=ph(Le,Me);L.rawContent=He;let nt=le.get(L.id),Xe=ce=>{var Ge;let ft=(Ge=L.content)!=null?Ge:"";ce.trim()!==""&&(ft.trim().length===0||ce.startsWith(ft)||ce.trimStart().startsWith(ft.trim()))&&(L.content=ce)},yt=()=>{var ce;if(nt){let ft=(ce=nt.close)==null?void 0:ce.call(nt);ft instanceof Promise&&ft.catch(()=>{})}le.delete(L.id),Te.delete(L.id),L.streaming=!1,m(L)};if(!nt){Xe(Me),yt();return}let fe=Qs(He);if(fe!==null&&fe.trim()!==""){Xe(fe),yt();return}let D=ce=>{var Pt;let ft=typeof ce=="string"?ce:(Pt=ce==null?void 0:ce.text)!=null?Pt:null;if(ft!==null&&ft.trim()!=="")return ft;let Ge=nt.getExtractedText();return Ge!==null&&Ge.trim()!==""?Ge:Me},ve;try{ve=nt.processChunk(He)}catch{Xe(Me),yt();return}if(ve instanceof Promise){ve.then(ce=>{Xe(D(ce)),yt()}).catch(()=>{Xe(Me),yt()});return}Xe(D(ve)),yt()},ht=null,ot=(L,ge,Me,Le)=>{var fe;L.rawContent=ge,le.has(L.id)||le.set(L.id,this.createStreamParser());let He=le.get(L.id),nt=ge.trim().startsWith("{")||ge.trim().startsWith("[");if(nt&&Te.set(L.id,ge),He.__isPlainTextParser===!0){L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L);return}let yt=He.processChunk(ge);if(yt instanceof Promise)yt.then(D=>{var ce;let ve=typeof D=="string"?D:(ce=D==null?void 0:D.text)!=null?ce:null;ve!==null&&ve.trim()!==""?(L.content=ve,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}).catch(()=>{L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L)});else{let D=typeof yt=="string"?yt:(fe=yt==null?void 0:yt.text)!=null?fe:null;D!==null&&D.trim()!==""?(L.content=D,m(L)):!nt&&!ge.trim().startsWith("<")&&(L.content=Le!==void 0?ge:L.content+Me,Te.delete(L.id),le.delete(L.id),L.rawContent=void 0,m(L))}},me=(L,ge)=>{var fe,D;let Me=ge!=null?ge:L.content;if(Me==null||Me===""){L.streaming=!1,m(L);return}let Le=Te.get(L.id),He=Le!=null?Le:Y(Me);L.rawContent=He;let nt=le.get(L.id),Xe=null,yt=!1;if(nt&&(Xe=nt.getExtractedText(),Xe===null&&(Xe=Qs(He)),Xe===null)){let ve=nt.processChunk(He);ve instanceof Promise?(yt=!0,ve.then(ce=>{var Ge;let ft=typeof ce=="string"?ce:(Ge=ce==null?void 0:ce.text)!=null?Ge:null;ft!==null&&(L.content=ft,L.streaming=!1,le.delete(L.id),Te.delete(L.id),m(L))}).catch(()=>{})):Xe=typeof ve=="string"?ve:(fe=ve==null?void 0:ve.text)!=null?fe:null}if(!yt){Xe!==null&&Xe.trim()!==""?L.content=Xe:Te.has(L.id)||(L.content=Y(Me));let ve=le.get(L.id);if(ve){let ce=(D=ve.close)==null?void 0:D.call(ve);ce instanceof Promise&&ce.catch(()=>{}),le.delete(L.id)}Te.delete(L.id),L.streaming=!1,m(L)}},X=(L,ge,Me)=>{let Le=P.get(L);if(Le)return Le;let He={id:`nested-${ge}-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Me?{variant:Me}:{},...Me==="reasoning"?{reasoning:{id:L,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ge}};return P.set(L,He),m(He),He},lt=[],Ve,Ee=new Map,xe=0,Ze="agent",jt=!1,be=null,ue=null,xn=new Map,At=(fn=this.config.iterationDisplay)!=null?fn:"separate";for(Ve=()=>{var L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo,Ce,Nr,Qn,_t,Xn,Fr,ks,Xo,Ls,Eo,Ar,to,ct,rn,on,Sr,Ps,Or,Mo,Tr,$,Jo,lr,Er,_r,Mr,cr,Yo,ha,hn,An,dr,Sn,ko,pr,yn,kr,Zo,Lo,es,no;for(let ro=0;ro<lt.length;ro++){let st=lt[ro].payloadType,x=lt[ro].payload;if(!jt&&Ze!=="flow"&&typeof x.stepType=="string"&&(Ze="flow"),st==="reasoning_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j),X(V,j,"reasoning");continue}let Q=(L=Ie(x,!0))!=null?L:`reason-${p()}`,G=ie(Q);G.reasoning=(ge=G.reasoning)!=null?ge:{id:Q,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:Se((Me=x.startedAt)!=null?Me:x.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),G.streaming=!0,G.reasoning.status="streaming",m(G)}else if(st==="reasoning_delta"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let Ne=P.get(V),rt=(Xe=(nt=(He=x.reasoningText)!=null?He:x.text)!=null?nt:x.delta)!=null?Xe:"";rt&&x.hidden!==!0&&Ne.reasoning&&(Ne.reasoning.chunks.push(String(rt)),m(Ne));continue}let j=(fe=(yt=Ie(x,!1))!=null?yt:Ie(x,!0))!=null?fe:`reason-${p()}`,Q=ie(j);Q.reasoning=(D=Q.reasoning)!=null?D:{id:j,status:"streaming",chunks:[]},Q.reasoning.startedAt=(ce=Q.reasoning.startedAt)!=null?ce:Se((ve=x.startedAt)!=null?ve:x.timestamp);let G=(Pt=(Ge=(ft=x.reasoningText)!=null?ft:x.text)!=null?Ge:x.delta)!=null?Pt:"";if(G&&x.hidden!==!0){let Ne=typeof x.sequenceIndex=="number"?x.sequenceIndex:void 0;if(Ne!==void 0){let rt=tt(j,Ne,String(G));Q.reasoning.chunks=[rt]}else Q.reasoning.chunks.push(String(G))}if(Q.reasoning.status=x.done?"complete":"streaming",x.done){Q.reasoning.completedAt=Se((kt=x.completedAt)!=null?kt:x.timestamp);let Ne=(wt=Q.reasoning.startedAt)!=null?wt:Date.now();Q.reasoning.durationMs=Math.max(0,((Ht=Q.reasoning.completedAt)!=null?Ht:Date.now())-Ne)}Q.streaming=Q.reasoning.status!=="complete",m(Q)}else if(st==="reasoning_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)&&P.has(V)){let rt=P.get(V);if(rt.reasoning){let dt=typeof x.text=="string"?x.text:"";dt&&rt.reasoning.chunks.length===0&&rt.reasoning.chunks.push(dt),rt.reasoning.status="complete",rt.streaming=!1,m(rt)}M.delete(V),P.delete(V);continue}let j=(Ot=(Xt=Ie(x,!1))!=null?Xt:Ie(x,!0))!=null?Ot:`reason-${p()}`,Q=typeof x.text=="string"?x.text:"";!k.get(j)&&(Q||x.scope==="loop")&&ie(j);let G=k.get(j);if(G!=null&&G.reasoning){(x.scope==="loop"||x.scope==="turn")&&(G.reasoning.scope=x.scope),Q&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(Q),G.reasoning.status="complete",G.reasoning.completedAt=Se((en=x.completedAt)!=null?en:x.timestamp);let rt=(br=G.reasoning.startedAt)!=null?br:Date.now();G.reasoning.durationMs=Math.max(0,((Wr=G.reasoning.completedAt)!=null?Wr:Date.now())-rt),G.streaming=!1,m(G)}let Ne=F(x);Ne&&_.byStep.delete(Ne)}else if(st==="tool_start"){y&&(y.streaming=!1,m(y),y=null),typeof x.iteration=="number"&&(xe=x.iteration);let V=(or=(rr=typeof x.toolCallId=="string"?x.toolCallId:void 0)!=null?rr:K(x,!0))!=null?or:`tool-${p()}`,j=(Kr=x.toolName)!=null?Kr:x.name;if($e(j)){re.add(V);continue}he(Z(x),V);let Q=J(V),G=(Vt=Q.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=j!=null?j:G.name,G.status="running",x.parameters!==void 0?G.args=x.parameters:x.args!==void 0&&(G.args=x.args),G.startedAt=(Hr=G.startedAt)!=null?Hr:Se((sr=x.startedAt)!=null?sr:x.timestamp),G.completedAt=void 0,G.durationMs=void 0,Q.toolCall=G,Q.streaming=!0,x.executionId&&(Q.agentMetadata={executionId:x.executionId,iteration:x.iteration}),m(Q)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(x,!1))!=null?Bn:K(x,!0))!=null?Ln:`tool-${p()}`;if(re.has(V))continue;let j=J(V),Q=(Dn=j.toolCall)!=null?Dn:{id:V,status:"running"};Q.startedAt=(vr=Q.startedAt)!=null?vr:Se((ar=x.startedAt)!=null?ar:x.timestamp);let G=(Qr=(Vn=(Gr=x.text)!=null?Gr:x.delta)!=null?Vn:x.message)!=null?Qr:"";G&&(Q.chunks=(St=Q.chunks)!=null?St:[],Q.chunks.push(String(G))),Q.status="running",j.toolCall=Q,j.streaming=!0;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Br=j.agentMetadata)!=null?Br:{executionId:(wr=Ne==null?void 0:Ne.executionId)!=null?wr:x.executionId,iteration:(xr=Ne==null?void 0:Ne.iteration)!=null?xr:x.iteration}),m(j)}else if(st==="tool_complete"){let V=(bt=(ir=K(x,!1))!=null?ir:K(x,!0))!=null?bt:`tool-${p()}`;if(re.has(V)){re.delete(V);continue}let j=J(V),Q=(Co=j.toolCall)!=null?Co:{id:V,status:"running"};Q.status="complete",x.result!==void 0&&(Q.result=x.result),typeof x.duration=="number"&&(Q.duration=x.duration),Q.completedAt=Se((Cr=x.completedAt)!=null?Cr:x.timestamp);let G=(Ao=x.duration)!=null?Ao:x.executionTime;if(typeof G=="number")Q.durationMs=G;else{let dt=(Pn=Q.startedAt)!=null?Pn:Date.now();Q.durationMs=Math.max(0,((Qo=Q.completedAt)!=null?Qo:Date.now())-dt)}j.toolCall=Q,j.streaming=!1;let Ne=x.agentContext;(Ne||x.executionId)&&(j.agentMetadata=(Jr=j.agentMetadata)!=null?Jr:{executionId:(Xr=Ne==null?void 0:Ne.executionId)!=null?Xr:x.executionId,iteration:(Dr=Ne==null?void 0:Ne.iteration)!=null?Dr:x.iteration}),m(j);let rt=Z(x);rt&&R.byCall.delete(rt)}else if(st==="await"&&x.toolName){let V=typeof x.toolCallId=="string"&&x.toolCallId.length>0?x.toolCallId:void 0,j=(Yr=V!=null?V:x.toolId)!=null?Yr:`local-${p()}`,Q=J(j),G=x.toolName,Ne=x.origin==="webmcp"&&!cs(G)?`webmcp:${G}`:G,rt=cs(Ne),dt=(So=Q.toolCall)!=null?So:{id:j,status:"pending"};dt.name=Ne,dt.args=x.parameters,dt.status=rt?"running":"complete",dt.chunks=(To=dt.chunks)!=null?To:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:Se((xt=(Zr=x.startedAt)!=null?Zr:x.timestamp)!=null?xt:x.awaitedAt),rt?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(Fn=dt.completedAt)!=null?Fn:dt.startedAt,Q.toolCall=dt,Q.streaming=!1,Q.agentMetadata={...Q.agentMetadata,executionId:(Tt=x.executionId)!=null?Tt:(Cn=Q.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},m(Q)}else if(st==="text_start"){let V=typeof x.id=="string"?x.id:null,j=typeof x.parentToolCallId=="string"&&x.parentToolCallId?x.parentToolCallId:null;if(V&&j){M.set(V,j);continue}let Q=y;Q&&(Ze==="flow"?(me(Q),ht=Q):(Q.streaming=!1,m(Q)),y=null),T=typeof x.id=="string"?x.id:T,I=""}else if(st==="text_delta"){let V=typeof x.id=="string"?x.id:null,j=V?M.get(V):void 0;if(V&&j){let G=typeof x.delta=="string"?x.delta:"",Ne=((Kn=C.get(V))!=null?Kn:"")+G;if(C.set(V,Ne),Ne.trim()==="")continue;let rt=X(V,j);rt.agentMetadata={...rt.agentMetadata,executionId:x.executionId,parentToolId:j},ot(rt,Ne,G,void 0);continue}if(T=typeof x.id=="string"?x.id:T,Ze==="flow"){let G=typeof x.delta=="string"?x.delta:"";if(I+=G,I.trim()==="")continue;let Ne=ee();Ne.agentMetadata={executionId:x.executionId,iteration:x.iteration},ot(Ne,I,G,void 0),w=Ne;continue}let Q=ee();Q.content+=(Gn=x.delta)!=null?Gn:"",Q.agentMetadata={executionId:x.executionId,iteration:x.iteration,turnId:be!=null?be:void 0,agentName:ue==null?void 0:ue.agentName},w=Q,m(Q)}else if(st==="text_complete"){let V=typeof x.id=="string"?x.id:null;if(V&&M.has(V)){let Q=P.get(V);Q&&me(Q),M.delete(V),C.delete(V),P.delete(V);continue}let j=y;j&&(Ze==="flow"?(me(j),ht=j):(((On=j.content)!=null?On:"")===""&&typeof x.text=="string"&&(j.content=x.text),j.streaming=!1,m(j)),y=null),T=null,I=""}else if(st==="step_complete"){let V=x.stepType,j=x.executionType;if(V==="tool"||j==="context")continue;if(x.success===!1){let Q=x.error,G=typeof Q=="string"&&Q!==""?Q:Q!=null&&typeof Q=="object"&&Reflect.has(Q,"message")?String((eo=Q.message)!=null?eo:"Step failed"):"Step failed";t({type:"error",error:new Error(G)});let Ne=y;Ne&&Ne.streaming&&(Ne.streaming=!1,m(Ne)),t({type:"status",status:"idle"});continue}{let Q=ht;ht=null;let G=x.stopReason,Ne=(Ce=x.result)==null?void 0:Ce.response;if(Q)G&&(Q.stopReason=G),Ne!=null?Wt(Q,Ne):Q.streaming!==!1&&(le.delete(Q.id),Te.delete(Q.id),Q.streaming=!1,m(Q));else{let rt=Ne!=null&&Ne!=="";if(rt||G){let dt=ee();G&&(dt.stopReason=G),rt?me(dt,Ne):(dt.streaming=!1,m(dt))}}continue}}else if(st==="execution_start")Ze=x.kind==="flow"?"flow":"agent",jt=!0,Ze==="agent"&&(ue={executionId:x.executionId,agentId:(Nr=x.agentId)!=null?Nr:"virtual",agentName:(Qn=x.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=x.maxTurns)!=null?_t:1,startedAt:Se(x.startedAt)});else if(st==="turn_start"){let V=typeof x.iteration=="number"?x.iteration:xe;if(V!==xe){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let j=y;j&&(j.streaming=!1,m(j),xn.set(V-1,j),y=null)}xe=V}be=typeof x.id=="string"?x.id:null,w=null}else if(st==="tool_input_delta"){let V=(Xn=x.toolCallId)!=null?Xn:R.lastId;if(V){let j=q.get(V);j!=null&&j.toolCall&&(j.toolCall.chunks=(Fr=j.toolCall.chunks)!=null?Fr:[],j.toolCall.chunks.push((ks=x.delta)!=null?ks:""),m(j))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=x.stopReason,j=y!=null?y:w;if(V&&j!==null){let Q=x.id;(!Q||((Xo=j.agentMetadata)==null?void 0:Xo.turnId)===Q)&&(j.stopReason=V,m(j))}be===x.id&&(be=null)}else if(st==="media_start"){let V=String(x.id);Ee.set(V,{mediaType:typeof x.mediaType=="string"?x.mediaType:void 0,role:typeof x.role=="string"?x.role:void 0,toolCallId:x.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Ee.get(String(x.id));V&&typeof x.delta=="string"&&V.parts.push(x.delta)}else if(st==="media_complete"){let V=String(x.id),j=Ee.get(V);Ee.delete(V);let Q=(Eo=(Ls=typeof x.mediaType=="string"?x.mediaType:void 0)!=null?Ls:j==null?void 0:j.mediaType)!=null?Eo:"application/octet-stream",G=typeof x.data=="string"?x.data:void 0,Ne=typeof x.url=="string"?x.url:j&&j.parts.length>0?j.parts.join(""):void 0,rt=null;if(G)rt={type:"media",data:G,mediaType:Q};else if(Ne){let In=Q.toLowerCase();rt={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Ne,mediaType:Q}}let dt=(Ar=x.toolCallId)!=null?Ar:j==null?void 0:j.toolCallId,hi=rt?[rt]:[],oo=[];for(let In of hi){if(!In||typeof In!="object")continue;let Jt=In,so=typeof Jt.type=="string"?Jt.type:void 0,Jn=typeof Jt.mediaType=="string"?Jt.mediaType.toLowerCase():"",Tn=null,Rn="";if(so==="media"){let En=typeof Jt.data=="string"?Jt.data:void 0;if(!En)continue;Rn=Jn.length>0?Jn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(so==="image-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else if(so==="file-url"){let En=typeof Jt.url=="string"?Jt.url:void 0;if(!En)continue;Rn=Jn,Tn=En}else continue;if(Tn)if(so==="image-url"||Rn.startsWith("image/"))oo.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))oo.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))oo.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";oo.push({type:"file",data:Tn,mimeType:En,filename:ch(En)})}}if(oo.length>0){let In=p(),Jt=dt,Jn={id:`agent-media-${typeof Jt=="string"&&Jt.length>0?`${Jt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:oo,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:x.executionId,iteration:typeof x.iteration=="number"?x.iteration:xe}};m(Jn);let Tn=y;Tn&&(Tn.streaming=!1,m(Tn)),y=null,E.current=null}}else if(st==="execution_complete"){let V=(to=x.kind)!=null?to:Ze;V==="agent"&&ue&&(ue.status=x.success?"complete":"error",ue.completedAt=Se(x.completedAt),ue.stopReason=x.stopReason);let j=y;j&&(V==="flow"&&j.streaming!==!1?me(j):(j.streaming=!1,m(j)),y=null),T=null,I="",ht=null,t({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof x.error=="string"?x.error:(rn=(ct=x.error)==null?void 0:ct.message)!=null?rn:"Execution error";t({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(on=x.approvalId)!=null?on:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(Sr=ue==null?void 0:ue.agentId)!=null?Sr:"virtual",executionId:(Or=(Ps=x.executionId)!=null?Ps:ue==null?void 0:ue.executionId)!=null?Or:"",toolName:(Mo=x.toolName)!=null?Mo:"",toolType:x.toolType,description:($=x.description)!=null?$:`Execute ${(Tr=x.toolName)!=null?Tr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="step_await"&&x.awaitReason==="approval_required"){let V=(Jo=x.approvalId)!=null?Jo:`approval-${p()}`,j={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(lr=ue==null?void 0:ue.agentId)!=null?lr:"virtual",executionId:(_r=(Er=x.executionId)!=null?Er:ue==null?void 0:ue.executionId)!=null?_r:"",toolName:(Mr=x.toolName)!=null?Mr:"",toolType:x.toolType,description:(Yo=x.description)!=null?Yo:`Execute ${(cr=x.toolName)!=null?cr:"tool"}`,...typeof x.reason=="string"&&x.reason?{reason:x.reason}:{},parameters:x.parameters}};m(j)}else if(st==="approval_complete"){let V=x.approvalId;if(V){let Q={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(ha=x.decision)!=null?ha:"approved",agentId:(hn=ue==null?void 0:ue.agentId)!=null?hn:"virtual",executionId:(dr=(An=x.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?dr:"",toolName:(Sn=x.toolName)!=null?Sn:"",description:(ko=x.description)!=null?ko:"",resolvedAt:Date.now()}};m(Q)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=x.artifactType,j=String(x.id),Q=typeof x.title=="string"?x.title:void 0;if(t({type:"artifact_start",id:j,artifactType:V,title:Q,component:typeof x.component=="string"?x.component:void 0}),Ae.set(j,{markdown:"",title:Q}),!de.has(j)){de.add(j);let G={id:`artifact-ref-${j}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:j,title:Q,artifactType:V,status:"streaming"}})};oe.set(j,G),m(G)}}else if(st==="artifact_delta"){let V=String(x.id),j=typeof x.delta=="string"?x.delta:String((pr=x.delta)!=null?pr:"");t({type:"artifact_delta",id:V,artDelta:j});let Q=Ae.get(V);Q&&(Q.markdown+=j)}else if(st==="artifact_update"){let V=x.props&&typeof x.props=="object"&&!Array.isArray(x.props)?x.props:{};t({type:"artifact_update",id:String(x.id),props:V,component:typeof x.component=="string"?x.component:void 0})}else if(st==="artifact_complete"){let V=String(x.id);t({type:"artifact_complete",id:V});let j=oe.get(V);if(j){j.streaming=!1;try{let Q=JSON.parse((yn=j.rawContent)!=null?yn:"{}");if(Q.props){Q.props.status="complete";let G=Ae.get(V);G!=null&&G.markdown&&(Q.props.markdown=G.markdown)}j.rawContent=JSON.stringify(Q)}catch{}Ae.delete(V),m(j),oe.delete(V)}}}else if(st==="transcript_insert"){let V=x.message;if(!V||typeof V!="object")continue;let j=String((kr=V.id)!=null?kr:`msg-${p()}`),Q=V.role,Ne={id:j,role:Q==="user"?"user":Q==="system"?"system":"assistant",content:typeof V.content=="string"?V.content:"",rawContent:typeof V.rawContent=="string"?V.rawContent:void 0,createdAt:typeof V.createdAt=="string"?V.createdAt:new Date().toISOString(),streaming:V.streaming===!0,...typeof V.variant=="string"?{variant:V.variant}:{},sequence:p()};if(m(Ne),Ne.rawContent)try{let rt=JSON.parse(Ne.rawContent),dt=(Zo=rt==null?void 0:rt.props)==null?void 0:Zo.artifactId;typeof dt=="string"&&de.add(dt)}catch{}y=null,E.current=null,le.delete(j),Te.delete(j)}else if(st==="error"){if(x.recoverable===!1&&x.error!=null&&x.error!==""){let V=typeof x.error=="string"?x.error:((Lo=x.error)==null?void 0:Lo.message)!=null?String(x.error.message):"Execution error";t({type:"error",error:new Error(V)});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(x.error instanceof Error)V=x.error;else if(st==="dispatch_error"){let j=(es=x.message)!=null?es:x.error;j!=null&&j!==""&&(V=new Error(String(j)))}else{let j=x.error;typeof j=="string"&&j!==""?V=new Error(j):j!=null&&typeof j=="object"&&Reflect.has(j,"message")&&(V=new Error(String((no=j.message)!=null?no:j)))}if(V){t({type:"error",error:V});let j=y;j&&j.streaming&&(j.streaming=!1,m(j)),t({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:L,value:ge}=await s.read();if(L)break;i+=a.decode(ge,{stream:!0});let Me=i.split(`
|
|
12
12
|
|
|
13
13
|
`);i=(hr=Me.pop())!=null?hr:"";for(let Le of Me){let He=Le.split(`
|
|
14
14
|
`),nt="message",Xe="",yt=null;for(let ce of He)ce.startsWith("event:")?nt=ce.replace("event:","").trim():ce.startsWith("data:")?Xe+=ce.replace("data:","").trim():ce.startsWith("id:")&&(yt=ce.slice(3).trim());let fe=()=>{yt!==null&&yt!==""&&t({type:"cursor",id:yt})};if(!Xe){fe();continue}let D;try{D=JSON.parse(Xe)}catch(ce){t({type:"error",error:ce instanceof Error?ce:new Error("Failed to parse chat stream payload")});continue}let ve=nt!=="message"?nt:(yr=D.type)!=null?yr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){E.current=y;let ce=await this.handleCustomSSEEvent(D,t,E,m,p,B);if(E.current&&E.current!==y&&(y=E.current),ce){fe();continue}}lt.push({payloadType:ve,payload:D}),Ve(),fe()}}Ve()}};function Ba(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`usr_${n}_${e}`}function fs(){let n=Date.now().toString(36),e=Math.random().toString(36).substring(2,10);return`ast_${n}_${e}`}var Da="[Image]";function $i(n){return{type:"text",text:n}}var Yu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],uh=["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"],jr=[...Yu,...uh];function mh(n){return Yu.includes(n)||n.startsWith("image/")}function Na(n){return mh(n.type)}async function Zu(n){return new Promise((e,t)=>{let r=new FileReader;r.onload=()=>{let o=r.result;Na(n)?e({type:"image",image:o,mimeType:n.type,alt:n.name}):e({type:"file",data:o,mimeType:n.type,filename:n.name})},r.onerror=()=>t(new Error("Failed to read file")),r.readAsDataURL(n)})}function em(n,e=jr,t=10*1024*1024){return e.includes(n.type)?n.size>t?{valid:!1,error:`File too large. Maximum size: ${Math.round(t/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${n.type}". Accepted types: ${e.join(", ")}`}}function gh(n){let e=n.split(".");return e.length>1?e.pop().toLowerCase():""}function tm(n,e){let t=gh(e).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[n]||t||"FILE"}Ui();var nm=16e3,fh=24e3,hh=4096,yh=1380533830;function bh(n){return n.byteLength>=44&&new DataView(n).getUint32(0,!1)===yh?new Uint8Array(n,44):new Uint8Array(n)}function vh(n){var r;let e=n.replace(/\/+$/,"");return/^wss?:\/\//i.test(e)?e:/^https?:\/\//i.test(e)?e.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${e}`}var Ys=class{constructor(e){this.config=e;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let e=(s=this.config)==null?void 0:s.agentId,t=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!e)throw new Error("Runtype voice requires an agentId");if(!t)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:nm,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(w=>w.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,g=new p({sampleRate:nm});g.state==="suspended"&&await g.resume().catch(()=>{}),this.captureContext=g;let h=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new hs(fh);if(o!==this.callGeneration){h.destroy(),c.getTracks().forEach(w=>w.stop()),g.close().catch(()=>{});return}this.playback=h,h.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vh(r)}/ws/agents/${encodeURIComponent(e)}/voice`,y=new WebSocket(m,["runtype.bearer",t]);y.binaryType="arraybuffer",this.ws=y,y.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(g,c,y,o))},y.onmessage=w=>this.handleMessage(w,o),y.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},y.onclose=w=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(w.code!==1e3){let E=w.code?` (code ${w.code})`:"";this.emitError(new Error(`Voice connection closed${E}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(e,t,r,o){let s=e.createMediaStreamSource(t);this.sourceNode=s;let a=e.createScriptProcessor(hh,1,1);this.processor=a,a.onaudioprocess=i=>{if(o!==this.callGeneration||r.readyState!==WebSocket.OPEN)return;let d=i.inputBuffer.getChannelData(0),c=new Int16Array(d.length);for(let p=0;p<d.length;p++){let g=Math.max(-1,Math.min(1,d[p]));c[p]=g<0?g*32768:g*32767}r.send(c.buffer)},s.connect(a),a.connect(e.destination)}handleMessage(e,t){var o,s;if(t!==this.callGeneration)return;if(e.data instanceof ArrayBuffer){this.handleAudioFrame(e.data,t);return}let r;try{r=JSON.parse(e.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(e,t){if(t!==this.callGeneration||!this.playback)return;let r=bh(e);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(e=>e.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}onTranscript(e){this.transcriptCallbacks.push(e)}onMetrics(e){this.metricsCallbacks.push(e)}emitStatus(e){this.statusCallbacks.forEach(t=>t(e))}emitError(e){this.errorCallbacks.forEach(t=>t(e))}emitTranscript(e,t,r){this.transcriptCallbacks.forEach(o=>o(e,t,r))}emitMetrics(e){this.metricsCallbacks.forEach(t=>t(e))}};var Uo=class{constructor(e={}){this.config=e;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(e=>e("connected"))}async startListening(){var e,t;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((e=this.config)==null?void 0:e.language)||"en-US",this.recognition.continuous=((t=this.config)==null?void 0:t.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(e=>e("idle"))}onResult(e){this.resultCallbacks.push(e)}onError(e){this.errorCallbacks.push(e)}onStatusChange(e){this.statusCallbacks.push(e)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(e=>e("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ys(n){switch(n.type){case"runtype":if(!n.runtype)throw new Error("Runtype voice provider requires configuration");return new Ys(n.runtype);case"browser":if(!Uo.isSupported())throw new Error("Browser speech recognition not supported");return new Uo(n.browser||{});case"custom":{let e=n.custom;if(!e)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let t=typeof e=="function"?e():e;if(!t||typeof t.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return t}default:throw new Error(`Unknown voice provider type: ${n.type}`)}}function rm(n){if((n==null?void 0:n.type)==="custom"&&n.custom)return ys({type:"custom",custom:n.custom});if((n==null?void 0:n.type)==="runtype"&&n.runtype)return ys({type:"runtype",runtype:n.runtype});if(Uo.isSupported())return ys({type:"browser",browser:(n==null?void 0:n.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function qi(n){try{return rm(n),!0}catch{return!1}}function Fa(n){var t;let e=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of e){let o=n.find(s=>s.name===r);if(o)return o}return(t=n.find(r=>r.lang.startsWith("en")))!=null?t:n[0]}var bs=class n{constructor(e={}){this.options=e;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(e,t){var a;if(!n.isSupported()){(a=t.onError)==null||a.call(t,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(e.text),s=r.getVoices();if(e.voice){let i=s.find(d=>d.name===e.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Fa(s));e.rate!==void 0&&(o.rate=e.rate),e.pitch!==void 0&&(o.pitch=e.pitch),o.onend=()=>{var i;return(i=t.onEnd)==null?void 0:i.call(t)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=t.onEnd)==null||c.call(t):(p=t.onError)==null||p.call(t,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=t.onStart)==null||i.call(t)},50)}pause(){n.isSupported()&&window.speechSynthesis.pause()}resume(){n.isSupported()&&window.speechSynthesis.resume()}stop(){n.isSupported()&&window.speechSynthesis.cancel()}};var Zs=class{constructor(e){this.resolveEngine=e;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var e,t;return(t=(e=this.engine)==null?void 0:e.supportsPause)!=null?t:!0}stateFor(e){return this.activeId===e?this.state:"idle"}activeMessageId(){return this.activeId}onChange(e){return this.listeners.add(e),()=>this.listeners.delete(e)}toggle(e,t){var r,o;if(this.activeId===e){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(e,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(e,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(e,t)}async play(e,t){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(e,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(t,{onStart:()=>{r===this.generation&&this.set(e,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var e;this.generation++,(e=this.engine)==null||e.stop(),this.set(null,"idle")}destroy(){var e,t;this.stop(),(t=(e=this.engine)==null?void 0:e.destroy)==null||t.call(e),this.engine=null,this.listeners.clear()}set(e,t){this.activeId=t==="idle"?null:e,this.state=t;for(let r of this.listeners)r(this.activeId,this.state)}};function zi(n){if(!n)return"";let e=wh(n);return om(e!==null?e:n)}function wh(n){let e=n.trim(),t=e.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(t&&(e=t[1].trim()),!e.startsWith("{"))return null;try{let r=JSON.parse(e);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function om(n){if(!n)return"";let e=n;return e=e.replace(/```[\s\S]*?```/g," "),e=e.replace(/~~~[\s\S]*?~~~/g," "),e=e.replace(/`([^`]+)`/g,"$1"),e=e.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),e=e.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),e=e.replace(/<\/?[a-zA-Z][^>]*>/g," "),e=e.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),e=e.replace(/^[ \t]*>[ \t]?/gm,""),e=e.replace(/^[ \t]*[-*+][ \t]+/gm,""),e=e.replace(/^[ \t]*\d+\.[ \t]+/gm,""),e=e.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),e=e.replace(/(\*\*|__)(.*?)\1/g,"$2"),e=e.replace(/(\*|_)(.*?)\1/g,"$2"),e=e.replace(/~~(.*?)~~/g,"$1"),e=e.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),e=e.replace(/[ \t]+/g," "),e=e.replace(/[ \t]*\n[ \t]*/g,`
|
|
15
15
|
`),e=e.replace(/\n{2,}/g,`
|
|
16
16
|
`),e.trim()}var cm=null;var ji=()=>cm?cm():Promise.resolve().then(()=>(lm(),im));var Th=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Eh(n,e){return Th.some(t=>n[t]!==e[t])}function Vi(n,e){let t=n instanceof Error?n:new Error(String(n));if(typeof e=="string")return e;if(typeof e=="function")return e(t);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return t.message?`${r}
|
|
17
17
|
|
|
18
|
-
_Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]}),um=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,mm=n=>cs(n)||n===zr,$a=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Zs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,p,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(cs(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(p=this.callbacks).onError)==null||g.call(p,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Js(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!t||!r||!this.config.clientToken||ji().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return qi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=bs.isSupported()?new bs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,p=(d=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&p&&g)return ji().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:y})=>{let w=new m({host:c,agentId:p,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new y(w,t,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ys(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,p,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=e.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Eh(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Js(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:g}=e,m={id:a!=null?a:t==="user"?Ba():t==="assistant"?fs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?Ba():o==="assistant"?fs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,p,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Ba(),s=fs();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Da,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){if(this.status==="resuming"||this.reconnecting)return;let w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!w){let E=Vi(y,this.config.errorMessage);if(E){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(y instanceof Error?(g=(p=this.callbacks).onError)==null||g.call(p,y):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=fs();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let g=Vi(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var p,g,h,m,y;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let E=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}E=w.body}else w instanceof ReadableStream&&(E=w);E?await this.connectStream(E,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(w){let E=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(y=(m=this.callbacks).onError)==null||y.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var p,g,h,m,y,w,E,B,T,I,M,P;let r=this.messages.find(C=>C.id===e.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,k=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(k.length===1){let q=typeof((E=k[0])==null?void 0:E.question)=="string"?k[0].question:"";q&&(a={[q]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([k,q])=>`${k}: ${Array.isArray(q)?q.join(", "):q}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((k,q)=>{let _=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!_)return;let R=C[_],O=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${q}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${q}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let k=await C.json().catch(()=>null);throw new Error((I=k==null?void 0:k.error)!=null?I:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let k=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,p,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var P,C,k,q,_,R,O;let m=(P=h.toolCall)==null?void 0:P.name,y=(C=h.toolCall)==null?void 0:C.id;if(!m||!y)return null;let w=`${e}:${y}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let E=this.markWebMcpToolRunning(h),B=(q=(k=h.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?q:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Di(),toolMessage:h,startedAt:E,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let I=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,T.signal),M;if(!I)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await I}catch(F){let Z=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return Z||(O=(R=this.callbacks).onError)==null||O.call(R,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(h,ea(Z?"Aborted by cancel()":um(F)),E),this.webMcpInflightKeys.delete(w),null}return T.signal.aborted?(this.markWebMcpToolComplete(h,ea("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(y=>y!==null),i.length===0)return;let h={};for(let y of i)h[y.resumeKey]=y.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${m.status}`)}for(let y of i)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((c=y.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(p=this.callbacks).onError)==null||g.call(p,h instanceof Error?h:new Error(String(h)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,ea("Aborted by cancel()"),y.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var y,w,E,B,T,I,M,P,C,k,q,_;let t=(y=e.agentMetadata)==null?void 0:y.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(E=e.toolCall)==null?void 0:E.id;if(!t){(T=(B=this.callbacks).onError)==null||T.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,p=(P=e.toolCall)==null?void 0:P.args,g=c?null:this.client.executeWebMcpToolCall(r,p,d),h="execute",m=a;try{let R;if(c?R=Di():g?R=await g:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ea("Aborted by cancel()"),a);return}let O=(k=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:r;h="resume",await this.resumeWithToolOutput(t,O,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,R,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let O=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(h==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(e,ea(O||d.aborted?"Aborted by cancel()":um(R)),a),O||(_=(q=this.callbacks).onError)==null||_.call(q,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(pm(),dm)).then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Vi(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=fs(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=zi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Fa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=zi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var p,g,h,m,y,w,E,B,T,I,M,P,C,k,q;if(s!==r)return o;let a={...o,...t};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,R=t.approval;a.approval={..._,...R,executionId:R.executionId||_.executionId,toolName:R.toolName||_.toolName,description:R.description||_.description,toolType:(m=R.toolType)!=null?m:_.toolType,reason:(y=R.reason)!=null?y:_.reason,parameters:(w=R.parameters)!=null?w:_.parameters}}let i=(E=t.toolCall)==null?void 0:E.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(T=t.toolCall)==null?void 0:T.id;if(i&&mm(i)&&d&&c&&((I=t.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let _=`${d}:${c}`,R=this.webMcpInflightKeys.has(_),O=this.webMcpResolvedKeys.has(_),F=(M=o.toolCall)==null?void 0:M.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&mm(F)&&((k=o.toolCall)==null?void 0:k.status)==="complete";(R||O||Z)&&(a.agentMetadata={...(q=a.agentMetadata)!=null?q:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var A=require("lucide"),Mh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ye=(n,e=24,t="currentColor",r=2)=>{let o=Mh[n];return o?kh(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kh(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ua={allowedTypes:jr,maxFileSize:10*1024*1024,maxFiles:4};function Lh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ph(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var ta=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ua.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ua.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ua.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ua.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let p=em(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let g=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Zu(c),h=Na(c)?URL.createObjectURL(c):null,m={id:Lh(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Na(e.file),r=v("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ph(e.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=v("span");c.textContent=tm(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var gm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function na(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];gm(s)&&gm(o)?t[r]=na(s,o):t[r]=o}return t}var Vr="min(440px, calc(100vw - 24px))",hm="440px",Ih={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:Vr,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)"},Bt={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:Ih,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 fm(n,e){if(!(!n&&!e))return n?e?na(n,e):n:e}function ym(n){var e,t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P;return n?{...Bt,...n,theme:fm(Bt.theme,n.theme),darkTheme:fm(Bt.darkTheme,n.darkTheme),launcher:{...Bt.launcher,...n.launcher,dock:{...(e=Bt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...n.copy},sendButton:{...Bt.sendButton,...n.sendButton},statusIndicator:{...Bt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,oe,de,Ae,$e,K,J,Se,Y,le;let C=(re=Bt.features)==null?void 0:re.artifacts,k=(oe=n.features)==null?void 0:oe.artifacts,q=(de=Bt.features)==null?void 0:de.scrollToBottom,_=(Ae=n.features)==null?void 0:Ae.scrollToBottom,R=($e=Bt.features)==null?void 0:$e.scrollBehavior,O=(K=n.features)==null?void 0:K.scrollBehavior,F=(J=Bt.features)==null?void 0:J.streamAnimation,Z=(Se=n.features)==null?void 0:Se.streamAnimation,ke=(Y=Bt.features)==null?void 0:Y.askUserQuestion,pe=(le=n.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&k===void 0?void 0:{...C,...k,layout:{...C==null?void 0:C.layout,...k==null?void 0:k.layout}},Pe=q===void 0&&_===void 0?void 0:{...q,..._},Ie=R===void 0&&O===void 0?void 0:{...R,...O},ie=F===void 0&&Z===void 0?void 0:{...F,...Z},he=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...n.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ie!==void 0?{streamAnimation:ie}:{},...he!==void 0?{askUserQuestion:he}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Bt.layout,...n.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(y=Bt.layout)==null?void 0:y.messages)==null?void 0:w.timestamp,...(B=(E=n.layout)==null?void 0:E.messages)==null?void 0:B.timestamp}},slots:{...(T=Bt.layout)==null?void 0:T.slots,...(I=n.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...n.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(P=n.markdown)==null?void 0:P.options}},messageActions:{...Bt.messageActions,...n.messageActions}}:Bt}var Rh={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"}},Wh={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"}},Hh={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:Vr,maxWidth:hm,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(n,r):r}function bm(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Bh(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function vm(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=vm(s,o):t[r]=o}return t}function Dh(n,e){return e?vm(n,e):n}function qo(n,e={}){var o,s,a,i,d,c,p,g,h,m,y,w,E;let t={palette:Rh,semantic:Wh,components:Hh},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(p=n==null?void 0:n.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(y=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Dh(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=Bh(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function wm(n){var w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me,X,lt,Ve,Ee,xe,Ze,jt,be,ue,xn,At,fn,hr,yr,qe,L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo;let e=bm(n),t={};for(let[Ce,Nr]of Object.entries(e)){let Qn=Ce.replace(/\./g,"-");t[`--persona-${Qn}`]=Nr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(T=t["--persona-semantic-colors-surface"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Z=t["--persona-components-voice-speaking-icon"])!=null?Z:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ke=t["--persona-components-approval-requested-background"])!=null?ke:t["--persona-surface"],t["--persona-approval-border"]=(pe=t["--persona-components-approval-requested-border"])!=null?pe:t["--persona-border"],t["--persona-approval-text"]=(ee=t["--persona-components-approval-requested-text"])!=null?ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Pe=t["--persona-components-approval-requested-shadow"])!=null?Pe:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Ie=t["--persona-components-approval-approve-background"])!=null?Ie:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ie=t["--persona-components-approval-deny-background"])!=null?ie:t["--persona-container"],t["--persona-attachment-image-bg"]=(he=t["--persona-components-attachment-image-background"])!=null?he:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(de=t["--persona-semantic-typography-fontSize"])!=null?de:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ae=t["--persona-semantic-typography-fontWeight"])!=null?Ae:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=($e=t["--persona-semantic-typography-lineHeight"])!=null?$e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(J=t["--persona-palette-radius-md"])!=null?J:"0.375rem",t["--persona-radius-lg"]=(Se=t["--persona-palette-radius-lg"])!=null?Se:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(Ye=(Te=t["--persona-components-launcher-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?Ye:"9999px",t["--persona-launcher-bg"]=(tt=t["--persona-components-launcher-background"])!=null?tt:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ht=t["--persona-components-launcher-border"])!=null?ht:t["--persona-border"],t["--persona-button-primary-bg"]=(ot=t["--persona-components-button-primary-background"])!=null?ot:t["--persona-primary"],t["--persona-button-primary-fg"]=(me=t["--persona-components-button-primary-foreground"])!=null?me:t["--persona-text-inverse"],t["--persona-button-radius"]=(lt=(X=t["--persona-components-button-primary-borderRadius"])!=null?X:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-panel-radius"]=(Ee=(Ve=t["--persona-components-panel-borderRadius"])!=null?Ve:t["--persona-radius-xl"])!=null?Ee:"0.75rem",t["--persona-panel-border"]=(xe=t["--persona-components-panel-border"])!=null?xe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(jt=(Ze=t["--persona-components-panel-shadow"])!=null?Ze:t["--persona-palette-shadows-xl"])!=null?jt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(be=t["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(xn=(ue=t["--persona-components-input-borderRadius"])!=null?ue:t["--persona-radius-lg"])!=null?xn:"0.5rem",t["--persona-message-user-radius"]=(fn=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?fn:"0.5rem",t["--persona-message-assistant-radius"]=(yr=(hr=t["--persona-components-message-assistant-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?yr:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(L=t["--persona-components-header-border"])!=null?L:t["--persona-divider"],t["--persona-header-icon-bg"]=(ge=t["--persona-components-header-iconBackground"])!=null?ge:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(He=t["--persona-components-header-subtitleForeground"])!=null?He:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(nt=t["--persona-components-header-actionIconForeground"])!=null?nt:t["--persona-muted"];let r=(Xe=n.components)==null?void 0:Xe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=n.components)==null?void 0:yt.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(D=t["--persona-components-introCard-borderRadius"])!=null?D:"1rem",t["--persona-intro-card-padding"]=(ve=t["--persona-components-introCard-padding"])!=null?ve:"1.5rem",t["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:t["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ge=t["--persona-components-input-background"])!=null?Ge:t["--persona-surface"],t["--persona-input-placeholder"]=(Pt=t["--persona-components-input-placeholder"])!=null?Pt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ht=t["--persona-components-message-user-shadow"])!=null?Ht:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Xt=t["--persona-components-message-assistant-background"])!=null?Xt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(en=t["--persona-components-message-assistant-border"])!=null?en:t["--persona-border"],t["--persona-message-assistant-shadow"]=(br=t["--persona-components-message-assistant-shadow"])!=null?br:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(rr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?rr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Kr=(or=t["--persona-components-scrollToBottom-foreground"])!=null?or:t["--persona-button-primary-fg"])!=null?Kr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Vt=t["--persona-components-scrollToBottom-border"])!=null?Vt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(sr=t["--persona-components-scrollToBottom-size"])!=null?sr:"40px",t["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(Hr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Hr:t["--persona-button-radius"])!=null?Bn:t["--persona-radius-full"])!=null?Ln:"9999px",t["--persona-scroll-to-bottom-shadow"]=(ar=(Dn=t["--persona-components-scrollToBottom-shadow"])!=null?Dn:t["--persona-palette-shadows-sm"])!=null?ar:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Gr=t["--persona-components-scrollToBottom-gap"])!=null?Gr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Qr=(Vn=t["--persona-components-scrollToBottom-fontSize"])!=null?Vn:t["--persona-palette-typography-fontSize-sm"])!=null?Qr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(St=t["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",t["--persona-tool-bubble-shadow"]=(wr=t["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(xr=t["--persona-components-reasoningBubble-shadow"])!=null?xr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Br=t["--persona-components-composer-shadow"])!=null?Br:"none",t["--persona-md-inline-code-bg"]=(ir=t["--persona-components-markdown-inlineCode-background"])!=null?ir:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Cr=(Co=t["--persona-components-markdown-link-foreground"])!=null?Co:t["--persona-accent"])!=null?Cr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Ao=t["--persona-components-markdown-codeBlock-background"])!=null?Ao:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Pn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Qo=t["--persona-components-markdown-codeBlock-textColor"])!=null?Qo:"inherit",t["--persona-md-table-header-bg"]=(Xr=t["--persona-components-markdown-table-headerBackground"])!=null?Xr:t["--persona-container"],t["--persona-md-table-border-color"]=(Dr=t["--persona-components-markdown-table-borderColor"])!=null?Dr:t["--persona-border"],t["--persona-md-hr-color"]=(Jr=t["--persona-components-markdown-hr-color"])!=null?Jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Yr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Yr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(So=t["--persona-components-markdown-blockquote-background"])!=null?So:"transparent",t["--persona-md-blockquote-text-color"]=(To=t["--persona-components-markdown-blockquote-textColor"])!=null?To:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zr=t["--persona-components-collapsibleWidget-container"])!=null?Zr:t["--persona-surface"],t["--cw-surface"]=(xt=t["--persona-components-collapsibleWidget-surface"])!=null?xt:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Fn=t["--persona-components-message-border"])!=null?Fn:t["--persona-border"];let p=n.components,g=p==null?void 0:p.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=p==null?void 0:p.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ce=y.toolbar;Ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,t["--persona-dropdown-bg"]=(Cn=t["--persona-dropdown-bg"])!=null?Cn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,t["--persona-dropdown-border"]=(Tt=t["--persona-dropdown-border"])!=null?Tt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Gn=t["--persona-dropdown-radius"])!=null?Gn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(On=t["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(y!=null&&y.tab){let Ce=y.tab;Ce.background&&(t["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(t["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(t["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(y!=null&&y.pane){let Ce=y.pane;if(Ce.toolbarBackground){let Nr=(eo=vs(n,Ce.toolbarBackground))!=null?eo:Ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nr}}return t}var Nh={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"}}},xm=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ki=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Fh=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ki()},Oh=n=>Fh(n),_h=n=>qo(n),$h=n=>{var t;let e=qo(void 0,{validate:!1});return qo({...n,palette:{...e.palette,colors:{...Nh.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},qa=n=>{let e=Oh(n),t=xm(n==null?void 0:n.theme),r=xm(n==null?void 0:n.darkTheme);return e==="dark"?$h(na(t!=null?t:{},r!=null?r:{})):_h(t)},Uh=n=>wm(n),ws=(n,e)=>{let t=qa(e),r=Uh(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Cm=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ki())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ki());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var Am=require("idiomorph"),za=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Am.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Sm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var ja={index:-1,draft:""};function Tm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ja}}}function Em(n,e){var t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=n.llmContent)==null?void 0:c.length)!=null?p:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(y=(m=n.toolCall)==null?void 0:m.status)!=null?y:"",(E=(w=n.toolCall)==null?void 0:w.name)!=null?E:"",(I=(T=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:T.length)!=null?I:0,(k=(C=(P=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:P[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?k:"",typeof((q=n.toolCall)==null?void 0:q.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(F=(O=(R=n.reasoning)==null?void 0:R.chunks)==null?void 0:O.length)!=null?F:0,(ee=(pe=(ke=(Z=n.reasoning)==null?void 0:Z.chunks)==null?void 0:ke[n.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(he=(ie=(Ie=(Pe=n.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?he:"",(oe=(re=n.contentParts)==null?void 0:re.length)!=null?oe:0,(de=n.stopReason)!=null?de:"",e].join("\0")}function Mm(){return new Map}function km(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Lm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Pm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Va(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Rr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function vo(n,e){return Rr(n)-n.scrollTop<=e}function Ka(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,p=t-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:t}:!e&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Ga(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function Im(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Rm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Wm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,wo=vn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qh=["pre","code","a","script","style"],Qa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ra.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ra.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ra.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ra.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ra.buffer}},zh=[{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"}],Bm=new Map;for(let n of zh)Bm.set(n.name,n);var xs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Bm.get(n))!=null?r:null},Xa=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
18
|
+
_Details: ${t.message}_`:r}var ea=n=>({isError:!0,content:[{type:"text",text:n}]}),um=(n,e="WebMCP tool execution failed.")=>n instanceof Error&&n.message?n.message:typeof n=="string"&&n?n:e,mm=n=>cs(n)||n===zr,$a=class{constructor(e={},t){this.config=e;this.callbacks=t;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.resumable=null;this.activeAssistantMessageId=null;this.reconnecting=!1;this.reconnectController=null;this.reconnectControllerPromise=null;this.executionStateTimer=null;this.artifacts=new Map;this.selectedArtifactId=null;this.webMcpInflightKeys=new Set;this.webMcpResolvedKeys=new Set;this.webMcpResolveControllers=new Set;this.webMcpEpoch=0;this.webMcpApprovalResolvers=new Map;this.webMcpApprovalSeq=0;this.webMcpAwaitBatches=new Map;this.voiceProvider=null;this.voiceActive=!1;this.voiceStatus="disconnected";this.pendingVoiceUserMessageId=null;this.pendingVoiceAssistantMessageId=null;this.ttsSpokenMessageIds=new Set;this.readAloud=new Zs(()=>this.createSpeechEngine());this.handleEvent=e=>{var t,r,o,s,a,i,d,c,p,g;if(e.type==="message"){this.upsertMessage(e.message),e.message.role==="assistant"&&!e.message.variant&&e.message.streaming&&(this.activeAssistantMessageId=e.message.id);let h=e.message.toolCall,m=!!(h!=null&&h.name)&&(cs(h.name)||h.name===zr&&((r=(t=this.config.features)==null?void 0:t.suggestReplies)==null?void 0:r.enabled)!==!1);((o=e.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(e.message),(s=e.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?e.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=e.message.agentMetadata.iteration):this.agentExecution={executionId:e.message.agentMetadata.executionId,agentId:"",agentName:(a=e.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=e.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(e.type==="cursor")this.trackCursor(e.id);else if(e.type==="status"){if(e.status==="idle"&&!e.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(e.status),e.status==="connecting")this.setStreaming(!0);else if(e.status==="idle"||e.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let h=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(e.status==="error"?this.agentExecution.status="error":h||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else e.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(g=(p=this.callbacks).onError)==null||g.call(p,e.error)):(e.type==="artifact_start"||e.type==="artifact_delta"||e.type==="artifact_update"||e.type==="artifact_complete")&&this.applyArtifactStreamEvent(e)};var r,o;this.messages=[...(r=e.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Js(e),this.wireDefaultWebMcpConfirm();for(let s of(o=e.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});e.initialSelectedArtifactId!=null&&(this.selectedArtifactId=e.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let e=this.config.textToSpeech;if((e==null?void 0:e.provider)!=="runtype"||e.createEngine)return;let t=(o=e.host)!=null?o:this.config.apiUrl,r=(c=(d=e.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!t||!r||!this.config.clientToken||ji().catch(()=>{})}setSSEEventCallback(e){this.client.setSSEEventCallback(e)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var e;return((e=this.agentExecution)==null?void 0:e.status)==="running"}isVoiceSupported(){var e;return qi((e=this.config.voiceRecognition)==null?void 0:e.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var e;return(e=this.voiceProvider)!=null&&e.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var e;(e=this.voiceProvider)!=null&&e.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var e,t,r;return(r=(t=(e=this.voiceProvider)==null?void 0:e.isBargeInActive)==null?void 0:t.call(e))!=null?r:!1}async deactivateBargeIn(){var e;(e=this.voiceProvider)!=null&&e.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let e=this.config.textToSpeech;if(e!=null&&e.createEngine)return e.createEngine();let t=bs.isSupported()?new bs({pickVoice:e==null?void 0:e.pickVoice}):null;if((e==null?void 0:e.provider)==="runtype"){let c=(r=e.host)!=null?r:this.config.apiUrl,p=(d=(i=e.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,g=this.config.clientToken,h=e.browserFallback!==!1;if(c&&p&&g)return ji().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:y})=>{let w=new m({host:c,agentId:p,clientToken:g,voice:e.voice,prebufferMs:e.prebufferMs,createPlaybackEngine:e.createPlaybackEngine});return h&&t?new y(w,t,{onFallback:E=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${E.message}`)}):w});if(h&&t)return g&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),t}return t}setupVoice(e){var t,r;try{let o=e||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=ys(o);let a=(r=((t=this.config.voiceRecognition)!=null?t:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,c)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:d,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!c});else{let p=this.injectMessage({role:"user",content:d,streaming:!1,voiceProcessing:!c});this.pendingVoiceUserMessageId=p.id}if(c){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:d,createdAt:new Date().toISOString(),streaming:!c,voiceProcessing:!c});else{let p=this.injectMessage({role:"assistant",content:d,streaming:!c,voiceProcessing:!c});this.pendingVoiceAssistantMessageId=p.id}c&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var d,c;(c=(d=this.config.voiceRecognition)==null?void 0:d.onMetrics)==null||c.call(d,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:a,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var d,c;this.voiceStatus=i,this.voiceActive=i==="listening",(c=(d=this.callbacks).onVoiceStatusChanged)==null||c.call(d,i)}),this.voiceProvider.connect()}catch(o){console.error("Failed to setup voice:",o)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(e){console.error("Failed to start voice:",e)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var t,r,o,s,a,i,d,c,p,g,h,m;if(!((t=this.config.voiceRecognition)!=null&&t.provider))return;let e=this.config.voiceRecognition.provider;switch(e.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=e.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=e.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=e.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=e.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(g=e.runtype)==null?void 0:g.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((h=e.browser)==null?void 0:h.language)||"en-US",continuous:(m=e.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:e.custom};default:return}}async initClientSession(){var e,t;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(t=(e=this.callbacks).onError)==null||t.call(e,r instanceof Error?r:new Error(String(r))),null}}setClientSession(e){if(this.clientSession=e,e.config.welcomeMessage&&this.messages.length===0){let t={id:`welcome-${Date.now()}`,role:"assistant",content:e.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(t)}}getClientSession(){var e;return(e=this.clientSession)!=null?e:this.client.getClientSession()}isSessionValid(){let e=this.getClientSession();return e?new Date<e.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(e,t){return this.client.submitMessageFeedback(e,t)}async submitCSATFeedback(e,t){return this.client.submitCSATFeedback(e,t)}async submitNPSFeedback(e,t){return this.client.submitNPSFeedback(e,t)}updateConfig(e){let t={...this.config,...e};if(!Eh(this.config,t)){this.config=t,this.client.updateConfig(t);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=t,this.client=new Js(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(e){this.handleEvent(e)}injectMessage(e){let{role:t,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:g}=e,m={id:a!=null?a:t==="user"?Ba():t==="assistant"?fs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:t,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...g!==void 0&&{rawContent:g}};return this.upsertMessage(m),m}injectAssistantMessage(e){return this.injectMessage({...e,role:"assistant"})}injectUserMessage(e){return this.injectMessage({...e,role:"user"})}injectSystemMessage(e){return this.injectMessage({...e,role:"system"})}injectMessageBatch(e){let t=[];for(let r of e){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:g=!1,voiceProcessing:h,rawContent:m}=r,w={id:d!=null?d:o==="user"?Ba():o==="assistant"?fs():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:o,content:s,createdAt:c!=null?c:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:g,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...h!==void 0&&{voiceProcessing:h},...m!==void 0&&{rawContent:m}};t.push(w)}return this.messages=this.sortMessages([...this.messages,...t]),this.callbacks.onMessagesChanged([...this.messages]),t}injectComponentDirective(e){let{component:t,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=e,c={text:o,component:t,props:r};return this.injectMessage({role:"assistant",content:o,rawContent:JSON.stringify(c),...s!==void 0&&{llmContent:s},...a!==void 0&&{id:a},...i!==void 0&&{createdAt:i},...d!==void 0&&{sequence:d}})}async sendMessage(e,t){var c,p,g,h,m;let r=e.trim();if(!r&&(!(t!=null&&t.contentParts)||t.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Ba(),s=fs();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||Da,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(t==null?void 0:t.viaVoice)||!1,...(t==null?void 0:t.contentParts)&&t.contentParts.length>0&&{contentParts:t.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(y){if(this.status==="resuming"||this.reconnecting)return;let w=y instanceof Error&&(y.name==="AbortError"||y.message.includes("aborted")||y.message.includes("abort"));if(!w){let E=Vi(y,this.config.errorMessage);if(E){let B={id:s,role:"assistant",createdAt:new Date().toISOString(),content:E,sequence:this.nextSequence()};this.appendMessage(B)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,w||(y instanceof Error?(g=(p=this.callbacks).onError)==null||g.call(p,y):(m=(h=this.callbacks).onError)==null||m.call(h,new Error(String(y))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let e=fs();this.activeAssistantMessageId=null,this.setStreaming(!0);let t=new AbortController;this.abortController=t;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:t.signal,assistantMessageId:e},this.handleEvent)}catch(c){if(this.status==="resuming"||this.reconnecting)return;let p=c instanceof Error&&(c.name==="AbortError"||c.message.includes("aborted")||c.message.includes("abort"));if(!p){let g=Vi(c,this.config.errorMessage);if(g){let h={id:e,role:"assistant",createdAt:new Date().toISOString(),content:g,sequence:this.nextSequence()};this.appendMessage(h)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(c instanceof Error?(a=(s=this.callbacks).onError)==null||a.call(s,c):(d=(i=this.callbacks).onError)==null||d.call(i,new Error(String(c))))}}async connectStream(e,t){var s,a,i;if(this.streaming&&!(t!=null&&t.allowReentry))return;t!=null&&t.allowReentry||(s=this.abortController)==null||s.abort(),t!=null&&t.preserveAssistantId&&t.assistantMessageId&&(this.activeAssistantMessageId=t.assistantMessageId);let r=t!=null&&t.preserveAssistantId?t.assistantMessageId:void 0,o=!1;for(let d of this.messages)d.streaming&&d.id!==r&&(d.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(e,this.handleEvent,t==null?void 0:t.assistantMessageId,t==null?void 0:t.seedContent)}catch(d){if(this.status==="resuming"||this.reconnecting)return;this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(i=(a=this.callbacks).onError)==null||i.call(a,d instanceof Error?d:new Error(String(d)))}}wireDefaultWebMcpConfirm(){let e=this.config.webmcp;(e==null?void 0:e.enabled)===!0&&!e.onConfirm&&this.client.setWebMcpConfirmHandler(t=>this.requestWebMcpApproval(t))}requestWebMcpApproval(e){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,e))===!0)return Promise.resolve(!0)}catch{}let t={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:e.toolName,toolType:"webmcp",description:(a=e.description)!=null?a:`Allow the assistant to run ${e.toolName}?`,parameters:e.args},r=`approval-${t.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:t}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(e,t){let r=this.webMcpApprovalResolvers.get(e);if(!r)return;this.webMcpApprovalResolvers.delete(e);let o=this.messages.find(s=>s.id===e);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:t,resolvedAt:Date.now()}}),r(t==="approved")}async resolveApproval(e,t,r){var p,g,h,m,y;let o=`approval-${e.id}`,s={...e,status:t,resolvedAt:Date.now()},a=this.messages.find(w=>w.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(g=this.abortController)==null||g.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let w;if(c?w=await c({approvalId:e.id,executionId:e.executionId,agentId:e.agentId,toolName:e.toolName},t,r):w=await this.client.resolveApproval({agentId:e.agentId,executionId:e.executionId,approvalId:e.id},t),w){let E=null;if(w instanceof Response){if(!w.ok){let B=await w.json().catch(()=>null);throw new Error((h=B==null?void 0:B.error)!=null?h:`Approval request failed: ${w.status}`)}E=w.body}else w instanceof ReadableStream&&(E=w);E?await this.connectStream(E,{allowReentry:!0}):(t==="denied"&&this.appendMessage({id:`denial-${e.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(w){let E=w instanceof Error&&(w.name==="AbortError"||w.message.includes("aborted")||w.message.includes("abort"));this.setStreaming(!1),this.abortController=null,E||(y=(m=this.callbacks).onError)==null||y.call(m,w instanceof Error?w:new Error(String(w)))}}persistAskUserQuestionProgress(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:t.answers,askUserQuestionIndex:t.currentIndex}})}markAskUserQuestionResolved(e,t){let r=this.messages.find(o=>o.id===e.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...t?{askUserQuestionAnswers:t}:{}}})}async resolveAskUserQuestion(e,t){var p,g,h,m,y,w,E,B,T,I,M,P;let r=this.messages.find(C=>C.id===e.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(g=e.agentMetadata)==null?void 0:g.executionId,s=(h=e.toolCall)==null?void 0:h.name;if(!o||!s){(y=(m=this.callbacks).onError)==null||y.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof t=="string"?void 0:t;if(a===void 0&&typeof t=="string"){let C=(w=e.toolCall)==null?void 0:w.args,k=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(k.length===1){let q=typeof((E=k[0])==null?void 0:E.question)=="string"?k[0].question:"";q&&(a={[q]:t})}}this.markAskUserQuestionResolved(e,a),(B=this.abortController)==null||B.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=e.toolCall.id,d=(T=e.toolCall)==null?void 0:T.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof t=="string"?t:Object.entries(t).map(([k,q])=>`${k}: ${Array.isArray(q)?q.join(", "):q}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((k,q)=>{let _=typeof(k==null?void 0:k.question)=="string"?k.question:"";if(!_)return;let R=C[_],O=Array.isArray(R)?R.join(", "):typeof R=="string"?R:"";this.appendMessage({id:`ask-user-q-${i}-${q}`,role:"assistant",content:_,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${q}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:t});if(!C.ok){let k=await C.json().catch(()=>null);throw new Error((I=k==null?void 0:k.error)!=null?I:`Resume failed: ${C.status}`)}C.body?await this.connectStream(C.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(C){let k=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,k||(P=(M=this.callbacks).onError)==null||P.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(e){var s,a;let t=(s=e.agentMetadata)==null?void 0:s.executionId,r=(a=e.toolCall)==null?void 0:a.id;if(!t||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(e)});return}let o=this.webMcpAwaitBatches.get(t);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(t,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(e))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let e=this.webMcpEpoch;queueMicrotask(()=>{if(e===this.webMcpEpoch)for(let t of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(t)})}flushWebMcpAwaitBatch(e){let t=this.webMcpAwaitBatches.get(e);if(!t)return;this.webMcpAwaitBatches.delete(e);let{snapshots:r}=t;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(e,r)}resolveWebMcpToolStartedAt(e){var o,s;let t=this.messages.find(a=>a.id===e.id),r=[(o=t==null?void 0:t.toolCall)==null?void 0:o.startedAt,(s=e.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(e){var r,o;if(((r=e.toolCall)==null?void 0:r.name)!==zr)return!1;let t=this.messages.find(s=>s.id===e.id);return((o=(t!=null?t:e).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(e){let t=this.resolveWebMcpToolStartedAt(e);return this.upsertMessage({...e,streaming:!0,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1},toolCall:e.toolCall?{...e.toolCall,status:"running",startedAt:t,completedAt:void 0,duration:void 0,durationMs:void 0}:e.toolCall}),t}markWebMcpToolComplete(e,t,r,o=Date.now(),s){this.messages.some(a=>a.id===e.id)&&this.upsertMessage({...e,streaming:!1,agentMetadata:{...e.agentMetadata,awaitingLocalTool:!1,...s},toolCall:e.toolCall?{...e.toolCall,status:"complete",result:t,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:e.toolCall})}async resolveWebMcpToolCallBatch(e,t){var d,c,p,g;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(t.map(async h=>{var P,C,k,q,_,R,O;let m=(P=h.toolCall)==null?void 0:P.name,y=(C=h.toolCall)==null?void 0:C.id;if(!m||!y)return null;let w=`${e}:${y}`;if(this.webMcpInflightKeys.has(w)||this.webMcpResolvedKeys.has(w)||this.isSuggestRepliesAlreadyResolved(h))return null;this.webMcpInflightKeys.add(w),r.push(w);let E=this.markWebMcpToolRunning(h),B=(q=(k=h.agentMetadata)==null?void 0:k.webMcpToolCallId)!=null?q:m;if(m===zr)return{dedupeKey:w,resumeKey:B,output:Di(),toolMessage:h,startedAt:E,completedAt:Date.now()};let T=new AbortController;this.webMcpResolveControllers.add(T),o.push(T);let I=this.client.executeWebMcpToolCall(m,(_=h.toolCall)==null?void 0:_.args,T.signal),M;if(!I)M={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{M=await I}catch(F){let Z=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return Z||(O=(R=this.callbacks).onError)==null||O.call(R,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(h,ea(Z?"Aborted by cancel()":um(F)),E),this.webMcpInflightKeys.delete(w),null}return T.signal.aborted?(this.markWebMcpToolComplete(h,ea("Aborted by cancel()"),E),this.webMcpInflightKeys.delete(w),null):{dedupeKey:w,resumeKey:B,output:M,toolMessage:h,startedAt:E,completedAt:Date.now()}})),i=[];try{if(i=a.filter(y=>y!==null),i.length===0)return;let h={};for(let y of i)h[y.resumeKey]=y.output;let m=await this.client.resumeFlow(e,h,{signal:s.signal});if(!m.ok){let y=await m.json().catch(()=>null);throw new Error((d=y==null?void 0:y.error)!=null?d:`Resume failed: ${m.status}`)}for(let y of i)this.webMcpResolvedKeys.add(y.dedupeKey),this.markWebMcpToolComplete(y.toolMessage,y.output,y.startedAt,y.completedAt,((c=y.toolMessage.toolCall)==null?void 0:c.name)===zr?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(h){if(!(h instanceof Error&&(h.name==="AbortError"||h.message.includes("aborted")||h.message.includes("abort"))))(g=(p=this.callbacks).onError)==null||g.call(p,h instanceof Error?h:new Error(String(h)));else for(let y of i)this.markWebMcpToolComplete(y.toolMessage,ea("Aborted by cancel()"),y.startedAt)}finally{for(let h of r)this.webMcpInflightKeys.delete(h);for(let h of o)this.webMcpResolveControllers.delete(h);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(e){var y,w,E,B,T,I,M,P,C,k,q,_;let t=(y=e.agentMetadata)==null?void 0:y.executionId,r=(w=e.toolCall)==null?void 0:w.name,o=(E=e.toolCall)==null?void 0:E.id;if(!t){(T=(B=this.callbacks).onError)==null||T.call(B,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let R=`${t}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(R)||this.webMcpResolvedKeys.has(R))return;this.webMcpInflightKeys.add(R);try{await this.resumeWithToolOutput(t,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(R)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(R)}return}let s=`${t}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(e))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(e),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===zr,p=(P=e.toolCall)==null?void 0:P.args,g=c?null:this.client.executeWebMcpToolCall(r,p,d),h="execute",m=a;try{let R;if(c?R=Di():g?R=await g:R={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),d.aborted){this.markWebMcpToolComplete(e,ea("Aborted by cancel()"),a);return}let O=(k=(C=e.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?k:r;h="resume",await this.resumeWithToolOutput(t,O,R,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(e,R,a,m,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(R){let O=R instanceof Error&&(R.name==="AbortError"||R.message.includes("aborted")||R.message.includes("abort"));(h==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(e,ea(O||d.aborted?"Aborted by cancel()":um(R)),a),O||(_=(q=this.callbacks).onError)==null||_.call(q,R instanceof Error?R:new Error(String(R)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(e,t,r,o){var a,i;let s=await this.client.resumeFlow(e,{[t]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let e of this.webMcpResolveControllers)e.abort();this.webMcpResolveControllers.clear();for(let e of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(e,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var e;(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var e;this.stopSpeaking(),(e=this.abortController)==null||e.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(e){return this.artifacts.get(e)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(e){this.selectedArtifactId=e,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(e){var o;let t=e.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(e.artifactType==="markdown"){let s={id:t,artifactType:"markdown",title:e.title,status:"complete",markdown:e.content};return this.artifacts.set(t,s),this.selectedArtifactId=t,this.emitArtifactsState(),s}let r={id:t,artifactType:"component",title:e.title,status:"complete",component:e.component,props:(o=e.props)!=null?o:{}};return this.artifacts.set(t,r),this.selectedArtifactId=t,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var e,t;(t=(e=this.callbacks).onArtifactsState)==null||t.call(e,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(e){var t,r;switch(e.type){case"artifact_start":{e.artifactType==="markdown"?this.artifacts.set(e.id,{id:e.id,artifactType:"markdown",title:e.title,status:"streaming",markdown:""}):this.artifacts.set(e.id,{id:e.id,artifactType:"component",title:e.title,status:"streaming",component:(t=e.component)!=null?t:"",props:{}}),this.selectedArtifactId=e.id;break}case"artifact_delta":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+e.artDelta);break}case"artifact_update":{let o=this.artifacts.get(e.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...e.props},e.component&&(o.component=e.component));break}case"artifact_complete":{let o=this.artifacts.get(e.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(e){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(e.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(e,t=null){this.artifacts.clear();for(let r of e)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=t,this.emitArtifactsState()}trackCursor(e){var o,s;let t=(o=this.agentExecution)==null?void 0:o.executionId;if(!t||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:t,lastEventId:e,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var e;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((e=this.abortController)==null?void 0:e.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(e=>{var t,r,o;return((t=e.agentMetadata)==null?void 0:t.awaitingLocalTool)===!0&&((r=e.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||e.variant==="approval"&&((o=e.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var e,t;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(t=(e=this.callbacks).onReconnect)==null||t.call(e,{phase:"paused",handle:this.resumable}),this.setStreaming(!0),this.setStatus("resuming"),this.loadReconnectController().then(r=>{this.reconnecting&&this.resumable&&r.begin()}))}loadReconnectController(){return this.reconnectController?Promise.resolve(this.reconnectController):(this.reconnectControllerPromise||(this.reconnectControllerPromise=Promise.resolve().then(()=>(pm(),dm)).then(({createReconnectController:e})=>{let t=e(this.buildReconnectHost());return this.reconnectController=t,t})),this.reconnectControllerPromise)}buildReconnectHost(){let e=this;return{get config(){return e.config},getResumable:()=>e.resumable,clearResumable:()=>e.clearResumable(),getStatus:()=>e.status,setStatus:t=>e.setStatus(t),setStreaming:t=>e.setStreaming(t),setReconnecting:t=>{e.reconnecting=t},setAbortController:t=>{e.abortController=t},getMessages:()=>e.messages,notifyMessagesChanged:()=>e.callbacks.onMessagesChanged([...e.messages]),resumeConnect:(t,r,o)=>e.connectStream(t,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:t=>e.appendMessage(t),nextSequence:()=>e.nextSequence(),emitReconnect:t=>{var r,o;return(o=(r=e.callbacks).onReconnect)==null?void 0:o.call(r,t)},buildErrorContent:t=>Vi(new Error(t),e.config.errorMessage),onError:t=>{var r,o;return(o=(r=e.callbacks).onError)==null?void 0:o.call(r,t)}}}reconnectNow(){var e;if(this.reconnecting){(e=this.reconnectController)==null||e.wake();return}this.beginReconnect()}resumeFromHandle(e){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let t=this.reopenTrailingAssistant();t||(t=fs(),this.appendMessage({id:t,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=t,this.agentExecution||(this.agentExecution={executionId:e.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:e.executionId,lastEventId:e.after,assistantMessageId:t,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(t.role==="assistant"&&!t.variant)return t.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),t.id;if(t.role==="user")break}return null}teardownReconnect(){var e;this.reconnecting=!1,(e=this.reconnectController)==null||e.teardown(),this.clearResumable()}clearResumable(){var t,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let e=this.resumable!==null;this.resumable=null,e&&((r=(t=this.config).onExecutionState)==null||r.call(t,null))}notifyExecutionState(e){let t=this.config.onExecutionState;if(t){if(e){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),t(this.resumable);return}this.executionStateTimer||(this.executionStateTimer=setTimeout(()=>{var r,o;this.executionStateTimer=null,(o=(r=this.config).onExecutionState)==null||o.call(r,this.resumable)},500))}}getResumableHandle(){return this.resumable}setStatus(e){this.status!==e&&(this.status=e,this.callbacks.onStatusChanged(e))}setStreaming(e){if(this.streaming===e)return;let t=this.streaming;this.streaming=e,this.callbacks.onStreamingChanged(e),t&&!e&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let e=this.config.textToSpeech;if(!(e!=null&&e.enabled)||!(!e.provider||e.provider==="browser"||e.provider==="runtype"&&e.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=zi(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:e.voice,rate:e.rate,pitch:e.pitch})}static pickBestVoice(e){return Fa(e)}toggleReadAloud(e){let t=this.messages.find(s=>s.id===e);if(!t||t.role!=="assistant")return;let r=zi(t.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(e,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(e){return this.readAloud.stateFor(e)}onReadAloudChange(e){return this.readAloud.onChange(e)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(e){let t=this.ensureSequence(e);this.messages=this.sortMessages([...this.messages,t]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(e){let t=this.ensureSequence(e),r=this.messages.findIndex(o=>o.id===t.id);if(r===-1){this.appendMessage(t);return}this.messages=this.messages.map((o,s)=>{var p,g,h,m,y,w,E,B,T,I,M,P,C,k,q;if(s!==r)return o;let a={...o,...t};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&t.agentMetadata&&(a.agentMetadata={...t.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((g=o.agentMetadata)==null?void 0:g.suggestRepliesResolved)===!0&&t.agentMetadata&&(a.agentMetadata={...(h=a.agentMetadata)!=null?h:t.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&t.approval&&o.approval.id===t.approval.id){let _=o.approval,R=t.approval;a.approval={..._,...R,executionId:R.executionId||_.executionId,toolName:R.toolName||_.toolName,description:R.description||_.description,toolType:(m=R.toolType)!=null?m:_.toolType,reason:(y=R.reason)!=null?y:_.reason,parameters:(w=R.parameters)!=null?w:_.parameters}}let i=(E=t.toolCall)==null?void 0:E.name,d=(B=t.agentMetadata)==null?void 0:B.executionId,c=(T=t.toolCall)==null?void 0:T.id;if(i&&mm(i)&&d&&c&&((I=t.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let _=`${d}:${c}`,R=this.webMcpInflightKeys.has(_),O=this.webMcpResolvedKeys.has(_),F=(M=o.toolCall)==null?void 0:M.name,Z=((P=o.agentMetadata)==null?void 0:P.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&mm(F)&&((k=o.toolCall)==null?void 0:k.status)==="complete";(R||O||Z)&&(a.agentMetadata={...(q=a.agentMetadata)!=null?q:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(e){return e.sequence!==void 0?{...e}:{...e,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(e){return[...e].sort((t,r)=>{var d,c;let o=new Date(t.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=t.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:t.id.localeCompare(r.id)})}};var A=require("lucide"),Mh={activity:A.Activity,"arrow-down":A.ArrowDown,"arrow-up":A.ArrowUp,"arrow-up-right":A.ArrowUpRight,bot:A.Bot,"chevron-down":A.ChevronDown,"chevron-up":A.ChevronUp,"chevron-right":A.ChevronRight,"chevron-left":A.ChevronLeft,check:A.Check,clipboard:A.Clipboard,"clipboard-copy":A.ClipboardCopy,copy:A.Copy,file:A.File,"file-code":A.FileCode,"file-spreadsheet":A.FileSpreadsheet,"file-text":A.FileText,"image-plus":A.ImagePlus,loader:A.Loader,"loader-circle":A.LoaderCircle,mic:A.Mic,paperclip:A.Paperclip,"refresh-cw":A.RefreshCw,search:A.Search,send:A.Send,"shield-alert":A.ShieldAlert,"shield-check":A.ShieldCheck,"shield-x":A.ShieldX,square:A.Square,"thumbs-down":A.ThumbsDown,"thumbs-up":A.ThumbsUp,upload:A.Upload,"volume-2":A.Volume2,x:A.X,user:A.User,mail:A.Mail,phone:A.Phone,calendar:A.Calendar,clock:A.Clock,building:A.Building,"map-pin":A.MapPin,lock:A.Lock,key:A.Key,"credit-card":A.CreditCard,"at-sign":A.AtSign,hash:A.Hash,globe:A.Globe,link:A.Link,"circle-check":A.CircleCheck,"circle-x":A.CircleX,"triangle-alert":A.TriangleAlert,info:A.Info,ban:A.Ban,shield:A.Shield,"arrow-left":A.ArrowLeft,"arrow-right":A.ArrowRight,"external-link":A.ExternalLink,ellipsis:A.Ellipsis,"ellipsis-vertical":A.EllipsisVertical,menu:A.Menu,house:A.House,plus:A.Plus,minus:A.Minus,pencil:A.Pencil,trash:A.Trash,"trash-2":A.Trash2,save:A.Save,download:A.Download,share:A.Share,funnel:A.Funnel,settings:A.Settings,"rotate-cw":A.RotateCw,maximize:A.Maximize,minimize:A.Minimize,"shopping-cart":A.ShoppingCart,"shopping-bag":A.ShoppingBag,package:A.Package,truck:A.Truck,tag:A.Tag,gift:A.Gift,receipt:A.Receipt,wallet:A.Wallet,store:A.Store,"dollar-sign":A.DollarSign,percent:A.Percent,play:A.Play,pause:A.Pause,"volume-x":A.VolumeX,camera:A.Camera,image:A.Image,film:A.Film,headphones:A.Headphones,"message-circle":A.MessageCircle,"message-square":A.MessageSquare,bell:A.Bell,heart:A.Heart,star:A.Star,eye:A.Eye,"eye-off":A.EyeOff,bookmark:A.Bookmark,"calendar-days":A.CalendarDays,history:A.History,timer:A.Timer,folder:A.Folder,"folder-open":A.FolderOpen,files:A.Files,sparkles:A.Sparkles,zap:A.Zap,sun:A.Sun,moon:A.Moon,flag:A.Flag,monitor:A.Monitor,smartphone:A.Smartphone},ye=(n,e=24,t="currentColor",r=2)=>{let o=Mh[n];return o?kh(o,e,t,r):(console.warn(`Lucide icon "${n}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function kh(n,e,t,r){if(!Array.isArray(n))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(e)),o.setAttribute("height",String(e)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",t),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),n.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var Ua={allowedTypes:jr,maxFileSize:10*1024*1024,maxFiles:4};function Lh(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Ph(n){return n==="application/pdf"||n.startsWith("text/")||n.includes("word")?"file-text":n.includes("excel")||n.includes("spreadsheet")?"file-spreadsheet":n==="application/json"?"file-code":"file"}var ta=class n{constructor(e={}){this.attachments=[];this.previewsContainer=null;var t,r,o;this.config={allowedTypes:(t=e.allowedTypes)!=null?t:Ua.allowedTypes,maxFileSize:(r=e.maxFileSize)!=null?r:Ua.maxFileSize,maxFiles:(o=e.maxFiles)!=null?o:Ua.maxFiles,onFileRejected:e.onFileRejected,onAttachmentsChange:e.onAttachmentsChange}}setPreviewsContainer(e){this.previewsContainer=e}updateConfig(e){e.allowedTypes!==void 0&&(this.config.allowedTypes=e.allowedTypes.length>0?e.allowedTypes:Ua.allowedTypes),e.maxFileSize!==void 0&&(this.config.maxFileSize=e.maxFileSize),e.maxFiles!==void 0&&(this.config.maxFiles=e.maxFiles),e.onFileRejected!==void 0&&(this.config.onFileRejected=e.onFileRejected),e.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=e.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(e=>e.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(e){!e||e.length===0||await this.handleFiles(Array.from(e))}async handleFiles(e){var t,r,o,s,a,i,d;if(e.length){for(let c of e){if(this.attachments.length>=this.config.maxFiles){(r=(t=this.config).onFileRejected)==null||r.call(t,c,"count");continue}let p=em(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let g=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,g);continue}try{let g=await Zu(c),h=Na(c)?URL.createObjectURL(c):null,m={id:Lh(),file:c,previewUrl:h,contentPart:g};this.attachments.push(m),this.renderPreview(m)}catch(g){console.error("[AttachmentManager] Failed to process file:",g)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(e){var s,a,i;let t=this.attachments.findIndex(d=>d.id===e);if(t===-1)return;let r=this.attachments[t];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(t,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${e}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var e,t;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(t=(e=this.config).onAttachmentsChange)==null||t.call(e,this.getAttachments())}renderPreview(e){if(!this.previewsContainer)return;let t=Na(e.file),r=v("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",e.id),r.style.width="48px",r.style.height="48px",t&&e.previewUrl){let a=v("img");a.src=e.previewUrl,a.alt=e.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=v("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=Ph(e.file.type),d=ye(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=v("span");c.textContent=tm(e.file.type,e.file.name),c.style.fontSize="8px",c.style.fontWeight="600",c.style.color="var(--persona-muted, #6b7280)",c.style.textTransform="uppercase",c.style.lineHeight="1",a.appendChild(c),r.appendChild(a)}let o=v("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=ye("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(e.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(e,t){return new n({allowedTypes:e==null?void 0:e.allowedTypes,maxFileSize:e==null?void 0:e.maxFileSize,maxFiles:e==null?void 0:e.maxFiles,onFileRejected:e==null?void 0:e.onFileRejected,onAttachmentsChange:t})}};var gm=n=>typeof n=="object"&&n!==null&&!Array.isArray(n);function na(n,e){if(!n)return e;if(!e)return n;let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];gm(s)&&gm(o)?t[r]=na(s,o):t[r]=o}return t}var Vr="min(440px, calc(100vw - 24px))",hm="440px",Ih={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:Vr,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)"},Bt={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:Ih,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 fm(n,e){if(!(!n&&!e))return n?e?na(n,e):n:e}function ym(n){var e,t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P;return n?{...Bt,...n,theme:fm(Bt.theme,n.theme),darkTheme:fm(Bt.darkTheme,n.darkTheme),launcher:{...Bt.launcher,...n.launcher,dock:{...(e=Bt.launcher)==null?void 0:e.dock,...(t=n.launcher)==null?void 0:t.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=n.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...n.copy},sendButton:{...Bt.sendButton,...n.sendButton},statusIndicator:{...Bt.statusIndicator,...n.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...n.voiceRecognition},features:(()=>{var re,oe,de,Ae,$e,K,J,Se,Y,le;let C=(re=Bt.features)==null?void 0:re.artifacts,k=(oe=n.features)==null?void 0:oe.artifacts,q=(de=Bt.features)==null?void 0:de.scrollToBottom,_=(Ae=n.features)==null?void 0:Ae.scrollToBottom,R=($e=Bt.features)==null?void 0:$e.scrollBehavior,O=(K=n.features)==null?void 0:K.scrollBehavior,F=(J=Bt.features)==null?void 0:J.streamAnimation,Z=(Se=n.features)==null?void 0:Se.streamAnimation,ke=(Y=Bt.features)==null?void 0:Y.askUserQuestion,pe=(le=n.features)==null?void 0:le.askUserQuestion,ee=C===void 0&&k===void 0?void 0:{...C,...k,layout:{...C==null?void 0:C.layout,...k==null?void 0:k.layout}},Pe=q===void 0&&_===void 0?void 0:{...q,..._},Ie=R===void 0&&O===void 0?void 0:{...R,...O},ie=F===void 0&&Z===void 0?void 0:{...F,...Z},he=ke===void 0&&pe===void 0?void 0:{...ke,...pe,styles:{...ke==null?void 0:ke.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...n.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...ee!==void 0?{artifacts:ee}:{},...ie!==void 0?{streamAnimation:ie}:{},...he!==void 0?{askUserQuestion:he}:{}}})(),suggestionChips:(s=n.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...n.suggestionChipsConfig},layout:{...Bt.layout,...n.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=n.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=n.layout)==null?void 0:c.messages,avatar:{...(g=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:g.avatar,...(m=(h=n.layout)==null?void 0:h.messages)==null?void 0:m.avatar},timestamp:{...(w=(y=Bt.layout)==null?void 0:y.messages)==null?void 0:w.timestamp,...(B=(E=n.layout)==null?void 0:E.messages)==null?void 0:B.timestamp}},slots:{...(T=Bt.layout)==null?void 0:T.slots,...(I=n.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...n.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(P=n.markdown)==null?void 0:P.options}},messageActions:{...Bt.messageActions,...n.messageActions}}:Bt}var Rh={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"}},Wh={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"}},Hh={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:Vr,maxWidth:hm,height:"600px",maxHeight:"calc(100vh - 80px)",borderRadius:"palette.radius.xl",shadow:"palette.shadows.xl"},header:{background:"palette.colors.primary.500",border:"palette.colors.primary.600",borderRadius:"palette.radius.xl palette.radius.xl 0 0",padding:"semantic.spacing.md",iconBackground:"palette.colors.primary.600",iconForeground:"palette.colors.primary.50",titleForeground:"palette.colors.primary.50",subtitleForeground:"palette.colors.primary.200",actionIconForeground:"palette.colors.primary.200"},message:{user:{background:"palette.colors.primary.500",text:"palette.colors.primary.50",borderRadius:"palette.radius.lg",shadow:"palette.shadows.sm"},assistant:{background:"palette.colors.gray.50",text:"palette.colors.gray.900",borderRadius:"palette.radius.lg",border:"palette.colors.gray.200",shadow:"palette.shadows.sm"},border:"semantic.colors.border"},introCard:{background:"semantic.colors.surface",borderRadius:"palette.radius.2xl",padding:"semantic.spacing.lg",shadow:"0 5px 15px rgba(15, 23, 42, 0.08)"},toolBubble:{shadow:"palette.shadows.sm"},reasoningBubble:{shadow:"palette.shadows.sm"},composer:{shadow:"palette.shadows.none"},markdown:{inlineCode:{background:"palette.colors.gray.50",foreground:"palette.colors.gray.900"},link:{foreground:"palette.colors.primary.600"},prose:{fontFamily:"inherit"},codeBlock:{background:"semantic.colors.container",borderColor:"semantic.colors.border",textColor:"inherit"},table:{headerBackground:"semantic.colors.container",borderColor:"semantic.colors.border"},hr:{color:"semantic.colors.divider"},blockquote:{borderColor:"palette.colors.gray.900",background:"transparent",textColor:"palette.colors.gray.500"}},collapsibleWidget:{container:"palette.colors.gray.50",surface:"semantic.colors.surface",border:"semantic.colors.border"},voice:{recording:{indicator:"palette.colors.error.500",background:"palette.colors.error.50",border:"palette.colors.error.200"},processing:{icon:"palette.colors.primary.500",background:"palette.colors.primary.50"},speaking:{icon:"palette.colors.success.500"}},approval:{requested:{background:"semantic.colors.surface",border:"semantic.colors.border",text:"palette.colors.gray.900",shadow:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)"},approve:{background:"semantic.colors.primary",foreground:"semantic.colors.textInverse",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"},deny:{background:"semantic.colors.container",foreground:"semantic.colors.text",borderRadius:"palette.radius.md",padding:"semantic.spacing.sm"}},attachment:{image:{background:"palette.colors.gray.100",border:"palette.colors.gray.200"}},scrollToBottom:{background:"components.button.primary.background",foreground:"components.button.primary.foreground",border:"semantic.colors.primary",size:"40px",borderRadius:"palette.radius.full",shadow:"palette.shadows.sm",padding:"0.5rem 0.875rem",gap:"0.5rem",fontSize:"0.875rem",iconSize:"14px"},artifact:{pane:{background:"semantic.colors.container",toolbarBackground:"semantic.colors.container"}}};function vs(n,e){if(!e.startsWith("palette.")&&!e.startsWith("semantic.")&&!e.startsWith("components."))return e;let t=e.split("."),r=n;for(let o of t){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?vs(n,r):r}function bm(n){let e={};function t(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=vs(n,a);d!==void 0&&(e[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&t(a,i)}}return t(n.palette,"palette"),t(n.semantic,"semantic"),t(n.components,"components"),e}function Bh(n){let e=[],t=[];return n.palette||e.push({path:"palette",message:"Theme must include a palette",severity:"error"}),n.semantic||t.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),n.components||t.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:e.length===0,errors:e,warnings:t}}function vm(n,e){let t={...n};for(let[r,o]of Object.entries(e)){let s=t[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?t[r]=vm(s,o):t[r]=o}return t}function Dh(n,e){return e?vm(n,e):n}function qo(n,e={}){var o,s,a,i,d,c,p,g,h,m,y,w,E;let t={palette:Rh,semantic:Wh,components:Hh},r={palette:{...t.palette,...n==null?void 0:n.palette,colors:{...t.palette.colors,...(o=n==null?void 0:n.palette)==null?void 0:o.colors},spacing:{...t.palette.spacing,...(s=n==null?void 0:n.palette)==null?void 0:s.spacing},typography:{...t.palette.typography,...(a=n==null?void 0:n.palette)==null?void 0:a.typography},shadows:{...t.palette.shadows,...(i=n==null?void 0:n.palette)==null?void 0:i.shadows},borders:{...t.palette.borders,...(d=n==null?void 0:n.palette)==null?void 0:d.borders},radius:{...t.palette.radius,...(c=n==null?void 0:n.palette)==null?void 0:c.radius}},semantic:{...t.semantic,...n==null?void 0:n.semantic,colors:{...t.semantic.colors,...(p=n==null?void 0:n.semantic)==null?void 0:p.colors,interactive:{...t.semantic.colors.interactive,...(h=(g=n==null?void 0:n.semantic)==null?void 0:g.colors)==null?void 0:h.interactive},feedback:{...t.semantic.colors.feedback,...(y=(m=n==null?void 0:n.semantic)==null?void 0:m.colors)==null?void 0:y.feedback}},spacing:{...t.semantic.spacing,...(w=n==null?void 0:n.semantic)==null?void 0:w.spacing},typography:{...t.semantic.typography,...(E=n==null?void 0:n.semantic)==null?void 0:E.typography}},components:Dh(t.components,n==null?void 0:n.components)};if(e.validate!==!1){let B=Bh(r);if(!B.valid)throw new Error(`Theme validation failed: ${B.errors.map(T=>T.message).join(", ")}`)}if(e.plugins)for(let B of e.plugins)r=B.transform(r);return r}function wm(n){var w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de,Ae,$e,K,J,Se,Y,le,Te,Ye,tt,Wt,ht,ot,me,X,lt,Ve,Ee,xe,Ze,jt,be,ue,xn,At,fn,hr,yr,qe,L,ge,Me,Le,He,nt,Xe,yt,fe,D,ve,ce,ft,Ge,Pt,kt,wt,Ht,Xt,Ot,en,br,Wr,rr,or,Kr,Vt,sr,Hr,Bn,Ln,Dn,ar,vr,Gr,Vn,Qr,St,wr,xr,Br,ir,bt,Co,Cr,Ao,Pn,Qo,Xr,Dr,Jr,Yr,So,To,Zr,xt,Nn,Fn,Cn,Tt,Kn,Gn,On,eo;let e=bm(n),t={};for(let[Ce,Nr]of Object.entries(e)){let Qn=Ce.replace(/\./g,"-");t[`--persona-${Qn}`]=Nr.value}t["--persona-primary"]=(w=t["--persona-semantic-colors-primary"])!=null?w:t["--persona-palette-colors-primary-500"],t["--persona-secondary"]=(E=t["--persona-semantic-colors-secondary"])!=null?E:t["--persona-palette-colors-secondary-500"],t["--persona-accent"]=(B=t["--persona-semantic-colors-accent"])!=null?B:t["--persona-palette-colors-accent-500"],t["--persona-surface"]=(T=t["--persona-semantic-colors-surface"])!=null?T:t["--persona-palette-colors-gray-50"],t["--persona-background"]=(I=t["--persona-semantic-colors-background"])!=null?I:t["--persona-palette-colors-gray-50"],t["--persona-container"]=(M=t["--persona-semantic-colors-container"])!=null?M:t["--persona-palette-colors-gray-100"],t["--persona-text"]=(P=t["--persona-semantic-colors-text"])!=null?P:t["--persona-palette-colors-gray-900"],t["--persona-text-muted"]=(C=t["--persona-semantic-colors-text-muted"])!=null?C:t["--persona-palette-colors-gray-500"],t["--persona-text-inverse"]=(k=t["--persona-semantic-colors-text-inverse"])!=null?k:t["--persona-palette-colors-gray-50"],t["--persona-border"]=(q=t["--persona-semantic-colors-border"])!=null?q:t["--persona-palette-colors-gray-200"],t["--persona-divider"]=(_=t["--persona-semantic-colors-divider"])!=null?_:t["--persona-palette-colors-gray-200"],t["--persona-muted"]=t["--persona-text-muted"],t["--persona-voice-recording-indicator"]=(R=t["--persona-components-voice-recording-indicator"])!=null?R:t["--persona-palette-colors-error-500"],t["--persona-voice-recording-bg"]=(O=t["--persona-components-voice-recording-background"])!=null?O:t["--persona-palette-colors-error-50"],t["--persona-voice-processing-icon"]=(F=t["--persona-components-voice-processing-icon"])!=null?F:t["--persona-palette-colors-primary-500"],t["--persona-voice-speaking-icon"]=(Z=t["--persona-components-voice-speaking-icon"])!=null?Z:t["--persona-palette-colors-success-500"],t["--persona-approval-bg"]=(ke=t["--persona-components-approval-requested-background"])!=null?ke:t["--persona-surface"],t["--persona-approval-border"]=(pe=t["--persona-components-approval-requested-border"])!=null?pe:t["--persona-border"],t["--persona-approval-text"]=(ee=t["--persona-components-approval-requested-text"])!=null?ee:t["--persona-palette-colors-gray-900"],t["--persona-approval-shadow"]=(Pe=t["--persona-components-approval-requested-shadow"])!=null?Pe:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",t["--persona-approval-approve-bg"]=(Ie=t["--persona-components-approval-approve-background"])!=null?Ie:t["--persona-button-primary-bg"],t["--persona-approval-deny-bg"]=(ie=t["--persona-components-approval-deny-background"])!=null?ie:t["--persona-container"],t["--persona-attachment-image-bg"]=(he=t["--persona-components-attachment-image-background"])!=null?he:t["--persona-palette-colors-gray-100"],t["--persona-attachment-image-border"]=(re=t["--persona-components-attachment-image-border"])!=null?re:t["--persona-palette-colors-gray-200"],t["--persona-font-family"]=(oe=t["--persona-semantic-typography-fontFamily"])!=null?oe:t["--persona-palette-typography-fontFamily-sans"],t["--persona-font-size"]=(de=t["--persona-semantic-typography-fontSize"])!=null?de:t["--persona-palette-typography-fontSize-base"],t["--persona-font-weight"]=(Ae=t["--persona-semantic-typography-fontWeight"])!=null?Ae:t["--persona-palette-typography-fontWeight-normal"],t["--persona-line-height"]=($e=t["--persona-semantic-typography-lineHeight"])!=null?$e:t["--persona-palette-typography-lineHeight-normal"],t["--persona-input-font-family"]=t["--persona-font-family"],t["--persona-input-font-weight"]=t["--persona-font-weight"],t["--persona-radius-sm"]=(K=t["--persona-palette-radius-sm"])!=null?K:"0.125rem",t["--persona-radius-md"]=(J=t["--persona-palette-radius-md"])!=null?J:"0.375rem",t["--persona-radius-lg"]=(Se=t["--persona-palette-radius-lg"])!=null?Se:"0.5rem",t["--persona-radius-xl"]=(Y=t["--persona-palette-radius-xl"])!=null?Y:"0.75rem",t["--persona-radius-full"]=(le=t["--persona-palette-radius-full"])!=null?le:"9999px",t["--persona-launcher-radius"]=(Ye=(Te=t["--persona-components-launcher-borderRadius"])!=null?Te:t["--persona-palette-radius-full"])!=null?Ye:"9999px",t["--persona-launcher-bg"]=(tt=t["--persona-components-launcher-background"])!=null?tt:t["--persona-primary"],t["--persona-launcher-fg"]=(Wt=t["--persona-components-launcher-foreground"])!=null?Wt:t["--persona-text-inverse"],t["--persona-launcher-border"]=(ht=t["--persona-components-launcher-border"])!=null?ht:t["--persona-border"],t["--persona-button-primary-bg"]=(ot=t["--persona-components-button-primary-background"])!=null?ot:t["--persona-primary"],t["--persona-button-primary-fg"]=(me=t["--persona-components-button-primary-foreground"])!=null?me:t["--persona-text-inverse"],t["--persona-button-radius"]=(lt=(X=t["--persona-components-button-primary-borderRadius"])!=null?X:t["--persona-palette-radius-full"])!=null?lt:"9999px",t["--persona-panel-radius"]=(Ee=(Ve=t["--persona-components-panel-borderRadius"])!=null?Ve:t["--persona-radius-xl"])!=null?Ee:"0.75rem",t["--persona-panel-border"]=(xe=t["--persona-components-panel-border"])!=null?xe:`1px solid ${t["--persona-border"]}`,t["--persona-panel-shadow"]=(jt=(Ze=t["--persona-components-panel-shadow"])!=null?Ze:t["--persona-palette-shadows-xl"])!=null?jt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",t["--persona-launcher-shadow"]=(be=t["--persona-components-launcher-shadow"])!=null?be:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",t["--persona-input-radius"]=(xn=(ue=t["--persona-components-input-borderRadius"])!=null?ue:t["--persona-radius-lg"])!=null?xn:"0.5rem",t["--persona-message-user-radius"]=(fn=(At=t["--persona-components-message-user-borderRadius"])!=null?At:t["--persona-radius-lg"])!=null?fn:"0.5rem",t["--persona-message-assistant-radius"]=(yr=(hr=t["--persona-components-message-assistant-borderRadius"])!=null?hr:t["--persona-radius-lg"])!=null?yr:"0.5rem",t["--persona-header-bg"]=(qe=t["--persona-components-header-background"])!=null?qe:t["--persona-surface"],t["--persona-header-border"]=(L=t["--persona-components-header-border"])!=null?L:t["--persona-divider"],t["--persona-header-icon-bg"]=(ge=t["--persona-components-header-iconBackground"])!=null?ge:t["--persona-primary"],t["--persona-header-icon-fg"]=(Me=t["--persona-components-header-iconForeground"])!=null?Me:t["--persona-text-inverse"],t["--persona-header-title-fg"]=(Le=t["--persona-components-header-titleForeground"])!=null?Le:t["--persona-primary"],t["--persona-header-subtitle-fg"]=(He=t["--persona-components-header-subtitleForeground"])!=null?He:t["--persona-text-muted"],t["--persona-header-action-icon-fg"]=(nt=t["--persona-components-header-actionIconForeground"])!=null?nt:t["--persona-muted"];let r=(Xe=n.components)==null?void 0:Xe.header;r!=null&&r.shadow&&(t["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(t["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=n.components)==null?void 0:yt.introCard;t["--persona-intro-card-bg"]=(fe=t["--persona-components-introCard-background"])!=null?fe:t["--persona-surface"],t["--persona-intro-card-radius"]=(D=t["--persona-components-introCard-borderRadius"])!=null?D:"1rem",t["--persona-intro-card-padding"]=(ve=t["--persona-components-introCard-padding"])!=null?ve:"1.5rem",t["--persona-intro-card-shadow"]=(ft=(ce=o==null?void 0:o.shadow)!=null?ce:t["--persona-components-introCard-shadow"])!=null?ft:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-input-background"]=(Ge=t["--persona-components-input-background"])!=null?Ge:t["--persona-surface"],t["--persona-input-placeholder"]=(Pt=t["--persona-components-input-placeholder"])!=null?Pt:t["--persona-text-muted"],t["--persona-message-user-bg"]=(kt=t["--persona-components-message-user-background"])!=null?kt:t["--persona-accent"],t["--persona-message-user-text"]=(wt=t["--persona-components-message-user-text"])!=null?wt:t["--persona-text-inverse"],t["--persona-message-user-shadow"]=(Ht=t["--persona-components-message-user-shadow"])!=null?Ht:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-message-assistant-bg"]=(Xt=t["--persona-components-message-assistant-background"])!=null?Xt:t["--persona-surface"],t["--persona-message-assistant-text"]=(Ot=t["--persona-components-message-assistant-text"])!=null?Ot:t["--persona-text"],t["--persona-message-assistant-border"]=(en=t["--persona-components-message-assistant-border"])!=null?en:t["--persona-border"],t["--persona-message-assistant-shadow"]=(br=t["--persona-components-message-assistant-shadow"])!=null?br:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-bg"]=(rr=(Wr=t["--persona-components-scrollToBottom-background"])!=null?Wr:t["--persona-button-primary-bg"])!=null?rr:t["--persona-accent"],t["--persona-scroll-to-bottom-fg"]=(Kr=(or=t["--persona-components-scrollToBottom-foreground"])!=null?or:t["--persona-button-primary-fg"])!=null?Kr:t["--persona-text-inverse"],t["--persona-scroll-to-bottom-border"]=(Vt=t["--persona-components-scrollToBottom-border"])!=null?Vt:t["--persona-primary"],t["--persona-scroll-to-bottom-size"]=(sr=t["--persona-components-scrollToBottom-size"])!=null?sr:"40px",t["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(Hr=t["--persona-components-scrollToBottom-borderRadius"])!=null?Hr:t["--persona-button-radius"])!=null?Bn:t["--persona-radius-full"])!=null?Ln:"9999px",t["--persona-scroll-to-bottom-shadow"]=(ar=(Dn=t["--persona-components-scrollToBottom-shadow"])!=null?Dn:t["--persona-palette-shadows-sm"])!=null?ar:"0 1px 2px 0 rgb(0 0 0 / 0.05)",t["--persona-scroll-to-bottom-padding"]=(vr=t["--persona-components-scrollToBottom-padding"])!=null?vr:"0.5rem 0.875rem",t["--persona-scroll-to-bottom-gap"]=(Gr=t["--persona-components-scrollToBottom-gap"])!=null?Gr:"0.5rem",t["--persona-scroll-to-bottom-font-size"]=(Qr=(Vn=t["--persona-components-scrollToBottom-fontSize"])!=null?Vn:t["--persona-palette-typography-fontSize-sm"])!=null?Qr:"0.875rem",t["--persona-scroll-to-bottom-icon-size"]=(St=t["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",t["--persona-tool-bubble-shadow"]=(wr=t["--persona-components-toolBubble-shadow"])!=null?wr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-reasoning-bubble-shadow"]=(xr=t["--persona-components-reasoningBubble-shadow"])!=null?xr:"0 5px 15px rgba(15, 23, 42, 0.08)",t["--persona-composer-shadow"]=(Br=t["--persona-components-composer-shadow"])!=null?Br:"none",t["--persona-md-inline-code-bg"]=(ir=t["--persona-components-markdown-inlineCode-background"])!=null?ir:t["--persona-container"],t["--persona-md-inline-code-color"]=(bt=t["--persona-components-markdown-inlineCode-foreground"])!=null?bt:t["--persona-text"],t["--persona-md-link-color"]=(Cr=(Co=t["--persona-components-markdown-link-foreground"])!=null?Co:t["--persona-accent"])!=null?Cr:"#0f0f0f";let s=t["--persona-components-markdown-heading-h1-fontSize"];s&&(t["--persona-md-h1-size"]=s);let a=t["--persona-components-markdown-heading-h1-fontWeight"];a&&(t["--persona-md-h1-weight"]=a);let i=t["--persona-components-markdown-heading-h2-fontSize"];i&&(t["--persona-md-h2-size"]=i);let d=t["--persona-components-markdown-heading-h2-fontWeight"];d&&(t["--persona-md-h2-weight"]=d);let c=t["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(t["--persona-md-prose-font-family"]=c),t["--persona-md-code-block-bg"]=(Ao=t["--persona-components-markdown-codeBlock-background"])!=null?Ao:t["--persona-container"],t["--persona-md-code-block-border-color"]=(Pn=t["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:t["--persona-border"],t["--persona-md-code-block-text-color"]=(Qo=t["--persona-components-markdown-codeBlock-textColor"])!=null?Qo:"inherit",t["--persona-md-table-header-bg"]=(Xr=t["--persona-components-markdown-table-headerBackground"])!=null?Xr:t["--persona-container"],t["--persona-md-table-border-color"]=(Dr=t["--persona-components-markdown-table-borderColor"])!=null?Dr:t["--persona-border"],t["--persona-md-hr-color"]=(Jr=t["--persona-components-markdown-hr-color"])!=null?Jr:t["--persona-divider"],t["--persona-md-blockquote-border-color"]=(Yr=t["--persona-components-markdown-blockquote-borderColor"])!=null?Yr:t["--persona-palette-colors-gray-900"],t["--persona-md-blockquote-bg"]=(So=t["--persona-components-markdown-blockquote-background"])!=null?So:"transparent",t["--persona-md-blockquote-text-color"]=(To=t["--persona-components-markdown-blockquote-textColor"])!=null?To:t["--persona-palette-colors-gray-500"],t["--cw-container"]=(Zr=t["--persona-components-collapsibleWidget-container"])!=null?Zr:t["--persona-surface"],t["--cw-surface"]=(xt=t["--persona-components-collapsibleWidget-surface"])!=null?xt:t["--persona-surface"],t["--cw-border"]=(Nn=t["--persona-components-collapsibleWidget-border"])!=null?Nn:t["--persona-border"],t["--persona-message-border"]=(Fn=t["--persona-components-message-border"])!=null?Fn:t["--persona-border"];let p=n.components,g=p==null?void 0:p.iconButton;g&&(g.background&&(t["--persona-icon-btn-bg"]=g.background),g.border&&(t["--persona-icon-btn-border"]=g.border),g.color&&(t["--persona-icon-btn-color"]=g.color),g.padding&&(t["--persona-icon-btn-padding"]=g.padding),g.borderRadius&&(t["--persona-icon-btn-radius"]=g.borderRadius),g.hoverBackground&&(t["--persona-icon-btn-hover-bg"]=g.hoverBackground),g.hoverColor&&(t["--persona-icon-btn-hover-color"]=g.hoverColor),g.activeBackground&&(t["--persona-icon-btn-active-bg"]=g.activeBackground),g.activeBorder&&(t["--persona-icon-btn-active-border"]=g.activeBorder));let h=p==null?void 0:p.labelButton;h&&(h.background&&(t["--persona-label-btn-bg"]=h.background),h.border&&(t["--persona-label-btn-border"]=h.border),h.color&&(t["--persona-label-btn-color"]=h.color),h.padding&&(t["--persona-label-btn-padding"]=h.padding),h.borderRadius&&(t["--persona-label-btn-radius"]=h.borderRadius),h.hoverBackground&&(t["--persona-label-btn-hover-bg"]=h.hoverBackground),h.fontSize&&(t["--persona-label-btn-font-size"]=h.fontSize),h.gap&&(t["--persona-label-btn-gap"]=h.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(t["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(t["--persona-toggle-group-radius"]=m.borderRadius));let y=p==null?void 0:p.artifact;if(y!=null&&y.toolbar){let Ce=y.toolbar;Ce.iconHoverColor&&(t["--persona-artifact-toolbar-icon-hover-color"]=Ce.iconHoverColor),Ce.iconHoverBackground&&(t["--persona-artifact-toolbar-icon-hover-bg"]=Ce.iconHoverBackground),Ce.iconPadding&&(t["--persona-artifact-toolbar-icon-padding"]=Ce.iconPadding),Ce.iconBorderRadius&&(t["--persona-artifact-toolbar-icon-radius"]=Ce.iconBorderRadius),Ce.iconBorder&&(t["--persona-artifact-toolbar-icon-border"]=Ce.iconBorder),Ce.toggleGroupGap&&(t["--persona-artifact-toolbar-toggle-group-gap"]=Ce.toggleGroupGap),Ce.toggleBorderRadius&&(t["--persona-artifact-toolbar-toggle-radius"]=Ce.toggleBorderRadius),Ce.copyBackground&&(t["--persona-artifact-toolbar-copy-bg"]=Ce.copyBackground),Ce.copyBorder&&(t["--persona-artifact-toolbar-copy-border"]=Ce.copyBorder),Ce.copyColor&&(t["--persona-artifact-toolbar-copy-color"]=Ce.copyColor),Ce.copyBorderRadius&&(t["--persona-artifact-toolbar-copy-radius"]=Ce.copyBorderRadius),Ce.copyPadding&&(t["--persona-artifact-toolbar-copy-padding"]=Ce.copyPadding),Ce.copyMenuBackground&&(t["--persona-artifact-toolbar-copy-menu-bg"]=Ce.copyMenuBackground,t["--persona-dropdown-bg"]=(Cn=t["--persona-dropdown-bg"])!=null?Cn:Ce.copyMenuBackground),Ce.copyMenuBorder&&(t["--persona-artifact-toolbar-copy-menu-border"]=Ce.copyMenuBorder,t["--persona-dropdown-border"]=(Tt=t["--persona-dropdown-border"])!=null?Tt:Ce.copyMenuBorder),Ce.copyMenuShadow&&(t["--persona-artifact-toolbar-copy-menu-shadow"]=Ce.copyMenuShadow,t["--persona-dropdown-shadow"]=(Kn=t["--persona-dropdown-shadow"])!=null?Kn:Ce.copyMenuShadow),Ce.copyMenuBorderRadius&&(t["--persona-artifact-toolbar-copy-menu-radius"]=Ce.copyMenuBorderRadius,t["--persona-dropdown-radius"]=(Gn=t["--persona-dropdown-radius"])!=null?Gn:Ce.copyMenuBorderRadius),Ce.copyMenuItemHoverBackground&&(t["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ce.copyMenuItemHoverBackground,t["--persona-dropdown-item-hover-bg"]=(On=t["--persona-dropdown-item-hover-bg"])!=null?On:Ce.copyMenuItemHoverBackground),Ce.iconBackground&&(t["--persona-artifact-toolbar-icon-bg"]=Ce.iconBackground),Ce.toolbarBorder&&(t["--persona-artifact-toolbar-border"]=Ce.toolbarBorder)}if(y!=null&&y.tab){let Ce=y.tab;Ce.background&&(t["--persona-artifact-tab-bg"]=Ce.background),Ce.activeBackground&&(t["--persona-artifact-tab-active-bg"]=Ce.activeBackground),Ce.activeBorder&&(t["--persona-artifact-tab-active-border"]=Ce.activeBorder),Ce.borderRadius&&(t["--persona-artifact-tab-radius"]=Ce.borderRadius),Ce.textColor&&(t["--persona-artifact-tab-color"]=Ce.textColor),Ce.hoverBackground&&(t["--persona-artifact-tab-hover-bg"]=Ce.hoverBackground),Ce.listBackground&&(t["--persona-artifact-tab-list-bg"]=Ce.listBackground),Ce.listBorderColor&&(t["--persona-artifact-tab-list-border-color"]=Ce.listBorderColor),Ce.listPadding&&(t["--persona-artifact-tab-list-padding"]=Ce.listPadding)}if(y!=null&&y.pane){let Ce=y.pane;if(Ce.toolbarBackground){let Nr=(eo=vs(n,Ce.toolbarBackground))!=null?eo:Ce.toolbarBackground;t["--persona-artifact-toolbar-bg"]=Nr}}return t}var Nh={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"}}},xm=n=>{if(!(!n||typeof n!="object"||Array.isArray(n)))return n},Ki=()=>{var n;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((n=window.matchMedia)!=null&&n.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},Fh=n=>{var t;let e=(t=n==null?void 0:n.colorScheme)!=null?t:"light";return e==="light"?"light":e==="dark"?"dark":Ki()},Oh=n=>Fh(n),_h=n=>qo(n),$h=n=>{var t;let e=qo(void 0,{validate:!1});return qo({...n,palette:{...e.palette,colors:{...Nh.colors,...(t=n==null?void 0:n.palette)==null?void 0:t.colors}}},{validate:!1})},qa=n=>{let e=Oh(n),t=xm(n==null?void 0:n.theme),r=xm(n==null?void 0:n.darkTheme);return e==="dark"?$h(na(t!=null?t:{},r!=null?r:{})):_h(t)},Uh=n=>wm(n),ws=(n,e)=>{let t=qa(e),r=Uh(t);for(let[o,s]of Object.entries(r))n.style.setProperty(o,s)},Cm=n=>{let e=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let t=new MutationObserver(()=>{n(Ki())});t.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),e.push(()=>t.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let t=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>n(Ki());t.addEventListener?(t.addEventListener("change",r),e.push(()=>t.removeEventListener("change",r))):t.addListener&&(t.addListener(r),e.push(()=>t.removeListener(r)))}return()=>{e.forEach(t=>t())}};var Am=require("idiomorph"),za=(n,e,t={})=>{let{preserveTypingAnimation:r=!0}=t;Am.Idiomorph.morph(n,e.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-tool-elapsed"))return s instanceof HTMLElement&&s.getAttribute("data-tool-elapsed")===o.getAttribute("data-tool-elapsed")?!1:void 0;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Sm=n=>n.replace(/^\n+/,"").replace(/\s+$/,"");var ja={index:-1,draft:""};function Tm(n){let{direction:e,history:t,currentValue:r,atStart:o,state:s}=n,a=s.index!==-1;if(t.length===0)return{handled:!1,state:s};if(e==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=t.length-1;return{handled:!0,value:t[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<t.length-1){let i=s.index+1;return{handled:!0,value:t[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...ja}}}function Em(n,e){var t,r,o,s,a,i,d,c,p,g,h,m,y,w,E,B,T,I,M,P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he,re,oe,de;return[n.id,n.role,(r=(t=n.content)==null?void 0:t.length)!=null?r:0,(s=(o=n.content)==null?void 0:o.slice(-32))!=null?s:"",n.streaming?"1":"0",n.voiceProcessing?"1":"0",(a=n.variant)!=null?a:"",(d=(i=n.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=n.llmContent)==null?void 0:c.length)!=null?p:0,(h=(g=n.approval)==null?void 0:g.status)!=null?h:"",(y=(m=n.toolCall)==null?void 0:m.status)!=null?y:"",(E=(w=n.toolCall)==null?void 0:w.name)!=null?E:"",(I=(T=(B=n.toolCall)==null?void 0:B.chunks)==null?void 0:T.length)!=null?I:0,(k=(C=(P=(M=n.toolCall)==null?void 0:M.chunks)==null?void 0:P[n.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?k:"",typeof((q=n.toolCall)==null?void 0:q.args)=="string"?n.toolCall.args.length:(_=n.toolCall)!=null&&_.args?JSON.stringify(n.toolCall.args).length:0,(F=(O=(R=n.reasoning)==null?void 0:R.chunks)==null?void 0:O.length)!=null?F:0,(ee=(pe=(ke=(Z=n.reasoning)==null?void 0:Z.chunks)==null?void 0:ke[n.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?ee:0,(he=(ie=(Ie=(Pe=n.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[n.reasoning.chunks.length-1])==null?void 0:ie.slice(-32))!=null?he:"",(oe=(re=n.contentParts)==null?void 0:re.length)!=null?oe:0,(de=n.stopReason)!=null?de:"",e].join("\0")}function Mm(){return new Map}function km(n,e,t){let r=n.get(e);return r&&r.fingerprint===t?r.wrapper:null}function Lm(n,e,t,r){n.set(e,{fingerprint:t,wrapper:r})}function Pm(n,e){for(let t of n.keys())e.has(t)||n.delete(t)}function Va(n=!0){let e=n;return{isFollowing:()=>e,pause:()=>e?(e=!1,!0):!1,resume:()=>e?!1:(e=!0,!0)}}function Rr(n){return Math.max(0,n.scrollHeight-n.clientHeight)}function vo(n,e){return Rr(n)-n.scrollTop<=e}function Ka(n){let{following:e,currentScrollTop:t,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=n,p=t-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:t}:!e&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:t}:e&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:t}:e&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:t}:{action:"none",delta:p,nextLastScrollTop:t}}function Ga(n){let{following:e,deltaY:t,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=n;return e&&t<0?"pause":!e&&o&&t>0&&r?"resume":"none"}function Im(n,e){return!n||n.isCollapsed?!1:e.contains(n.anchorNode)||e.contains(n.focusNode)}function Rm(n){let e=Math.max(0,n.anchorOffsetTop-n.topOffset),t=Math.max(0,e+n.viewportHeight-n.contentHeight);return{targetScrollTop:e,spacerHeight:t}}function Wm(n){let e=Math.max(0,n.currentContentHeight-n.contentHeightAtAnchor);return Math.max(0,n.initialSpacerHeight-e)}var nn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,wo=vn+1;var ra={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},qh=["pre","code","a","script","style"],Qa=n=>{var e,t,r,o,s;return{type:(e=n==null?void 0:n.type)!=null?e:ra.type,placeholder:(t=n==null?void 0:n.placeholder)!=null?t:ra.placeholder,speed:(r=n==null?void 0:n.speed)!=null?r:ra.speed,duration:(o=n==null?void 0:n.duration)!=null?o:ra.duration,buffer:(s=n==null?void 0:n.buffer)!=null?s:ra.buffer}},zh=[{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"}],Bm=new Map;for(let n of zh)Bm.set(n.name,n);var xs=(n,e)=>{var t,r;return n==="none"?null:e&&Object.prototype.hasOwnProperty.call(e,n)?(t=e[n])!=null?t:null:(r=Bm.get(n))!=null?r:null},Xa=(n,e,t,r,o)=>{if(!o)return n;if(t!=null&&t.bufferContent)return t.bufferContent(n,r);if(!n)return n;if(e==="word"){let s=n.search(/\s(?=\S*$)/);return s<0?"":n.slice(0,s)}if(e==="line"){let s=n.lastIndexOf(`
|
|
19
19
|
`);return s<0?"":n.slice(0,s)}return n},jh=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${t}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=e,o},Vh=(n,e,t,r)=>{let o=n.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${t}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=e,o},Gi=/\s/,Kh=(n,e)=>{let t=n.parentNode;for(;t;){if(t.nodeType===1){let r=t;if(e.has(r.tagName.toLowerCase()))return!0}t=t.parentNode}return!1},Gh=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Gi.test(s[i])){let c=i;for(;c<s.length&&Gi.test(s[c]);)c+=1;a.appendChild(r.createTextNode(s.slice(i,c))),i=c}else{let c=r.createElement("span");c.className="persona-stream-word-group";let p=i;for(;p<s.length&&!Gi.test(s[p]);)c.appendChild(jh(r,s[p],e,t.value)),t.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,n)},Qh=(n,e,t)=>{var d;let r=n.ownerDocument,o=n.parentNode;if(!r||!o)return;let s=(d=n.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(Vh(r,c,e,t.value)),t.value+=1));o.replaceChild(a,n)},oa=(n,e,t,r)=>{var g,h;if(!n||typeof document=="undefined")return n;let o=document.createElement("div");o.innerHTML=n;let s=new Set(((g=r==null?void 0:r.skipTags)!=null?g:qh).map(m=>m.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)Kh(d,s)||i.push(d),d=a.nextNode();let c={value:(h=r==null?void 0:r.startIndex)!=null?h:0},p=e==="char"?Gh:Qh;for(let m of i)p(m,t,c);return o.innerHTML},Ja=(n=document)=>{let e=n.createElement("span");return e.className="persona-stream-caret",e.setAttribute("aria-hidden","true"),e.setAttribute("data-preserve-animation","stream-caret"),e},sa=(n=document)=>{let e=n.createElement("div");e.className="persona-stream-skeleton",e.setAttribute("data-preserve-animation","stream-skeleton"),e.setAttribute("aria-hidden","true");let t=n.createElement("div");return t.className="persona-stream-skeleton-line",e.appendChild(t),e},Hm=new WeakMap,Xh=(n,e)=>{var s;if(!n.styles)return;let t=Hm.get(e);if(t||(t=new Set,Hm.set(e,t)),t.has(n.name)){let a=n.name.replace(/["\\]/g,"\\$&");if(e.querySelector(`style[data-persona-animation="${a}"]`))return;t.delete(n.name)}t.add(n.name);let o=(e instanceof ShadowRoot?e.ownerDocument:(s=e.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",n.name),o.textContent=n.styles,e.appendChild(o)},Qi=new WeakMap,Jh=(n,e)=>{if(!n.onAttach)return;let t=Qi.get(e);if(t||(t=new Map,Qi.set(e,t)),t.has(n.name))return;let r=n.onAttach(e);t.set(n.name,r)},Dm=n=>{let e=Qi.get(n);if(e){for(let t of e.values())typeof t=="function"&&t();e.clear()}},Ya=(n,e)=>{Xh(n,e),Jh(n,e)};function Xi(n,e=vn){let t=n.style.position,r=n.style.zIndex,o=n.style.isolation,s=getComputedStyle(n),a=s.position==="static"||s.position==="";return a&&(n.style.position="relative"),n.style.zIndex=String(e),n.style.isolation="isolate",()=>{a&&(n.style.position=t),n.style.zIndex=r,n.style.isolation=o}}var aa=0,xo=null;function Ji(n=document){var t;if(aa++,aa===1){let r=n.body,s=((t=n.defaultView)!=null?t:window).scrollY||n.documentElement.scrollTop;xo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let e=!1;return()=>{var r;if(!e&&(e=!0,aa=Math.max(0,aa-1),aa===0&&xo)){let o=n.body,s=(r=n.defaultView)!=null?r:window;o.style.overflow=xo.originalOverflow,o.style.position=xo.originalPosition,o.style.top=xo.originalTop,o.style.width=xo.originalWidth,s.scrollTo(0,xo.scrollY),xo=null}}}var ia={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},gn=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="docked"},la=n=>{var e,t;return((t=(e=n==null?void 0:n.launcher)==null?void 0:e.mountMode)!=null?t:"floating")==="composer-bar"},gr=n=>{var t,r,o,s,a,i;let e=(t=n==null?void 0:n.launcher)==null?void 0:t.dock;return{side:(r=e==null?void 0:e.side)!=null?r:ia.side,width:(o=e==null?void 0:e.width)!=null?o:ia.width,animate:(s=e==null?void 0:e.animate)!=null?s:ia.animate,reveal:(a=e==null?void 0:e.reveal)!=null?a:ia.reveal,maxHeight:(i=e==null?void 0:e.maxHeight)!=null?i:ia.maxHeight}};var fr={"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 Yh="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Za=(n,e={})=>{var E,B,T,I,M,P;let{showClose:t=!0,wrapperClassName:r=Yh,buttonSize:o,iconSize:s="28px"}=e,a=(E=n==null?void 0:n.launcher)!=null?E:{},i=(B=o!=null?o:a.closeButtonSize)!=null?B:"32px",d=v("div",r),c=(T=a.closeButtonTooltipText)!=null?T:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0,g=(M=a.closeButtonIconName)!=null?M:"x",h=(P=a.closeButtonIconText)!=null?P:"\xD7",m=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),y=Mt("button",{className:zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:t?void 0:"none",color:a.closeButtonColor||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:m?`${a.closeButtonBorderWidth||"0px"} solid ${a.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:a.closeButtonBorderRadius||void 0,paddingLeft:a.closeButtonPaddingX||void 0,paddingRight:a.closeButtonPaddingX||void 0,paddingTop:a.closeButtonPaddingY||void 0,paddingBottom:a.closeButtonPaddingY||void 0}}),w=ye(g,s,"currentColor",1);if(w?(w.style.display="block",y.appendChild(w)):y.textContent=h,d.appendChild(y),p&&c){let C=null,k=()=>{if(C)return;let _=y.ownerDocument,R=_.body;if(!R)return;C=Ir(_,"div","persona-clear-chat-tooltip"),C.textContent=c;let O=Ir(_,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let F=y.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(wo),C.style.left=`${F.left+F.width/2}px`,C.style.top=`${F.top-8}px`,C.style.transform="translate(-50%, -100%)",R.appendChild(C)},q=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",k),d.addEventListener("mouseleave",q),y.addEventListener("focus",k),y.addEventListener("blur",q),d._cleanupTooltip=()=>{q(),d.removeEventListener("mouseenter",k),d.removeEventListener("mouseleave",q),y.removeEventListener("focus",k),y.removeEventListener("blur",q)}}return{button:y,wrapper:d}},Zh="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",ei=(n,e={})=>{var C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie;let{wrapperClassName:t=Zh,buttonSize:r,iconSize:o="20px"}=e,a=(k=((C=n==null?void 0:n.launcher)!=null?C:{}).clearChat)!=null?k:{},i=(q=r!=null?r:a.size)!=null?q:"32px",d=(_=a.iconName)!=null?_:"refresh-cw",c=(R=a.iconColor)!=null?R:"",p=(O=a.backgroundColor)!=null?O:"",g=(F=a.borderWidth)!=null?F:"",h=(Z=a.borderColor)!=null?Z:"",m=(ke=a.borderRadius)!=null?ke:"",y=(pe=a.paddingX)!=null?pe:"",w=(ee=a.paddingY)!=null?ee:"",E=(Pe=a.tooltipText)!=null?Pe:"Clear chat",B=(Ie=a.showTooltip)!=null?Ie:!0,T=v("div",t),I=!!(g||h),M=Mt("button",{className:zs("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":E},style:{height:i,width:i,color:c||kn.actionIconColor,backgroundColor:p||void 0,border:I?`${g||"0px"} solid ${h||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:y||void 0,paddingRight:y||void 0,paddingTop:w||void 0,paddingBottom:w||void 0}}),P=ye(d,o,"currentColor",1);if(P&&(P.style.display="block",M.appendChild(P)),T.appendChild(M),B&&E){let ie=null,he=()=>{if(ie)return;let oe=M.ownerDocument,de=oe.body;if(!de)return;ie=Ir(oe,"div","persona-clear-chat-tooltip"),ie.textContent=E;let Ae=Ir(oe,"div");Ae.className="persona-clear-chat-tooltip-arrow",ie.appendChild(Ae);let $e=M.getBoundingClientRect();ie.style.position="fixed",ie.style.zIndex=String(wo),ie.style.left=`${$e.left+$e.width/2}px`,ie.style.top=`${$e.top-8}px`,ie.style.transform="translate(-50%, -100%)",de.appendChild(ie)},re=()=>{ie&&ie.parentNode&&(ie.parentNode.removeChild(ie),ie=null)};T.addEventListener("mouseenter",he),T.addEventListener("mouseleave",re),M.addEventListener("focus",he),M.addEventListener("blur",re),T._cleanupTooltip=()=>{re(),T.removeEventListener("mouseenter",he),T.removeEventListener("mouseleave",re),M.removeEventListener("focus",he),M.removeEventListener("blur",re)}}return{button:M,wrapper:T}};var kn={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))"},zo=n=>{var P,C,k,q,_,R,O,F,Z,ke,pe,ee,Pe,Ie,ie,he;let{config:e,showClose:t=!0}=n,r=Mt("div",{className:"persona-widget-header persona-flex persona-items-center persona-gap-3 persona-px-6 persona-py-5",attrs:{"data-persona-theme-zone":"header"},style:{backgroundColor:"var(--persona-header-bg, var(--persona-surface, #ffffff))",borderBottomColor:"var(--persona-header-border, var(--persona-divider, #f1f5f9))",boxShadow:"var(--persona-header-shadow, none)",borderBottom:"var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))"}}),o=(P=e==null?void 0:e.launcher)!=null?P:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(k=o.closeButtonPlacement)!=null?k:"inline",i=(q=o.headerIconHidden)!=null?q:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let re=parseFloat(s)||24,oe=ye(d,re*.6,"currentColor",1);oe?c.replaceChildren(oe):c.textContent=(R=(_=e==null?void 0:e.launcher)==null?void 0:_.agentIconText)!=null?R:"\u{1F4AC}"}else if((O=e==null?void 0:e.launcher)!=null&&O.iconUrl){let re=v("img");re.src=e.launcher.iconUrl,re.alt="",re.className="persona-rounded-xl persona-object-cover",re.style.height=s,re.style.width=s,c.replaceChildren(re)}else c.textContent=(Z=(F=e==null?void 0:e.launcher)==null?void 0:F.agentIconText)!=null?Z:"\u{1F4AC}";let p=v("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),g=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(ke=e==null?void 0:e.launcher)==null?void 0:ke.title)!=null?pe:"Chat Assistant",style:{color:kn.titleColor}}),h=Mt("span",{className:"persona-text-xs",text:(Pe=(ee=e==null?void 0:e.launcher)==null?void 0:ee.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:kn.subtitleColor}});p.append(g,h),i?r.append(p):r.append(c,p);let m=(Ie=o.clearChat)!=null?Ie:{},y=(ie=m.enabled)!=null?ie:!0,w=(he=m.placement)!=null?he:"inline",E=null,B=null;if(y){let oe=ei(e,{wrapperClassName:w==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});E=oe.button,B=oe.wrapper,w==="top-right"&&(B.style.right="48px"),w==="inline"&&r.appendChild(B)}let T=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":y&&w==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:I,wrapper:M}=Za(e,{showClose:t,wrapperClassName:T});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:g,headerSubtitle:h,closeButton:I,closeButtonWrapper:M,clearChatButton:E,clearChatButtonWrapper:B}},ca=(n,e,t)=>{var a,i,d,c;let r=(a=t==null?void 0:t.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";n.appendChild(e.header),o==="top-right"&&(n.style.position="relative",n.appendChild(e.closeButtonWrapper)),e.clearChatButtonWrapper&&s==="top-right"&&(n.style.position="relative",n.appendChild(e.clearChatButtonWrapper))};function Cs(n){let{items:e,onSelect:t,anchor:r,position:o="bottom-left",portal:s}=n,a=v("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(wo)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let m of e){if(m.dividerBefore){let E=document.createElement("hr");a.appendChild(E)}let y=document.createElement("button");if(y.type="button",y.setAttribute("role","menuitem"),y.setAttribute("data-dropdown-item-id",m.id),m.destructive&&y.setAttribute("data-destructive",""),m.icon){let E=ye(m.icon,16,"currentColor",1.5);E&&y.appendChild(E)}let w=document.createElement("span");w.textContent=m.label,y.appendChild(w),y.addEventListener("click",E=>{E.stopPropagation(),p(),t(m.id)}),a.appendChild(y)}let i=null;function d(){if(!s)return;let m=r.getBoundingClientRect();a.style.top=`${m.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-m.right}px`,a.style.left="auto"):(a.style.left=`${m.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=y=>{!a.contains(y.target)&&!r.contains(y.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function g(){a.classList.contains("persona-hidden")?c():p()}function h(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:g,destroy:h}}function wn(n){let{icon:e,label:t,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=n,d=v("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",t),d.title=t;let c=ye(e,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,g]of Object.entries(i))d.setAttribute(p,g);return d}function Yi(n){let{icon:e,label:t,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=n,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=v("button",c);if(p.type="button",p.setAttribute("aria-label",t),e){let h=ye(e,s!=null?s:14,"currentColor",2);h&&p.appendChild(h)}let g=v("span");if(g.textContent=t,p.appendChild(g),i&&p.addEventListener("click",i),d)for(let[h,m]of Object.entries(d))p.setAttribute(h,m);return p}function Nm(n){var m,y;let{label:e,icon:t="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=n,c=v("div","persona-combo-btn"+(i?" "+i:""));c.style.position="relative",c.style.display="inline-flex",c.style.alignItems="center",c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0"),c.setAttribute("aria-haspopup","true"),c.setAttribute("aria-expanded","false"),c.setAttribute("aria-label",e);let p=v("span","persona-combo-btn-label");p.textContent=e,c.appendChild(p);let g=ye(t,14,"currentColor",2);g&&(g.style.marginLeft="4px",g.style.opacity="0.6",c.appendChild(g)),d&&(c.style.borderRadius=(m=d.borderRadius)!=null?m:"10px",c.style.padding=(y=d.padding)!=null?y:"6px 4px 6px 12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.addEventListener("mouseenter",()=>{var w,E;c.style.backgroundColor=(w=d.background)!=null?w:"",c.style.borderColor=(E=d.border)!=null?E:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let h=Cs({items:r,onSelect:w=>{c.setAttribute("aria-expanded","false"),o(w)},anchor:c,position:s,portal:a});return a||c.appendChild(h.element),c.addEventListener("click",w=>{w.stopPropagation();let E=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",E?"false":"true"),h.toggle()}),c.addEventListener("keydown",w=>{(w.key==="Enter"||w.key===" ")&&(w.preventDefault(),c.click())}),{element:c,setLabel:w=>{p.textContent=w,c.setAttribute("aria-label",w)},open:()=>{c.setAttribute("aria-expanded","true"),h.show()},close:()=>{c.setAttribute("aria-expanded","false"),h.hide()},toggle:()=>{let w=!h.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",w?"false":"true"),h.toggle()},destroy:()=>{h.destroy(),c.remove()}}}var ey=n=>{var r;let e=zo({config:n.config,showClose:n.showClose,onClose:n.onClose,onClearChat:n.onClearChat}),t=(r=n.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(t){let o=e.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>t()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),t())}))}return e};function ty(n,e,t){var r,o,s;if(e!=null&&e.length)for(let a of e){let i=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=ye(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=v("div","persona-relative");d.appendChild(i);let c=Cs({items:a.menuItems,onSelect:p=>t==null?void 0:t(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),n.appendChild(d)}else i.addEventListener("click",()=>t==null?void 0:t(a.id)),n.appendChild(i)}}var ny=n=>{var T,I,M,P,C,k,q,_,R;let{config:e,showClose:t=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=n,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=v("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Nm({label:(I=a.title)!=null?I:"Chat Assistant",menuItems:d.menuItems,onSelect:d.onSelect,hover:d.hover,className:""}).element,c.style.color=kn.titleColor,p=(M=c.querySelector(".persona-combo-btn-label"))!=null?M:c;else{if(c=v("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=v("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=kn.titleColor,p.textContent=(P=a.title)!=null?P:"Chat Assistant",c.appendChild(p),ty(c,o==null?void 0:o.trailingActions,(C=o==null?void 0:o.onAction)!=null?C:s),o!=null&&o.onTitleClick){c.style.cursor="pointer",c.setAttribute("role","button"),c.setAttribute("tabindex","0");let F=o.onTitleClick;c.addEventListener("click",Z=>{Z.target.closest("button")||F()}),c.addEventListener("keydown",Z=>{(Z.key==="Enter"||Z.key===" ")&&(Z.preventDefault(),F())})}let O=o==null?void 0:o.titleRowHover;O&&(c.style.borderRadius=(k=O.borderRadius)!=null?k:"10px",c.style.padding=(q=O.padding)!=null?q:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,Z;c.style.backgroundColor=(F=O.background)!=null?F:"",c.style.borderColor=(Z=O.border)!=null?Z:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let g=(_=a.closeButtonSize)!=null?_:"32px",h=v("div",""),m=v("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=g,m.style.width=g,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=t?"":"none",m.style.color=a.closeButtonColor||kn.actionIconColor;let y=(R=a.closeButtonIconName)!=null?R:"x",w=ye(y,"28px","currentColor",1);w?m.appendChild(w):m.textContent="\xD7",r&&m.addEventListener("click",r),h.appendChild(m),i.appendChild(h);let E=v("div");E.style.display="none";let B=v("span");return B.style.display="none",{header:i,iconHolder:E,headerTitle:p,headerSubtitle:B,closeButton:m,closeButtonWrapper:h,clearChatButton:null,clearChatButtonWrapper:null}},Fm={default:ey,minimal:ny},ry=n=>{var e;return(e=Fm[n])!=null?e:Fm.default},ti=(n,e,t)=>{var a,i,d;if(e!=null&&e.render){let c=e.render({config:n,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,trailingActions:e.trailingActions,onAction:e.onAction}),p=v("div");p.style.display="none";let g=v("span"),h=v("span"),m=v("button");m.style.display="none";let y=v("div");return y.style.display="none",{header:c,iconHolder:p,headerTitle:g,headerSubtitle:h,closeButton:m,closeButtonWrapper:y,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=e==null?void 0:e.layout)!=null?a:"default",s=ry(r)({config:n,showClose:(d=(i=e==null?void 0:e.showCloseButton)!=null?i:t==null?void 0:t.showClose)!=null?d:!0,onClose:t==null?void 0:t.onClose,onClearChat:t==null?void 0:t.onClearChat,layoutHeaderConfig:e,onHeaderAction:e==null?void 0:e.onAction});return e&&(e.showIcon===!1&&(s.iconHolder.style.display="none"),e.showTitle===!1&&(s.headerTitle.style.display="none"),e.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),e.showCloseButton===!1&&(s.closeButton.style.display="none"),e.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var ni=n=>{var a,i;let e=v("textarea");e.setAttribute("data-persona-composer-input",""),e.placeholder=(i=(a=n==null?void 0:n.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",e.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",e.rows=1,e.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',e.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let t=3,r=20;e.style.maxHeight=`${t*r}px`,e.style.overflowY="auto";let o=()=>{let d=parseFloat(e.style.maxHeight);return Number.isFinite(d)&&d>0?d:t*r},s=()=>{e.addEventListener("input",()=>{e.style.height="auto";let d=Math.min(e.scrollHeight,o());e.style.height=`${d}px`})};return e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.addEventListener("focus",()=>{e.style.border="none",e.style.outline="none",e.style.borderWidth="0",e.style.borderStyle="none",e.style.borderColor="transparent",e.style.boxShadow="none"}),e.addEventListener("blur",()=>{e.style.border="none",e.style.outline="none"}),{textarea:e,attachAutoResize:s}},ri=n=>{var P,C,k,q,_,R,O,F,Z,ke,pe,ee;let e=(P=n==null?void 0:n.sendButton)!=null?P:{},t=(C=e.useIcon)!=null?C:!1,r=(k=e.iconText)!=null?k:"\u2191",o=e.iconName,s=(q=e.stopIconName)!=null?q:"square",a=(_=e.tooltipText)!=null?_:"Send message",i=(R=e.stopTooltipText)!=null?R:"Stop generating",d=(F=(O=n==null?void 0:n.copy)==null?void 0:O.sendButtonLabel)!=null?F:"Send",c=(ke=(Z=n==null?void 0:n.copy)==null?void 0:Z.stopButtonLabel)!=null?ke:"Stop",p=(pe=e.showTooltip)!=null?pe:!1,g=(ee=e.size)!=null?ee:"40px",h=e.backgroundColor,m=e.textColor,y=v("div","persona-send-button-wrapper"),w=Mt("button",{className:zs("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",t?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",t&&!h&&"persona-bg-persona-primary",!t&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:t?g:void 0,height:t?g:void 0,minWidth:t?g:void 0,minHeight:t?g:void 0,fontSize:t?"18px":void 0,lineHeight:t?"1":void 0,color:t?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:t&&h||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),E=null,B=null;if(t){let Pe=parseFloat(g)||24,Ie=(m==null?void 0:m.trim())||"currentColor";o?(E=ye(o,Pe,Ie,2),E?w.appendChild(E):w.textContent=r):w.textContent=r,B=ye(s,Pe,Ie,2)}else w.textContent=d;let T=null;p&&a&&(T=v("div","persona-send-button-tooltip"),T.textContent=a,y.appendChild(T)),w.setAttribute("aria-label",a),y.appendChild(w);let I="send";return{button:w,wrapper:y,setMode:Pe=>{if(Pe===I)return;I=Pe;let Ie=Pe==="stop"?i:a;if(w.setAttribute("aria-label",Ie),T&&(T.textContent=Ie),t){if(E&&B){let ie=Pe==="stop"?B:E;w.replaceChildren(ie)}}else w.textContent=Pe==="stop"?c:d}}},oi=n=>{var T,I,M,P,C,k,q,_,R,O,F,Z;let e=(T=n==null?void 0:n.voiceRecognition)!=null?T:{};if(!(e.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((I=e.provider)==null?void 0:I.type)==="runtype";if(!(r||o))return null;let a=(P=(M=n==null?void 0:n.sendButton)==null?void 0:M.size)!=null?P:"40px",i=(C=e.iconName)!=null?C:"mic",d=(k=e.iconSize)!=null?k:a,c=parseFloat(d)||24,p=(_=e.backgroundColor)!=null?_:(q=n==null?void 0:n.sendButton)==null?void 0:q.backgroundColor,g=(O=e.iconColor)!=null?O:(R=n==null?void 0:n.sendButton)==null?void 0:R.textColor,h=v("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:d,height:d,minWidth:d,minHeight:d,fontSize:"18px",lineHeight:"1",color:g||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:e.borderWidth||void 0,borderStyle:e.borderWidth?"solid":void 0,borderColor:e.borderColor||void 0,paddingLeft:e.paddingX||void 0,paddingRight:e.paddingX||void 0,paddingTop:e.paddingY||void 0,paddingBottom:e.paddingY||void 0}}),w=ye(i,c,g||"currentColor",1.5);w?m.appendChild(w):m.textContent="\u{1F3A4}",h.appendChild(m);let E=(F=e.tooltipText)!=null?F:"Start voice recognition";if(((Z=e.showTooltip)!=null?Z:!1)&&E){let ke=v("div","persona-send-button-tooltip");ke.textContent=E,h.appendChild(ke)}return{button:m,wrapper:h}},si=n=>{var y,w,E,B,T,I,M,P;let e=(y=n==null?void 0:n.attachments)!=null?y:{};if(e.enabled!==!0)return null;let t=(E=(w=n==null?void 0:n.sendButton)==null?void 0:w.size)!=null?E:"40px",r=v("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=v("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((B=e.allowedTypes)!=null?B:jr).join(","),o.multiple=((T=e.maxFiles)!=null?T:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(I=e.buttonIconName)!=null?I:"paperclip",a=t,i=parseFloat(a)||40,d=Math.round(i*.6),c=v("div","persona-send-button-wrapper"),p=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button",attrs:{type:"button","data-persona-composer-attachment-button":"","aria-label":(M=e.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});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 g=ye(s,d,"currentColor",1.5);g?p.appendChild(g):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let h=(P=e.buttonTooltipText)!=null?P:"Attach file",m=v("div","persona-send-button-tooltip");return m.textContent=h,c.appendChild(m),{button:p,wrapper:c,input:o,previewsContainer:r}},ai=n=>{var a,i,d;let e=(a=n==null?void 0:n.statusIndicator)!=null?a:{},t=e.align==="left"?"persona-text-left":e.align==="center"?"persona-text-center":"persona-text-right",r=v("div",`persona-mt-2 ${t} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=e.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=e.idleText)!=null?d:"Online";if(e.idleLink){let c=v("a");c.href=e.idleLink,c.target="_blank",c.rel="noopener noreferrer",c.textContent=s,c.style.color="inherit",c.style.textDecoration="none",r.appendChild(c)}else r.textContent=s;return r},ii=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var li=n=>{var y,w,E,B,T,I;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-border-t-persona-divider persona-bg-persona-surface persona-px-6 persona-py-4",attrs:{"data-persona-theme-zone":"composer"}}),r=ii(),o=Mt("form",{className:"persona-widget-composer persona-flex persona-flex-col persona-gap-2 persona-rounded-2xl persona-border persona-border-gray-200 persona-bg-persona-input-background persona-px-4 persona-py-3",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),{textarea:s,attachAutoResize:a}=ni(e);a();let i=ri(e),d=oi(e),c=si(e),p=ai(e);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let g=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),h=v("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=v("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&h.append(c.wrapper),d&&m.append(d.wrapper),m.append(i.wrapper),g.append(h,m),o.append(g),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),t.append(r,o,p),{footer:t,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:p,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:g,leftActions:h,rightActions:m,setSendButtonMode:i.setMode}};var Om=()=>{let n=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),e=v("span","persona-pill-peek__icon"),t=ye("message-square",16,"currentColor",1.5);t&&e.appendChild(t);let r=v("span","persona-pill-peek__text"),o=v("span","persona-pill-peek__caret"),s=ye("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),n.append(e,r,o),{root:n,textNode:r}},_m=n=>{var y,w,E,B,T,I;let{config:e}=n,t=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=ii();r.style.display="none";let o=ai(e);o.style.display="none";let{textarea:s,attachAutoResize:a}=ni(e);s.style.maxHeight="100px",a();let i=ri(e),d=oi(e),c=si(e);c&&c.previewsContainer.classList.add("persona-pill-composer__previews");let p=Mt("form",{className:"persona-widget-composer persona-pill-composer",attrs:{"data-persona-composer-form":""},style:{outline:"none"}}),g=v("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&g.append(c.wrapper);let h=v("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&h.append(d.wrapper),h.append(i.wrapper),p.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),c&&p.append(c.input),p.append(g,s,h),c&&t.append(c.previewsContainer),t.append(p,r,o);let m=p;return{footer:t,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(y=d==null?void 0:d.button)!=null?y:null,micButtonWrapper:(w=d==null?void 0:d.wrapper)!=null?w:null,statusText:o,attachmentButton:(E=c==null?void 0:c.button)!=null?E:null,attachmentButtonWrapper:(B=c==null?void 0:c.wrapper)!=null?B:null,attachmentInput:(T=c==null?void 0:c.input)!=null?T:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:m,leftActions:g,rightActions:h,setSendButtonMode:i.setMode}};var $m=n=>{var p,g,h,m,y,w,E,B,T,I,M,P,C,k,q,_,R;let e=(g=(p=n==null?void 0:n.launcher)==null?void 0:p.enabled)!=null?g:!0,t=gn(n);if(la(n)){let O=(m=(h=n==null?void 0:n.launcher)==null?void 0:h.composerBar)!=null?m:{},F=v("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(y=O.expandedSize)!=null?y:"anchored",F.style.zIndex=String((E=(w=n==null?void 0:n.launcher)==null?void 0:w.zIndex)!=null?E:vn);let Z=v("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");Z.style.width="100%",F.appendChild(Z);let ke=v("div","persona-widget-pill-root");return ke.setAttribute("data-persona-composer-bar",""),ke.dataset.state="collapsed",ke.dataset.expandedSize=(B=O.expandedSize)!=null?B:"anchored",ke.style.zIndex=String((I=(T=n==null?void 0:n.launcher)==null?void 0:T.zIndex)!=null?I:vn),{wrapper:F,panel:Z,pillRoot:ke}}if(t){let O=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=v("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(F),{wrapper:O,panel:F}}if(!e){let O=v("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=v("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),Z=(P=(M=n==null?void 0:n.launcher)==null?void 0:M.width)!=null?P:"100%";return O.style.width=Z,F.style.width="100%",O.appendChild(F),{wrapper:O,panel:F}}let o=(C=n==null?void 0:n.launcher)!=null?C:{},s=o.position&&fr[o.position]?fr[o.position]:fr["bottom-right"],a=v("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((q=(k=n==null?void 0:n.launcher)==null?void 0:k.zIndex)!=null?q:vn);let i=v("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(R=(_=n==null?void 0:n.launcher)==null?void 0:_.width)!=null?R:n==null?void 0:n.launcherWidth,c=d!=null?d:Vr;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},oy=(n,e)=>{var M,P,C,k,q,_,R,O,F;let t=v("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");t.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Za(n,{showClose:e,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(P=(M=n==null?void 0:n.launcher)==null?void 0:M.clearChat)==null?void 0:P.enabled)!=null?C:!0,a=null,i=null;if(s){let Z=ei(n,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=Z.button,i=Z.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let d=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),c=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"},style:{paddingTop:"48px"}});c.style.setProperty("scrollbar-gutter","stable");let p=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(q=(k=n==null?void 0:n.copy)==null?void 0:k.welcomeTitle)!=null?q:"Hello \u{1F44B}"}),g=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(R=(_=n==null?void 0:n.copy)==null?void 0:_.welcomeSubtitle)!=null?R:"Ask anything about your account or products."}),h=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,g),m=v("div","persona-flex persona-flex-col persona-gap-3"),y=(O=n==null?void 0:n.layout)==null?void 0:O.contentMaxWidth;y&&(m.style.maxWidth=y,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((F=n==null?void 0:n.copy)==null?void 0:F.showWelcomeCard)!==!1||(h.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(h,m);let E=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),B=_m({config:n}),{root:T,textNode:I}=Om();return t.append(d,o,c,E),i&&t.appendChild(i),{container:t,body:c,messagesWrapper:m,composerOverlay:E,suggestions:B.suggestions,textarea:B.textarea,sendButton:B.sendButton,sendButtonWrapper:B.sendButtonWrapper,micButton:B.micButton,micButtonWrapper:B.micButtonWrapper,composerForm:B.composerForm,statusText:B.statusText,introTitle:p,introSubtitle:g,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:v("span"),headerTitle:v("span"),headerSubtitle:v("span"),header:d,footer:B.footer,attachmentButton:B.attachmentButton,attachmentButtonWrapper:B.attachmentButtonWrapper,attachmentInput:B.attachmentInput,attachmentPreviewsContainer:B.attachmentPreviewsContainer,actionsRow:B.actionsRow,leftActions:B.leftActions,rightActions:B.rightActions,setSendButtonMode:B.setSendButtonMode,peekBanner:T,peekTextNode:I}},Um=(n,e=!0)=>{var E,B,T,I,M,P,C,k,q;if(la(n))return oy(n,e);let t=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(E=n==null?void 0:n.layout)==null?void 0:E.header,o=((B=n==null?void 0:n.layout)==null?void 0:B.showHeader)!==!1,s=r?ti(n,r,{showClose:e}):zo({config:n,showClose:e}),a=Mt("div",{className:"persona-widget-body persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-gap-6 persona-overflow-y-auto persona-bg-persona-container persona-px-6 persona-py-6",attrs:{id:"persona-scroll-container","data-persona-theme-zone":"messages"}});a.style.setProperty("scrollbar-gutter","stable");let i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(I=(T=n==null?void 0:n.copy)==null?void 0:T.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(P=(M=n==null?void 0:n.copy)==null?void 0:M.welcomeSubtitle)!=null?P:"Ask anything about your account or products."}),c=Mt("div",{className:"persona-rounded-2xl persona-p-6",attrs:{"data-persona-intro-card":""},style:{background:"var(--persona-intro-card-bg, var(--persona-surface, #ffffff))",boxShadow:gn(n)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=v("div","persona-flex persona-flex-col persona-gap-3"),g=(C=n==null?void 0:n.layout)==null?void 0:C.contentMaxWidth;g&&(p.style.maxWidth=g,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((k=n==null?void 0:n.copy)==null?void 0:k.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let m=li({config:n}),y=((q=n==null?void 0:n.layout)==null?void 0:q.showFooter)!==!1;o?ca(t,s,n):(s.header.style.display="none",ca(t,s,n)),t.append(a);let w=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}});return y||(m.footer.style.display="none"),t.append(m.footer),t.append(w),{container:t,body:a,messagesWrapper:p,composerOverlay:w,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:d,closeButton:s.closeButton,closeButtonWrapper:s.closeButtonWrapper,clearChatButton:s.clearChatButton,clearChatButtonWrapper:s.clearChatButtonWrapper,iconHolder:s.iconHolder,headerTitle:s.headerTitle,headerSubtitle:s.headerSubtitle,header:s.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var Zi=(n,e)=>{let t=v("button");t.type="button",t.innerHTML=`
|
|
20
20
|
<span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
|
|
21
21
|
<img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
|