@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/index.cjs CHANGED
@@ -8,14 +8,14 @@ ${t}`:"")+(e.description?`
8
8
  ${e.description}`:"");return window.confirm(n)},py=e=>{if(e==null)return"";try{let t=JSON.stringify(e,null,2);return t.length>500?t.slice(0,500)+"\u2026":t}catch{return String(e)}},uy=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},my=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var gy="agent_",fy="flow_";function jm(e){return e.startsWith(gy)?{kind:"agentId",agentId:e}:e.startsWith(fy)?{kind:"flowId",flowId:e}:null}function Um(e,t){let n=e.trim();if(!n)throw new Error("[Persona] `target` is empty.");let r=n.indexOf(":");if(r>0){let a=n.slice(0,r),i=n.slice(r+1);if(a==="runtype"){let c=jm(i);if(c)return c;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let d=t==null?void 0:t[a];if(!d)throw new Error(`[Persona] No target provider registered for "${a}". Add a \`targetProviders.${a}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:d(i).payload}}let o=jm(n);if(o)return o;let s=t==null?void 0:t.default;if(s)return{kind:"payload",payload:s(n).payload};throw new Error(`[Persona] target "${n}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${n}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var So=require("partial-json");var y=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Mt=(e,t={},...n)=>{let r=document.createElement(e);if(t.className&&(r.className=t.className),t.text!==void 0&&(r.textContent=t.text),t.attrs)for(let[s,a]of Object.entries(t.attrs))r.setAttribute(s,a);if(t.style){let s=r.style,a=t.style;for(let i of Object.keys(a)){let d=a[i];d!=null&&(s[i]=d)}}let o=n.filter(s=>s!=null);return o.length>0&&r.append(...o),r},ma=(...e)=>e.filter(Boolean).join(" ");var fa="ask_user_question",ga=8,Rs="data-persona-ask-sheet-for",hy="Other",yy="Other\u2026",zm="Type your own answer here",Vm="Send",by="Next",xy="Back",vy="Submit all",wy="Skip",Cy=3,El="data-ask-current-index",Ml="data-ask-question-count",Km="data-ask-answers",kl="data-ask-grouped",Gm="data-ask-layout",Ay=e=>e.layout==="pills"?"pills":"rows",Sy=e=>e.getAttribute(Gm)==="pills"?"pills":"rows",qm=!1,Jm=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===fa,ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Xr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,So.parse)(o,So.STR|So.OBJ|So.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},ha=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>ga&&!qm&&(qm=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${ga}.`)),t.slice(0,ga)},Ty=e=>{var t;return(t=ha(e)[0])!=null?t:null},Ey=(e,t)=>{var n;return(n=ha(e)[t])!=null?n:null},Xm=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},Qm=(e,t,n)=>{if(e!=="rows")return null;let r=y("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let o=y("span","persona-ask-row-check");r.appendChild(o)}else{let o=y("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},My=(e,t,n,r)=>{let s=y("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=y("span","persona-ask-row-content"),i=y("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let c=y("span","persona-ask-row-description");c.textContent=e.description,a.appendChild(c)}s.appendChild(a);let d=Qm(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},ky=e=>{let n=y("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},Ly=(e,t,n,r)=>{var p,u,f;let s=y("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<Cy;g++)s.appendChild(ky(r));return s}if(d.forEach((g,b)=>{s.appendChild(My(g,b,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?hy:yy;if(r==="rows"){let b=y("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");b.setAttribute("data-ask-user-action","focus-free-text"),b.setAttribute("data-option-index",String(d.length)),b.setAttribute("data-ask-other-row","true");let v=y("span","persona-ask-row-content"),T=document.createElement("input");T.type="text",T.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",T.placeholder=(p=t.freeTextPlaceholder)!=null?p:zm,T.setAttribute("data-ask-free-text-input","true"),T.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),v.appendChild(T),b.appendChild(v);let E=Qm(r,a,d.length);E&&b.appendChild(E),s.appendChild(b)}else{let b=y("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");b.type="button",b.setAttribute("data-ask-user-action","open-free-text"),b.textContent=(f=t.freeTextLabel)!=null?f:g,s.appendChild(b)}}return s},Ym=(e,t)=>{var s,a;let r=y("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:zm,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),t!=="rows"){let i=y("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:Vm,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Py=e=>{var r;let t=y("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=y("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:Vm,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Iy=(e,t,n)=>{var c,p,u,f;let r=y("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let o=y("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(c=n.backLabel)!=null?c:xy,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=y("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=y("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:wy,a.setAttribute("data-ask-user-action","skip"),s.appendChild(a);let i=y("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:vy:(f=n.nextLabel)!=null?f:by,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},os=e=>{let t=e.getAttribute(Km);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zm=(e,t)=>{e.setAttribute(Km,JSON.stringify(t))},rr=e=>{var n;let t=Number((n=e.getAttribute(El))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Ry=(e,t)=>{e.setAttribute(El,String(Math.max(0,Math.floor(t))))},Ws=e=>{var n;let t=Number((n=e.getAttribute(Ml))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},To=e=>e.getAttribute(kl)==="true",Wy=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},Hy=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ti=(e,t)=>{let{payload:n}=Xr(t),r=ha(n),o=os(e),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},eg=e=>{let t=os(e),n=rr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let c=(u=d.getAttribute("data-option-label"))!=null?u:"",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=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},tg=e=>{if(!To(e))return;let t=os(e),n=rr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Ll=(e,t,n)=>{let r=ei(n),o=Sy(e),{payload:s,complete:a}=Xr(t),i=To(e),d=rr(e),c=Ws(e),p=i?Ey(s,d):Ty(s),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${c}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let b=e.querySelector('[data-ask-question="true"]');if(b){let P=typeof(p==null?void 0:p.question)=="string"?p.question:"";b.textContent=P,b.classList.toggle("persona-ask-question-skeleton",!P&&!a)}let v=e.querySelector('[data-ask-pill-list="true"]');if(v){let P=Ly(p,r,a,o);v.replaceWith(P)}if(o!=="rows"){let P=e.querySelector('[data-ask-free-text-row="true"]');P&&P.replaceWith(Ym(r,o))}let T=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!T?e.appendChild(Py(r)):(!u||i)&&T&&T.remove(),e.setAttribute("data-multi-select",u?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let P=Iy(d,c,r);E?E.replaceWith(P):e.appendChild(P)}else E&&E.remove();eg(e),tg(e)},By=(e,t,n)=>{let r=ei(t),o=Ay(r),s=e.toolCall.id,a=ha(n),i=Math.max(1,a.length),d=i>1,c=Wy(e,a),p=d?Hy(e,i):0,u=y("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(Rs,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(Ml,String(i)),u.setAttribute(El,String(p)),u.setAttribute(kl,d?"true":"false"),u.setAttribute(Gm,o),Zm(u,c),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),Xm(u,r);let f=y("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=y("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let b=y("span","persona-ask-sheet-step-inline");b.setAttribute("data-ask-step-inline","true"),b.textContent="",f.appendChild(b),u.appendChild(f);let T=y("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return T.setAttribute("data-ask-pill-list","true"),T.setAttribute("role","group"),u.appendChild(T),o!=="rows"&&u.appendChild(Ym(r,o)),Ll(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},Dy=(e,t,n)=>{let{payload:r}=Xr(t),o=Math.max(1,ha(r).length);o>Ws(e)&&(e.setAttribute(Ml,String(o)),o>1&&!To(e)&&e.setAttribute(kl,"true")),Ll(e,t,n)},ng=(e,t)=>{let n=y("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=ei(t);Xm(n,r);let o=y("span","persona-ask-stub-label"),{complete:s}=Xr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},Hs=(e,t,n)=>{if(!n||!Jr(e)||ei(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${Rs}]`).forEach(c=>{c.getAttribute(Rs)!==o&&c.remove()});let a=n.querySelector(`[${Rs}="${Jm(o)}"]`);if(a){Dy(a,e,t);return}let{payload:i}=Xr(e),d=By(e,t,i);n.appendChild(d)},Eo=(e,t)=>{if(!e)return;let n=t?`[${Rs}="${Jm(t)}"]`:`[${Rs}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Pl=e=>Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]')).map(t=>t.getAttribute("data-option-label")).filter(t=>typeof t=="string"&&t.length>0),Mo=(e,t)=>{let n=os(e),r=rr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Zm(e,n),eg(e),tg(e)},ni=(e,t,n,r)=>{let o=Ws(e),s=Math.max(0,Math.min(o-1,r));Ry(e,s),Ll(e,t,n)};var br="suggest_replies";var Il={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},ri={name:br,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:Il,origin:"sdk",annotations:{readOnlyHint:!0}},Rl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ya=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===br},Wl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},oi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ya(r))continue;let o=Wl((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},rg=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Hl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:ga,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},Bl={name:fa,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:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},ba=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(Bl),rg(e)&&t.push(ri),t};var Qr=require("partial-json"),si=e=>e.replace(/\\n/g,`
9
9
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ko=e=>{if(e===null)return"null";if(e===void 0)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return String(e);try{return JSON.stringify(e,null,2)}catch{return String(e)}},Ny=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},og=e=>e.status==="complete"?Ny(e):e.status==="pending"?"Waiting":"",Oy=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var sg=e=>e.status==="complete"?Oy(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},va=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},ii=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},Dl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=va(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},li=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&xa(r,n.slice(s,a.index),[]),a[1]!==void 0?xa(r,a[1],["bold"]):a[2]!==void 0?xa(r,a[2],["italic"]):a[3]!==void 0&&xa(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&xa(r,n.slice(s),[]),r},xa=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Fy=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
11
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},wa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=Fy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Qr.parse)(n,Qr.STR|Qr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ag=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Qr.parse)(s,Qr.STR|Qr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ig="4.6.0";var or=ig;var $y="https://api.runtype.com/v1/dispatch",mi="https://api.runtype.com";function jy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Nl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Uy(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var lg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function qy(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lg(n);if(!lg(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=wa(e);return wa(t)!==null&&a===null?t:e}var ss=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:$y,this.headers={"Content-Type":"application/json","X-Persona-Version":or,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Uy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Is(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Um(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Nl).map(M=>{var L,C,R;return{id:M.id,role:M.role,content:(R=(C=(L=M.contentParts)!=null?L:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.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}},f=c.clientTools,g=!!(f&&f.length>0),b=g?$m(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,T=g&&v&&this.lastSentClientToolsFingerprint===b,E=!1,P=null,I;for(let M=0;;M++){let C={...u,...g&&(E||!T)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};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":or},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&g){let R=await I.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=R!=null?R:{error:"Chat request failed"}}break}if(!I.ok){let M=P!=null?P: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 n({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let L=new Error(M.error||"Failed to send message");throw n({type:"error",error:L}),L}if(!I.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(I.body,n,t.assistantMessageId)}finally{n({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")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||mi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Nl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Nl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let 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(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var hn,vr,wr,qe;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=k=>{let me=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,Ee=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,Le=k.tools?k.tools.map(Be=>({...Be,chunks:Be.chunks?[...Be.chunks]:void 0})):void 0;return{...k,reasoning:me,toolCall:Ee,tools:Le}},f=k=>{if(k.role!=="assistant"||k.variant)return!0;let me=Array.isArray(k.contentParts)&&k.contentParts.length>0,Ee=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||me||Ee||!!k.stopReason},g=k=>{f(k)&&n({type:"message",message:u(k)})},b=null,v=null,T={current:null},E={current:null},P=null,I="",M=new Map,L=new Map,C=new Map,R=new Map,U=new Map,j={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},O=k=>{if(k==null)return null;try{return String(k)}catch{return null}},F=k=>{var me,Ee,Le,Be,rt;return O((rt=(Be=(Le=(Ee=(me=k.stepId)!=null?me:k.step_id)!=null?Ee:k.step)!=null?Le:k.parentId)!=null?Be:k.flowStepId)!=null?rt:k.flow_step_id)},ee=k=>{var me,Ee,Le,Be,rt,Ye,yt;return O((yt=(Ye=(rt=(Be=(Le=(Ee=(me=k.callId)!=null?me:k.call_id)!=null?Ee:k.requestId)!=null?Le:k.request_id)!=null?Be:k.toolCallId)!=null?rt:k.tool_call_id)!=null?Ye:k.stepId)!=null?yt:k.step_id)},Me=r,pe=!1,te=()=>{if(b)return b;let k,me="",Ee=P;return!pe&&Me?(k=Me,pe=!0,me=o!=null?o:""):Me&&Ee?k=`${Me}_${Ee}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:k,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Pe=(k,me)=>{j.lastId=me,k&&j.byStep.set(k,me)},Ie=(k,me)=>{var rt;let Ee=(rt=k.reasoningId)!=null?rt:k.id,Le=F(k);if(Ee){let Ye=String(Ee);return Pe(Le,Ye),Ye}if(Le){let Ye=j.byStep.get(Le);if(Ye)return j.lastId=Ye,Ye}if(j.lastId&&!me)return j.lastId;if(!me)return null;let Be=`reason-${p()}`;return Pe(Le,Be),Be},re=k=>{let me=R.get(k);if(me)return me;let Ee={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:k,status:"streaming",chunks:[]}};return R.set(k,Ee),g(Ee),Ee},Se=(k,me)=>{W.lastId=me,k&&W.byCall.set(k,me)},oe=new Set,ae=new Map,ie=new Set,ye=new Map,je=k=>{if(!k)return!1;let me=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},K=(k,me)=>{var rt;let Ee=(rt=k.toolId)!=null?rt:k.id,Le=ee(k);if(Ee){let Ye=String(Ee);return Se(Le,Ye),Ye}if(Le){let Ye=W.byCall.get(Le);if(Ye)return W.lastId=Ye,Ye}if(W.lastId&&!me)return W.lastId;if(!me)return null;let Be=`tool-${p()}`;return Se(Le,Be),Be},Y=k=>{let me=U.get(k);if(me)return me;let Ee={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:k,status:"pending"}};return U.set(k,Ee),g(Ee),Ee},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let me=Number(k);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Ee=Date.parse(k);if(!Number.isNaN(Ee))return Ee}return Date.now()},X=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},ce=new Map,Re=new Map,be=new Map,Ge=(k,me,Ee)=>{var yt;let Le=be.get(k);Le||(Le=[],be.set(k,Le));let Be=0,rt=Le.length;for(;Be<rt;){let ge=Be+rt>>>1;Le[ge].seq<me?Be=ge+1:rt=ge}((yt=Le[Be])==null?void 0:yt.seq)===me?Le[Be]={seq:me,text:Ee}:Le.splice(Be,0,{seq:me,text:Ee});let Ye="";for(let ge=0;ge<Le.length;ge++)Ye+=Le[ge].text;return Ye},ft=(k,me)=>{let Ee=X(me),Le=Re.get(k.id),Be=qy(Le,Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=de=>{var Xe;let ht=(Xe=k.content)!=null?Xe:"";de.trim()!==""&&(ht.trim().length===0||de.startsWith(ht)||de.trimStart().startsWith(ht.trim()))&&(k.content=de)},yt=()=>{var de;if(rt){let ht=(de=rt.close)==null?void 0:de.call(rt);ht instanceof Promise&&ht.catch(()=>{})}ce.delete(k.id),Re.delete(k.id),k.streaming=!1,g(k)};if(!rt){Ye(Ee),yt();return}let ge=wa(Be);if(ge!==null&&ge.trim()!==""){Ye(ge),yt();return}let D=de=>{var Pt;let ht=typeof de=="string"?de:(Pt=de==null?void 0:de.text)!=null?Pt:null;if(ht!==null&&ht.trim()!=="")return ht;let Xe=rt.getExtractedText();return Xe!==null&&Xe.trim()!==""?Xe:Ee},ve;try{ve=rt.processChunk(Be)}catch{Ye(Ee),yt();return}if(ve instanceof Promise){ve.then(de=>{Ye(D(de)),yt()}).catch(()=>{Ye(Ee),yt()});return}Ye(D(ve)),yt()},Ht=null,nt=(k,me,Ee,Le)=>{var ge;k.rawContent=me,ce.has(k.id)||ce.set(k.id,this.createStreamParser());let Be=ce.get(k.id),rt=me.trim().startsWith("{")||me.trim().startsWith("[");if(rt&&Re.set(k.id,me),Be.__isPlainTextParser===!0){k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k);return}let yt=Be.processChunk(me);if(yt instanceof Promise)yt.then(D=>{var de;let ve=typeof D=="string"?D:(de=D==null?void 0:D.text)!=null?de:null;ve!==null&&ve.trim()!==""?(k.content=ve,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k)});else{let D=typeof yt=="string"?yt:(ge=yt==null?void 0:yt.text)!=null?ge:null;D!==null&&D.trim()!==""?(k.content=D,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}},fe=(k,me)=>{var ge,D;let Ee=me!=null?me:k.content;if(Ee==null||Ee===""){k.streaming=!1,g(k);return}let Le=Re.get(k.id),Be=Le!=null?Le:X(Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=null,yt=!1;if(rt&&(Ye=rt.getExtractedText(),Ye===null&&(Ye=wa(Be)),Ye===null)){let ve=rt.processChunk(Be);ve instanceof Promise?(yt=!0,ve.then(de=>{var Xe;let ht=typeof de=="string"?de:(Xe=de==null?void 0:de.text)!=null?Xe:null;ht!==null&&(k.content=ht,k.streaming=!1,ce.delete(k.id),Re.delete(k.id),g(k))}).catch(()=>{})):Ye=typeof ve=="string"?ve:(ge=ve==null?void 0:ve.text)!=null?ge:null}if(!yt){Ye!==null&&Ye.trim()!==""?k.content=Ye:Re.has(k.id)||(k.content=X(Ee));let ve=ce.get(k.id);if(ve){let de=(D=ve.close)==null?void 0:D.call(ve);de instanceof Promise&&de.catch(()=>{}),ce.delete(k.id)}Re.delete(k.id),k.streaming=!1,g(k)}},Q=(k,me,Ee)=>{let Le=L.get(k);if(Le)return Le;let Be={id:`nested-${me}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return L.set(k,Be),g(Be),Be},lt=[],Ke,Te=new Map,Ce=0,et="agent",zt=!1,xe=null,ue=null,wn=new Map,At=(hn=this.config.iterationDisplay)!=null?hn:"separate";for(Ke=()=>{var k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co,Ae,Ur,Qn,_t,Yn,qr,Qs,hs,Ys,Uo,Mr,po,ct,sn,an,kr,Zs,zr,qo,Lr,_,ys,pr,Pr,Vr,Ir,ur,bs,qa,yn,An,mr,Sn,zo,gr,bn,Rr,xs,Vo,vs,uo;for(let mo=0;mo<lt.length;mo++){let st=lt[mo].payloadType,w=lt[mo].payload;if(!zt&&et!=="flow"&&typeof w.stepType=="string"&&(et="flow"),st==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z),Q(V,z,"reasoning");continue}let J=(k=Ie(w,!0))!=null?k:`reason-${p()}`,G=re(J);G.reasoning=(me=G.reasoning)!=null?me:{id:J,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:ke((Ee=w.startedAt)!=null?Ee:w.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),G.streaming=!0,G.reasoning.status="streaming",g(G)}else if(st==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let Oe=L.get(V),ot=(Ye=(rt=(Be=w.reasoningText)!=null?Be:w.text)!=null?rt:w.delta)!=null?Ye:"";ot&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(ot)),g(Oe));continue}let z=(ge=(yt=Ie(w,!1))!=null?yt:Ie(w,!0))!=null?ge:`reason-${p()}`,J=re(z);J.reasoning=(D=J.reasoning)!=null?D:{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=(de=J.reasoning.startedAt)!=null?de:ke((ve=w.startedAt)!=null?ve:w.timestamp);let G=(Pt=(Xe=(ht=w.reasoningText)!=null?ht:w.text)!=null?Xe:w.delta)!=null?Pt:"";if(G&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let ot=Ge(z,Oe,String(G));J.reasoning.chunks=[ot]}else J.reasoning.chunks.push(String(G))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=ke((kt=w.completedAt)!=null?kt:w.timestamp);let Oe=(vt=J.reasoning.startedAt)!=null?vt:Date.now();J.reasoning.durationMs=Math.max(0,((Wt=J.reasoning.completedAt)!=null?Wt:Date.now())-Oe)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(st==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let ot=L.get(V);if(ot.reasoning){let dt=typeof w.text=="string"?w.text:"";dt&&ot.reasoning.chunks.length===0&&ot.reasoning.chunks.push(dt),ot.reasoning.status="complete",ot.streaming=!1,g(ot)}M.delete(V),L.delete(V);continue}let z=(Ft=(Qt=Ie(w,!1))!=null?Qt:Ie(w,!0))!=null?Ft:`reason-${p()}`,J=typeof w.text=="string"?w.text:"";!R.get(z)&&(J||w.scope==="loop")&&re(z);let G=R.get(z);if(G!=null&&G.reasoning){(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),J&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(J),G.reasoning.status="complete",G.reasoning.completedAt=ke((tn=w.completedAt)!=null?tn:w.timestamp);let ot=(Cr=G.reasoning.startedAt)!=null?Cr:Date.now();G.reasoning.durationMs=Math.max(0,((Fr=G.reasoning.completedAt)!=null?Fr:Date.now())-ot),G.streaming=!1,g(G)}let Oe=F(w);Oe&&j.byStep.delete(Oe)}else if(st==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(ir=(ar=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?ar:K(w,!0))!=null?ir:`tool-${p()}`,z=(no=w.toolName)!=null?no:w.name;if(je(z)){oe.add(V);continue}Se(ee(w),V);let J=Y(V),G=(Vt=J.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=z!=null?z:G.name,G.status="running",w.parameters!==void 0?G.args=w.parameters:w.args!==void 0&&(G.args=w.args),G.startedAt=(_r=G.startedAt)!=null?_r:ke((lr=w.startedAt)!=null?lr:w.timestamp),G.completedAt=void 0,G.durationMs=void 0,J.toolCall=G,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(w,!1))!=null?Bn:K(w,!0))!=null?Ln:`tool-${p()}`;if(oe.has(V))continue;let z=Y(V),J=(Dn=z.toolCall)!=null?Dn:{id:V,status:"running"};J.startedAt=(Ar=J.startedAt)!=null?Ar:ke((cr=w.startedAt)!=null?cr:w.timestamp);let G=(oo=(Gn=(ro=w.text)!=null?ro:w.delta)!=null?Gn:w.message)!=null?oo:"";G&&(J.chunks=(St=J.chunks)!=null?St:[],J.chunks.push(String(G))),J.status="running",z.toolCall=J,z.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=($r=z.agentMetadata)!=null?$r:{executionId:(Sr=Oe==null?void 0:Oe.executionId)!=null?Sr:w.executionId,iteration:(Tr=Oe==null?void 0:Oe.iteration)!=null?Tr:w.iteration}),g(z)}else if(st==="tool_complete"){let V=(bt=(dr=K(w,!1))!=null?dr:K(w,!0))!=null?bt:`tool-${p()}`;if(oe.has(V)){oe.delete(V);continue}let z=Y(V),J=(Fo=z.toolCall)!=null?Fo:{id:V,status:"running"};J.status="complete",w.result!==void 0&&(J.result=w.result),typeof w.duration=="number"&&(J.duration=w.duration),J.completedAt=ke((Er=w.completedAt)!=null?Er:w.timestamp);let G=(_o=w.duration)!=null?_o:w.executionTime;if(typeof G=="number")J.durationMs=G;else{let dt=(Pn=J.startedAt)!=null?Pn:Date.now();J.durationMs=Math.max(0,((fs=J.completedAt)!=null?fs:Date.now())-dt)}z.toolCall=J,z.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=(ao=z.agentMetadata)!=null?ao:{executionId:(so=Oe==null?void 0:Oe.executionId)!=null?so:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g(z);let ot=ee(w);ot&&W.byCall.delete(ot)}else if(st==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,z=(io=V!=null?V:w.toolId)!=null?io:`local-${p()}`,J=Y(z),G=w.toolName,Oe=w.origin==="webmcp"&&!Ao(G)?`webmcp:${G}`:G,ot=Ao(Oe),dt=($o=J.toolCall)!=null?$o:{id:z,status:"pending"};dt.name=Oe,dt.args=w.parameters,dt.status=ot?"running":"complete",dt.chunks=(jo=dt.chunks)!=null?jo:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:ke((wt=(lo=w.startedAt)!=null?lo:w.timestamp)!=null?wt:w.awaitedAt),ot?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(On=dt.completedAt)!=null?On:dt.startedAt,J.toolCall=dt,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(Tt=w.executionId)!=null?Tt:(Cn=J.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(J)}else if(st==="text_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z);continue}let J=b;J&&(et==="flow"?(fe(J),Ht=J):(J.streaming=!1,g(J)),b=null),P=typeof w.id=="string"?w.id:P,I=""}else if(st==="text_delta"){let V=typeof w.id=="string"?w.id:null,z=V?M.get(V):void 0;if(V&&z){let G=typeof w.delta=="string"?w.delta:"",Oe=((Jn=C.get(V))!=null?Jn:"")+G;if(C.set(V,Oe),Oe.trim()==="")continue;let ot=Q(V,z);ot.agentMetadata={...ot.agentMetadata,executionId:w.executionId,parentToolId:z},nt(ot,Oe,G,void 0);continue}if(P=typeof w.id=="string"?w.id:P,et==="flow"){let G=typeof w.delta=="string"?w.delta:"";if(I+=G,I.trim()==="")continue;let Oe=te();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},nt(Oe,I,G,void 0),v=Oe;continue}let J=te();J.content+=(Xn=w.delta)!=null?Xn:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:xe!=null?xe:void 0,agentName:ue==null?void 0:ue.agentName},v=J,g(J)}else if(st==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)){let J=L.get(V);J&&fe(J),M.delete(V),C.delete(V),L.delete(V);continue}let z=b;z&&(et==="flow"?(fe(z),Ht=z):(((Fn=z.content)!=null?Fn:"")===""&&typeof w.text=="string"&&(z.content=w.text),z.streaming=!1,g(z)),b=null),P=null,I=""}else if(st==="step_complete"){let V=w.stepType,z=w.executionType;if(V==="tool"||z==="context")continue;if(w.success===!1){let J=w.error,G=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&"message"in J?String((co=J.message)!=null?co:"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let Oe=b;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),n({type:"status",status:"idle"});continue}{let J=Ht;Ht=null;let G=w.stopReason,Oe=(Ae=w.result)==null?void 0:Ae.response;if(J)G&&(J.stopReason=G),Oe!=null?ft(J,Oe):J.streaming!==!1&&(ce.delete(J.id),Re.delete(J.id),J.streaming=!1,g(J));else{let ot=Oe!=null&&Oe!=="";if(ot||G){let dt=te();G&&(dt.stopReason=G),ot?fe(dt,Oe):(dt.streaming=!1,g(dt))}}continue}}else if(st==="execution_start")et=w.kind==="flow"?"flow":"agent",zt=!0,et==="agent"&&(ue={executionId:w.executionId,agentId:(Ur=w.agentId)!=null?Ur:"virtual",agentName:(Qn=w.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=w.maxTurns)!=null?_t:1,startedAt:ke(w.startedAt)});else if(st==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let z=b;z&&(z.streaming=!1,g(z),wn.set(V-1,z),b=null)}Ce=V}xe=typeof w.id=="string"?w.id:null,v=null}else if(st==="tool_input_delta"){let V=(Yn=w.toolCallId)!=null?Yn:W.lastId;if(V){let z=U.get(V);z!=null&&z.toolCall&&(z.toolCall.chunks=(qr=z.toolCall.chunks)!=null?qr:[],z.toolCall.chunks.push((Qs=w.delta)!=null?Qs:""),g(z))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=w.stopReason,z=b!=null?b:v;if(V&&z!==null){let J=w.id;(!J||((hs=z.agentMetadata)==null?void 0:hs.turnId)===J)&&(z.stopReason=V,g(z))}xe===w.id&&(xe=null)}else if(st==="media_start"){let V=String(w.id);Te.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Te.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(st==="media_complete"){let V=String(w.id),z=Te.get(V);Te.delete(V);let J=(Uo=(Ys=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ys:z==null?void 0:z.mediaType)!=null?Uo:"application/octet-stream",G=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:z&&z.parts.length>0?z.parts.join(""):void 0,ot=null;if(G)ot={type:"media",data:G,mediaType:J};else if(Oe){let In=J.toLowerCase();ot={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:J}}let dt=(Mr=w.toolCallId)!=null?Mr:z==null?void 0:z.toolCallId,pl=ot?[ot]:[],go=[];for(let In of pl){if(!In||typeof In!="object")continue;let Yt=In,fo=typeof Yt.type=="string"?Yt.type:void 0,Zn=typeof Yt.mediaType=="string"?Yt.mediaType.toLowerCase():"",Tn=null,Rn="";if(fo==="media"){let En=typeof Yt.data=="string"?Yt.data:void 0;if(!En)continue;Rn=Zn.length>0?Zn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(fo==="image-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else if(fo==="file-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else continue;if(Tn)if(fo==="image-url"||Rn.startsWith("image/"))go.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))go.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))go.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";go.push({type:"file",data:Tn,mimeType:En,filename:jy(En)})}}if(go.length>0){let In=p(),Yt=dt,Zn={id:`agent-media-${typeof Yt=="string"&&Yt.length>0?`${Yt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:go,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Zn);let Tn=b;Tn&&(Tn.streaming=!1,g(Tn)),b=null,T.current=null}}else if(st==="execution_complete"){let V=(po=w.kind)!=null?po:et;V==="agent"&&ue&&(ue.status=w.success?"complete":"error",ue.completedAt=ke(w.completedAt),ue.stopReason=w.stopReason);let z=b;z&&(V==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,g(z)),b=null),P=null,I="",Ht=null,n({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof w.error=="string"?w.error:(sn=(ct=w.error)==null?void 0:ct.message)!=null?sn:"Execution error";n({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(an=w.approvalId)!=null?an:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(kr=ue==null?void 0:ue.agentId)!=null?kr:"virtual",executionId:(zr=(Zs=w.executionId)!=null?Zs:ue==null?void 0:ue.executionId)!=null?zr:"",toolName:(qo=w.toolName)!=null?qo:"",toolType:w.toolType,description:(_=w.description)!=null?_:`Execute ${(Lr=w.toolName)!=null?Lr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let V=(ys=w.approvalId)!=null?ys:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(pr=ue==null?void 0:ue.agentId)!=null?pr:"virtual",executionId:(Vr=(Pr=w.executionId)!=null?Pr:ue==null?void 0:ue.executionId)!=null?Vr:"",toolName:(Ir=w.toolName)!=null?Ir:"",toolType:w.toolType,description:(bs=w.description)!=null?bs:`Execute ${(ur=w.toolName)!=null?ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="approval_complete"){let V=w.approvalId;if(V){let J={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(qa=w.decision)!=null?qa:"approved",agentId:(yn=ue==null?void 0:ue.agentId)!=null?yn:"virtual",executionId:(mr=(An=w.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?mr:"",toolName:(Sn=w.toolName)!=null?Sn:"",description:(zo=w.description)!=null?zo:"",resolvedAt:Date.now()}};g(J)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=w.artifactType,z=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:z,artifactType:V,title:J,component:typeof w.component=="string"?w.component:void 0}),ye.set(z,{markdown:"",title:J}),!ie.has(z)){ie.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:J,artifactType:V,status:"streaming"}})};ae.set(z,G),g(G)}}else if(st==="artifact_delta"){let V=String(w.id),z=typeof w.delta=="string"?w.delta:String((gr=w.delta)!=null?gr:"");n({type:"artifact_delta",id:V,artDelta:z});let J=ye.get(V);J&&(J.markdown+=z)}else if(st==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let z=ae.get(V);if(z){z.streaming=!1;try{let J=JSON.parse((bn=z.rawContent)!=null?bn:"{}");if(J.props){J.props.status="complete";let G=ye.get(V);G!=null&&G.markdown&&(J.props.markdown=G.markdown)}z.rawContent=JSON.stringify(J)}catch{}ye.delete(V),g(z),ae.delete(V)}}}else if(st==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let z=String((Rr=V.id)!=null?Rr:`msg-${p()}`),J=V.role,Oe={id:z,role:J==="user"?"user":J==="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(g(Oe),Oe.rawContent)try{let ot=JSON.parse(Oe.rawContent),dt=(xs=ot==null?void 0:ot.props)==null?void 0:xs.artifactId;typeof dt=="string"&&ie.add(dt)}catch{}b=null,T.current=null,ce.delete(z),Re.delete(z)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((Vo=w.error)==null?void 0:Vo.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(st==="dispatch_error"){let z=(vs=w.message)!=null?vs:w.error;z!=null&&z!==""&&(V=new Error(String(z)))}else{let z=w.error;typeof z=="string"&&z!==""?V=new Error(z):z!=null&&typeof z=="object"&&"message"in z&&(V=new Error(String((uo=z.message)!=null?uo:z)))}if(V){n({type:"error",error:V});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:k,value:me}=await s.read();if(k)break;i+=a.decode(me,{stream:!0});let Ee=i.split(`
11
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},wa=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=Fy();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Qr.parse)(n,Qr.STR|Qr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},ag=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Qr.parse)(s,Qr.STR|Qr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var ig="4.6.1";var or=ig;var $y="https://api.runtype.com/v1/dispatch",mi="https://api.runtype.com";function jy(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Nl=e=>!!(e.contentParts&&e.contentParts.length>0||e.llmContent&&e.llmContent.trim().length>0||e.rawContent&&e.rawContent.trim().length>0||e.content&&e.content.trim().length>0);function Uy(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var lg=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function qy(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=lg(n);if(!lg(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=wa(e);return wa(t)!==null&&a===null?t:e}var ss=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(n=t.apiUrl)!=null?n:$y,this.headers={"Content-Type":"application/json","X-Persona-Version":or,...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:Uy(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new Is(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:n,target:r,targetProviders:o}=this.config;if(!r)return{agentId:t,flowId:n};let s=Um(r,o);return s.kind==="agentId"?{agentId:s.agentId}:s.kind==="flowId"?{flowId:s.flowId}:{targetPayload:s.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,d,c;let t=((d=(i=this.config).getStoredSessionId)==null?void 0:d.call(i))||null,n=this.routing(),r=(c=n.agentId)!=null?c:n.flowId,o={token:this.config.clientToken,...r&&{flowId:r},...t&&{sessionId:t}},s=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let p=await s.json().catch(()=>({error:"Session initialization failed"}));throw s.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):s.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let a=await s.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(a.sessionId),{sessionId:a.sessionId,expiresAt:new Date(a.expiresAt),flow:a.flow,config:{welcomeMessage:a.config.welcomeMessage,placeholder:a.config.placeholder,theme:a.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":or},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isClientTokenMode()?this.dispatchClientToken(t,n):this.isAgentMode()?this.dispatchAgent(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let M=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:M}),M}let c=await this.buildPayload(t.messages),p=c.metadata?Object.fromEntries(Object.entries(c.metadata).filter(([M])=>M!=="sessionId"&&M!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Nl).map(M=>{var L,C,R;return{id:M.id,role:M.role,content:(R=(C=(L=M.contentParts)!=null?L:M.llmContent)!=null?C:M.rawContent)!=null?R:M.content}}),...t.assistantMessageId&&{assistantMessageId:t.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}},f=c.clientTools,g=!!(f&&f.length>0),b=g?$m(f):void 0,v=this.clientToolsFingerprintSessionId===d.sessionId,T=g&&v&&this.lastSentClientToolsFingerprint===b,E=!1,P=null,I;for(let M=0;;M++){let C={...u,...g&&(E||!T)&&f?{clientTools:f}:{},...b?{clientToolsFingerprint:b}:{}};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":or},body:JSON.stringify(C),signal:r.signal}),I.status===409&&M===0&&g){let R=await I.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}P=R!=null?R:{error:"Chat request failed"}}break}if(!I.ok){let M=P!=null?P: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 n({type:"error",error:C}),C}if(I.status===429){let C=new Error(M.hint||"Message limit reached for this session.");throw n({type:"error",error:C}),C}let L=new Error(M.error||"Failed to send message");throw n({type:"error",error:L}),L}if(!I.body){let M=new Error("No response body received");throw n({type:"error",error:M}),M}this.lastSentClientToolsFingerprint=b!=null?b:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(I.body,n,t.assistantMessageId)}finally{n({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")&&n({type:"error",error:c}),c}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r,o){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r,o)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||mi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var c,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((c=this.config.apiUrl)==null?void 0:c.replace(/\/+$/,""))||mi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var a,i,d;let n=this.routing().agentId;if(!this.config.agent&&!n)throw new Error("Agent configuration required for agent mode");let r=t.slice().filter(Nl).filter(c=>c.role==="user"||c.role==="assistant"||c.role==="system").filter(c=>!c.variant||c.variant==="assistant").sort((c,p)=>{let u=new Date(c.createdAt).getTime(),f=new Date(p.createdAt).getTime();return u-f}).map(c=>{var p,u,f;return{role:c.role,content:(f=(u=(p=c.contentParts)!=null?p:c.llmContent)!=null?u:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o={agent:(a=this.config.agent)!=null?a:{agentId:n},messages:r,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...ba(this.config),...(d=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?d:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async p=>{try{let u=await p({messages:t,config:this.config});u&&typeof u=="object"&&Object.assign(c,u)}catch(u){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",u)}})),Object.keys(c).length&&(o.context=c)}return o}async buildPayload(t){var a,i;let n=t.slice().filter(Nl).sort((d,c)=>{let p=new Date(d.createdAt).getTime(),u=new Date(c.createdAt).getTime();return p-u}).map(d=>{var c,p,u;return{role:d.role,content:(u=(p=(c=d.contentParts)!=null?c:d.llmContent)!=null?p:d.rawContent)!=null?u:d.content,createdAt:d.createdAt}}),r=this.routing(),o={messages:n,...r.agentId?{agent:{agentId:r.agentId}}:r.flowId?{flowId:r.flowId}:{}};if(r.targetPayload)for(let[d,c]of Object.entries(r.targetPayload))d!=="messages"&&(o[d]=c);let s=[...ba(this.config),...(i=await((a=this.webMcpBridge)==null?void 0:a.snapshotForDispatch()))!=null?i:[]];if(s.length>0&&(o.clientTools=s),this.contextProviders.length){let d={};await Promise.all(this.contextProviders.map(async c=>{try{let p=await c({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(d,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(d).length&&(o.context=d)}if(this.requestMiddleware)try{let d=await this.requestMiddleware({payload:{...o},config:this.config});if(d&&typeof d=="object"){let 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(t,n,r,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r,o){var hn,vr,wr,qe;let s=t.getReader(),a=new TextDecoder,i="",d=Date.now(),c=0,p=()=>d+c++,u=k=>{let me=k.reasoning?{...k.reasoning,chunks:[...k.reasoning.chunks]}:void 0,Ee=k.toolCall?{...k.toolCall,chunks:k.toolCall.chunks?[...k.toolCall.chunks]:void 0}:void 0,Le=k.tools?k.tools.map(Be=>({...Be,chunks:Be.chunks?[...Be.chunks]:void 0})):void 0;return{...k,reasoning:me,toolCall:Ee,tools:Le}},f=k=>{if(k.role!=="assistant"||k.variant)return!0;let me=Array.isArray(k.contentParts)&&k.contentParts.length>0,Ee=typeof k.rawContent=="string"&&k.rawContent.trim()!=="";return typeof k.content=="string"&&k.content.trim()!==""||me||Ee||!!k.stopReason},g=k=>{f(k)&&n({type:"message",message:u(k)})},b=null,v=null,T={current:null},E={current:null},P=null,I="",M=new Map,L=new Map,C=new Map,R=new Map,U=new Map,j={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},O=k=>{if(k==null)return null;try{return String(k)}catch{return null}},F=k=>{var me,Ee,Le,Be,rt;return O((rt=(Be=(Le=(Ee=(me=k.stepId)!=null?me:k.step_id)!=null?Ee:k.step)!=null?Le:k.parentId)!=null?Be:k.flowStepId)!=null?rt:k.flow_step_id)},ee=k=>{var me,Ee,Le,Be,rt,Ye,yt;return O((yt=(Ye=(rt=(Be=(Le=(Ee=(me=k.callId)!=null?me:k.call_id)!=null?Ee:k.requestId)!=null?Le:k.request_id)!=null?Be:k.toolCallId)!=null?rt:k.tool_call_id)!=null?Ye:k.stepId)!=null?yt:k.step_id)},Me=r,pe=!1,te=()=>{if(b)return b;let k,me="",Ee=P;return!pe&&Me?(k=Me,pe=!0,me=o!=null?o:""):Me&&Ee?k=`${Me}_${Ee}`:k=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,b={id:k,role:"assistant",content:me,createdAt:new Date().toISOString(),streaming:!0,sequence:p()},g(b),b},Pe=(k,me)=>{j.lastId=me,k&&j.byStep.set(k,me)},Ie=(k,me)=>{var rt;let Ee=(rt=k.reasoningId)!=null?rt:k.id,Le=F(k);if(Ee){let Ye=String(Ee);return Pe(Le,Ye),Ye}if(Le){let Ye=j.byStep.get(Le);if(Ye)return j.lastId=Ye,Ye}if(j.lastId&&!me)return j.lastId;if(!me)return null;let Be=`reason-${p()}`;return Pe(Le,Be),Be},re=k=>{let me=R.get(k);if(me)return me;let Ee={id:`reason-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:p(),reasoning:{id:k,status:"streaming",chunks:[]}};return R.set(k,Ee),g(Ee),Ee},Se=(k,me)=>{W.lastId=me,k&&W.byCall.set(k,me)},oe=new Set,ae=new Map,ie=new Set,ye=new Map,je=k=>{if(!k)return!1;let me=k.replace(/_+/g,"_").replace(/^_|_$/g,"");return me==="emit_artifact_markdown"||me==="emit_artifact_component"},K=(k,me)=>{var rt;let Ee=(rt=k.toolId)!=null?rt:k.id,Le=ee(k);if(Ee){let Ye=String(Ee);return Se(Le,Ye),Ye}if(Le){let Ye=W.byCall.get(Le);if(Ye)return W.lastId=Ye,Ye}if(W.lastId&&!me)return W.lastId;if(!me)return null;let Be=`tool-${p()}`;return Se(Le,Be),Be},Y=k=>{let me=U.get(k);if(me)return me;let Ee={id:`tool-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:p(),toolCall:{id:k,status:"pending"}};return U.set(k,Ee),g(Ee),Ee},ke=k=>{if(typeof k=="number"&&Number.isFinite(k))return k;if(typeof k=="string"){let me=Number(k);if(!Number.isNaN(me)&&Number.isFinite(me))return me;let Ee=Date.parse(k);if(!Number.isNaN(Ee))return Ee}return Date.now()},X=k=>{if(typeof k=="string")return k;if(k==null)return"";try{return JSON.stringify(k)}catch{return String(k)}},ce=new Map,Re=new Map,be=new Map,Ge=(k,me,Ee)=>{var yt;let Le=be.get(k);Le||(Le=[],be.set(k,Le));let Be=0,rt=Le.length;for(;Be<rt;){let ge=Be+rt>>>1;Le[ge].seq<me?Be=ge+1:rt=ge}((yt=Le[Be])==null?void 0:yt.seq)===me?Le[Be]={seq:me,text:Ee}:Le.splice(Be,0,{seq:me,text:Ee});let Ye="";for(let ge=0;ge<Le.length;ge++)Ye+=Le[ge].text;return Ye},ft=(k,me)=>{let Ee=X(me),Le=Re.get(k.id),Be=qy(Le,Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=de=>{var Xe;let ht=(Xe=k.content)!=null?Xe:"";de.trim()!==""&&(ht.trim().length===0||de.startsWith(ht)||de.trimStart().startsWith(ht.trim()))&&(k.content=de)},yt=()=>{var de;if(rt){let ht=(de=rt.close)==null?void 0:de.call(rt);ht instanceof Promise&&ht.catch(()=>{})}ce.delete(k.id),Re.delete(k.id),k.streaming=!1,g(k)};if(!rt){Ye(Ee),yt();return}let ge=wa(Be);if(ge!==null&&ge.trim()!==""){Ye(ge),yt();return}let D=de=>{var Pt;let ht=typeof de=="string"?de:(Pt=de==null?void 0:de.text)!=null?Pt:null;if(ht!==null&&ht.trim()!=="")return ht;let Xe=rt.getExtractedText();return Xe!==null&&Xe.trim()!==""?Xe:Ee},ve;try{ve=rt.processChunk(Be)}catch{Ye(Ee),yt();return}if(ve instanceof Promise){ve.then(de=>{Ye(D(de)),yt()}).catch(()=>{Ye(Ee),yt()});return}Ye(D(ve)),yt()},Ht=null,nt=(k,me,Ee,Le)=>{var ge;k.rawContent=me,ce.has(k.id)||ce.set(k.id,this.createStreamParser());let Be=ce.get(k.id),rt=me.trim().startsWith("{")||me.trim().startsWith("[");if(rt&&Re.set(k.id,me),Be.__isPlainTextParser===!0){k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k);return}let yt=Be.processChunk(me);if(yt instanceof Promise)yt.then(D=>{var de;let ve=typeof D=="string"?D:(de=D==null?void 0:D.text)!=null?de:null;ve!==null&&ve.trim()!==""?(k.content=ve,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}).catch(()=>{k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k)});else{let D=typeof yt=="string"?yt:(ge=yt==null?void 0:yt.text)!=null?ge:null;D!==null&&D.trim()!==""?(k.content=D,g(k)):!rt&&!me.trim().startsWith("<")&&(k.content=Le!==void 0?me:k.content+Ee,Re.delete(k.id),ce.delete(k.id),k.rawContent=void 0,g(k))}},fe=(k,me)=>{var ge,D;let Ee=me!=null?me:k.content;if(Ee==null||Ee===""){k.streaming=!1,g(k);return}let Le=Re.get(k.id),Be=Le!=null?Le:X(Ee);k.rawContent=Be;let rt=ce.get(k.id),Ye=null,yt=!1;if(rt&&(Ye=rt.getExtractedText(),Ye===null&&(Ye=wa(Be)),Ye===null)){let ve=rt.processChunk(Be);ve instanceof Promise?(yt=!0,ve.then(de=>{var Xe;let ht=typeof de=="string"?de:(Xe=de==null?void 0:de.text)!=null?Xe:null;ht!==null&&(k.content=ht,k.streaming=!1,ce.delete(k.id),Re.delete(k.id),g(k))}).catch(()=>{})):Ye=typeof ve=="string"?ve:(ge=ve==null?void 0:ve.text)!=null?ge:null}if(!yt){Ye!==null&&Ye.trim()!==""?k.content=Ye:Re.has(k.id)||(k.content=X(Ee));let ve=ce.get(k.id);if(ve){let de=(D=ve.close)==null?void 0:D.call(ve);de instanceof Promise&&de.catch(()=>{}),ce.delete(k.id)}Re.delete(k.id),k.streaming=!1,g(k)}},Q=(k,me,Ee)=>{let Le=L.get(k);if(Le)return Le;let Be={id:`nested-${me}-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),...Ee?{variant:Ee}:{},...Ee==="reasoning"?{reasoning:{id:k,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:me}};return L.set(k,Be),g(Be),Be},lt=[],Ke,Te=new Map,Ce=0,et="agent",zt=!1,xe=null,ue=null,wn=new Map,At=(hn=this.config.iterationDisplay)!=null?hn:"separate";for(Ke=()=>{var k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co,Ae,Ur,Qn,_t,Yn,qr,Qs,hs,Ys,Uo,Mr,po,ct,sn,an,kr,Zs,zr,qo,Lr,_,ys,pr,Pr,Vr,Ir,ur,bs,qa,yn,An,mr,Sn,zo,gr,bn,Rr,xs,Vo,vs,uo;for(let mo=0;mo<lt.length;mo++){let st=lt[mo].payloadType,w=lt[mo].payload;if(!zt&&et!=="flow"&&typeof w.stepType=="string"&&(et="flow"),st==="reasoning_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z),Q(V,z,"reasoning");continue}let J=(k=Ie(w,!0))!=null?k:`reason-${p()}`,G=re(J);G.reasoning=(me=G.reasoning)!=null?me:{id:J,status:"streaming",chunks:[]},G.reasoning.startedAt=(Le=G.reasoning.startedAt)!=null?Le:ke((Ee=w.startedAt)!=null?Ee:w.timestamp),G.reasoning.completedAt=void 0,G.reasoning.durationMs=void 0,(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),G.streaming=!0,G.reasoning.status="streaming",g(G)}else if(st==="reasoning_delta"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let Oe=L.get(V),ot=(Ye=(rt=(Be=w.reasoningText)!=null?Be:w.text)!=null?rt:w.delta)!=null?Ye:"";ot&&w.hidden!==!0&&Oe.reasoning&&(Oe.reasoning.chunks.push(String(ot)),g(Oe));continue}let z=(ge=(yt=Ie(w,!1))!=null?yt:Ie(w,!0))!=null?ge:`reason-${p()}`,J=re(z);J.reasoning=(D=J.reasoning)!=null?D:{id:z,status:"streaming",chunks:[]},J.reasoning.startedAt=(de=J.reasoning.startedAt)!=null?de:ke((ve=w.startedAt)!=null?ve:w.timestamp);let G=(Pt=(Xe=(ht=w.reasoningText)!=null?ht:w.text)!=null?Xe:w.delta)!=null?Pt:"";if(G&&w.hidden!==!0){let Oe=typeof w.sequenceIndex=="number"?w.sequenceIndex:void 0;if(Oe!==void 0){let ot=Ge(z,Oe,String(G));J.reasoning.chunks=[ot]}else J.reasoning.chunks.push(String(G))}if(J.reasoning.status=w.done?"complete":"streaming",w.done){J.reasoning.completedAt=ke((kt=w.completedAt)!=null?kt:w.timestamp);let Oe=(vt=J.reasoning.startedAt)!=null?vt:Date.now();J.reasoning.durationMs=Math.max(0,((Wt=J.reasoning.completedAt)!=null?Wt:Date.now())-Oe)}J.streaming=J.reasoning.status!=="complete",g(J)}else if(st==="reasoning_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)&&L.has(V)){let ot=L.get(V);if(ot.reasoning){let dt=typeof w.text=="string"?w.text:"";dt&&ot.reasoning.chunks.length===0&&ot.reasoning.chunks.push(dt),ot.reasoning.status="complete",ot.streaming=!1,g(ot)}M.delete(V),L.delete(V);continue}let z=(Ft=(Qt=Ie(w,!1))!=null?Qt:Ie(w,!0))!=null?Ft:`reason-${p()}`,J=typeof w.text=="string"?w.text:"";!R.get(z)&&(J||w.scope==="loop")&&re(z);let G=R.get(z);if(G!=null&&G.reasoning){(w.scope==="loop"||w.scope==="turn")&&(G.reasoning.scope=w.scope),J&&G.reasoning.chunks.length===0&&G.reasoning.chunks.push(J),G.reasoning.status="complete",G.reasoning.completedAt=ke((tn=w.completedAt)!=null?tn:w.timestamp);let ot=(Cr=G.reasoning.startedAt)!=null?Cr:Date.now();G.reasoning.durationMs=Math.max(0,((Fr=G.reasoning.completedAt)!=null?Fr:Date.now())-ot),G.streaming=!1,g(G)}let Oe=F(w);Oe&&j.byStep.delete(Oe)}else if(st==="tool_start"){b&&(b.streaming=!1,g(b),b=null),typeof w.iteration=="number"&&(Ce=w.iteration);let V=(ir=(ar=typeof w.toolCallId=="string"?w.toolCallId:void 0)!=null?ar:K(w,!0))!=null?ir:`tool-${p()}`,z=(no=w.toolName)!=null?no:w.name;if(je(z)){oe.add(V);continue}Se(ee(w),V);let J=Y(V),G=(Vt=J.toolCall)!=null?Vt:{id:V,status:"pending"};G.name=z!=null?z:G.name,G.status="running",w.parameters!==void 0?G.args=w.parameters:w.args!==void 0&&(G.args=w.args),G.startedAt=(_r=G.startedAt)!=null?_r:ke((lr=w.startedAt)!=null?lr:w.timestamp),G.completedAt=void 0,G.durationMs=void 0,J.toolCall=G,J.streaming=!0,w.executionId&&(J.agentMetadata={executionId:w.executionId,iteration:w.iteration}),g(J)}else if(st==="tool_output_delta"){let V=(Ln=(Bn=K(w,!1))!=null?Bn:K(w,!0))!=null?Ln:`tool-${p()}`;if(oe.has(V))continue;let z=Y(V),J=(Dn=z.toolCall)!=null?Dn:{id:V,status:"running"};J.startedAt=(Ar=J.startedAt)!=null?Ar:ke((cr=w.startedAt)!=null?cr:w.timestamp);let G=(oo=(Gn=(ro=w.text)!=null?ro:w.delta)!=null?Gn:w.message)!=null?oo:"";G&&(J.chunks=(St=J.chunks)!=null?St:[],J.chunks.push(String(G))),J.status="running",z.toolCall=J,z.streaming=!0;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=($r=z.agentMetadata)!=null?$r:{executionId:(Sr=Oe==null?void 0:Oe.executionId)!=null?Sr:w.executionId,iteration:(Tr=Oe==null?void 0:Oe.iteration)!=null?Tr:w.iteration}),g(z)}else if(st==="tool_complete"){let V=(bt=(dr=K(w,!1))!=null?dr:K(w,!0))!=null?bt:`tool-${p()}`;if(oe.has(V)){oe.delete(V);continue}let z=Y(V),J=(Fo=z.toolCall)!=null?Fo:{id:V,status:"running"};J.status="complete",w.result!==void 0&&(J.result=w.result),typeof w.duration=="number"&&(J.duration=w.duration),J.completedAt=ke((Er=w.completedAt)!=null?Er:w.timestamp);let G=(_o=w.duration)!=null?_o:w.executionTime;if(typeof G=="number")J.durationMs=G;else{let dt=(Pn=J.startedAt)!=null?Pn:Date.now();J.durationMs=Math.max(0,((fs=J.completedAt)!=null?fs:Date.now())-dt)}z.toolCall=J,z.streaming=!1;let Oe=w.agentContext;(Oe||w.executionId)&&(z.agentMetadata=(ao=z.agentMetadata)!=null?ao:{executionId:(so=Oe==null?void 0:Oe.executionId)!=null?so:w.executionId,iteration:(jr=Oe==null?void 0:Oe.iteration)!=null?jr:w.iteration}),g(z);let ot=ee(w);ot&&W.byCall.delete(ot)}else if(st==="await"&&w.toolName){let V=typeof w.toolCallId=="string"&&w.toolCallId.length>0?w.toolCallId:void 0,z=(io=V!=null?V:w.toolId)!=null?io:`local-${p()}`,J=Y(z),G=w.toolName,Oe=w.origin==="webmcp"&&!Ao(G)?`webmcp:${G}`:G,ot=Ao(Oe),dt=($o=J.toolCall)!=null?$o:{id:z,status:"pending"};dt.name=Oe,dt.args=w.parameters,dt.status=ot?"running":"complete",dt.chunks=(jo=dt.chunks)!=null?jo:[],dt.startedAt=(Nn=dt.startedAt)!=null?Nn:ke((wt=(lo=w.startedAt)!=null?lo:w.timestamp)!=null?wt:w.awaitedAt),ot?(dt.completedAt=void 0,dt.duration=void 0,dt.durationMs=void 0):dt.completedAt=(On=dt.completedAt)!=null?On:dt.startedAt,J.toolCall=dt,J.streaming=!1,J.agentMetadata={...J.agentMetadata,executionId:(Tt=w.executionId)!=null?Tt:(Cn=J.agentMetadata)==null?void 0:Cn.executionId,awaitingLocalTool:!0,...V?{webMcpToolCallId:V}:{}},g(J)}else if(st==="text_start"){let V=typeof w.id=="string"?w.id:null,z=typeof w.parentToolCallId=="string"&&w.parentToolCallId?w.parentToolCallId:null;if(V&&z){M.set(V,z);continue}let J=b;J&&(et==="flow"?(fe(J),Ht=J):(J.streaming=!1,g(J)),b=null),P=typeof w.id=="string"?w.id:P,I=""}else if(st==="text_delta"){let V=typeof w.id=="string"?w.id:null,z=V?M.get(V):void 0;if(V&&z){let G=typeof w.delta=="string"?w.delta:"",Oe=((Jn=C.get(V))!=null?Jn:"")+G;if(C.set(V,Oe),Oe.trim()==="")continue;let ot=Q(V,z);ot.agentMetadata={...ot.agentMetadata,executionId:w.executionId,parentToolId:z},nt(ot,Oe,G,void 0);continue}if(P=typeof w.id=="string"?w.id:P,et==="flow"){let G=typeof w.delta=="string"?w.delta:"";if(I+=G,I.trim()==="")continue;let Oe=te();Oe.agentMetadata={executionId:w.executionId,iteration:w.iteration},nt(Oe,I,G,void 0),v=Oe;continue}let J=te();J.content+=(Xn=w.delta)!=null?Xn:"",J.agentMetadata={executionId:w.executionId,iteration:w.iteration,turnId:xe!=null?xe:void 0,agentName:ue==null?void 0:ue.agentName},v=J,g(J)}else if(st==="text_complete"){let V=typeof w.id=="string"?w.id:null;if(V&&M.has(V)){let J=L.get(V);J&&fe(J),M.delete(V),C.delete(V),L.delete(V);continue}let z=b;z&&(et==="flow"?(fe(z),Ht=z):(((Fn=z.content)!=null?Fn:"")===""&&typeof w.text=="string"&&(z.content=w.text),z.streaming=!1,g(z)),b=null),P=null,I=""}else if(st==="step_complete"){let V=w.stepType,z=w.executionType;if(V==="tool"||z==="context")continue;if(w.success===!1){let J=w.error,G=typeof J=="string"&&J!==""?J:J!=null&&typeof J=="object"&&Reflect.has(J,"message")?String((co=J.message)!=null?co:"Step failed"):"Step failed";n({type:"error",error:new Error(G)});let Oe=b;Oe&&Oe.streaming&&(Oe.streaming=!1,g(Oe)),n({type:"status",status:"idle"});continue}{let J=Ht;Ht=null;let G=w.stopReason,Oe=(Ae=w.result)==null?void 0:Ae.response;if(J)G&&(J.stopReason=G),Oe!=null?ft(J,Oe):J.streaming!==!1&&(ce.delete(J.id),Re.delete(J.id),J.streaming=!1,g(J));else{let ot=Oe!=null&&Oe!=="";if(ot||G){let dt=te();G&&(dt.stopReason=G),ot?fe(dt,Oe):(dt.streaming=!1,g(dt))}}continue}}else if(st==="execution_start")et=w.kind==="flow"?"flow":"agent",zt=!0,et==="agent"&&(ue={executionId:w.executionId,agentId:(Ur=w.agentId)!=null?Ur:"virtual",agentName:(Qn=w.agentName)!=null?Qn:"",status:"running",currentIteration:0,maxTurns:(_t=w.maxTurns)!=null?_t:1,startedAt:ke(w.startedAt)});else if(st==="turn_start"){let V=typeof w.iteration=="number"?w.iteration:Ce;if(V!==Ce){if(ue&&(ue.currentIteration=V),At==="separate"&&V>1){let z=b;z&&(z.streaming=!1,g(z),wn.set(V-1,z),b=null)}Ce=V}xe=typeof w.id=="string"?w.id:null,v=null}else if(st==="tool_input_delta"){let V=(Yn=w.toolCallId)!=null?Yn:W.lastId;if(V){let z=U.get(V);z!=null&&z.toolCall&&(z.toolCall.chunks=(qr=z.toolCall.chunks)!=null?qr:[],z.toolCall.chunks.push((Qs=w.delta)!=null?Qs:""),g(z))}}else{if(st==="tool_input_complete")continue;if(st==="turn_complete"){let V=w.stopReason,z=b!=null?b:v;if(V&&z!==null){let J=w.id;(!J||((hs=z.agentMetadata)==null?void 0:hs.turnId)===J)&&(z.stopReason=V,g(z))}xe===w.id&&(xe=null)}else if(st==="media_start"){let V=String(w.id);Te.set(V,{mediaType:typeof w.mediaType=="string"?w.mediaType:void 0,role:typeof w.role=="string"?w.role:void 0,toolCallId:w.toolCallId,parts:[]})}else if(st==="media_delta"){let V=Te.get(String(w.id));V&&typeof w.delta=="string"&&V.parts.push(w.delta)}else if(st==="media_complete"){let V=String(w.id),z=Te.get(V);Te.delete(V);let J=(Uo=(Ys=typeof w.mediaType=="string"?w.mediaType:void 0)!=null?Ys:z==null?void 0:z.mediaType)!=null?Uo:"application/octet-stream",G=typeof w.data=="string"?w.data:void 0,Oe=typeof w.url=="string"?w.url:z&&z.parts.length>0?z.parts.join(""):void 0,ot=null;if(G)ot={type:"media",data:G,mediaType:J};else if(Oe){let In=J.toLowerCase();ot={type:In==="image"||In.startsWith("image/")?"image-url":"file-url",url:Oe,mediaType:J}}let dt=(Mr=w.toolCallId)!=null?Mr:z==null?void 0:z.toolCallId,pl=ot?[ot]:[],go=[];for(let In of pl){if(!In||typeof In!="object")continue;let Yt=In,fo=typeof Yt.type=="string"?Yt.type:void 0,Zn=typeof Yt.mediaType=="string"?Yt.mediaType.toLowerCase():"",Tn=null,Rn="";if(fo==="media"){let En=typeof Yt.data=="string"?Yt.data:void 0;if(!En)continue;Rn=Zn.length>0?Zn:"application/octet-stream",Tn=`data:${Rn};base64,${En}`}else if(fo==="image-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else if(fo==="file-url"){let En=typeof Yt.url=="string"?Yt.url:void 0;if(!En)continue;Rn=Zn,Tn=En}else continue;if(Tn)if(fo==="image-url"||Rn.startsWith("image/"))go.push({type:"image",image:Tn,...Rn.includes("/")?{mimeType:Rn}:{}});else if(Rn.startsWith("audio/"))go.push({type:"audio",audio:Tn,mimeType:Rn});else if(Rn.startsWith("video/"))go.push({type:"video",video:Tn,mimeType:Rn});else{let En=Rn||"application/octet-stream";go.push({type:"file",data:Tn,mimeType:En,filename:jy(En)})}}if(go.length>0){let In=p(),Yt=dt,Zn={id:`agent-media-${typeof Yt=="string"&&Yt.length>0?`${Yt}-${In}`:String(In)}`,role:"assistant",content:"",contentParts:go,createdAt:new Date().toISOString(),streaming:!1,sequence:In,agentMetadata:{executionId:w.executionId,iteration:typeof w.iteration=="number"?w.iteration:Ce}};g(Zn);let Tn=b;Tn&&(Tn.streaming=!1,g(Tn)),b=null,T.current=null}}else if(st==="execution_complete"){let V=(po=w.kind)!=null?po:et;V==="agent"&&ue&&(ue.status=w.success?"complete":"error",ue.completedAt=ke(w.completedAt),ue.stopReason=w.stopReason);let z=b;z&&(V==="flow"&&z.streaming!==!1?fe(z):(z.streaming=!1,g(z)),b=null),P=null,I="",Ht=null,n({type:"status",status:"idle",terminal:!0})}else if(st==="execution_error"){let V=typeof w.error=="string"?w.error:(sn=(ct=w.error)==null?void 0:ct.message)!=null?sn:"Execution error";n({type:"error",error:new Error(V)})}else if(st!=="ping"){if(st==="approval_start"){let V=(an=w.approvalId)!=null?an:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(kr=ue==null?void 0:ue.agentId)!=null?kr:"virtual",executionId:(zr=(Zs=w.executionId)!=null?Zs:ue==null?void 0:ue.executionId)!=null?zr:"",toolName:(qo=w.toolName)!=null?qo:"",toolType:w.toolType,description:(_=w.description)!=null?_:`Execute ${(Lr=w.toolName)!=null?Lr:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="step_await"&&w.awaitReason==="approval_required"){let V=(ys=w.approvalId)!=null?ys:`approval-${p()}`,z={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:"pending",agentId:(pr=ue==null?void 0:ue.agentId)!=null?pr:"virtual",executionId:(Vr=(Pr=w.executionId)!=null?Pr:ue==null?void 0:ue.executionId)!=null?Vr:"",toolName:(Ir=w.toolName)!=null?Ir:"",toolType:w.toolType,description:(bs=w.description)!=null?bs:`Execute ${(ur=w.toolName)!=null?ur:"tool"}`,...typeof w.reason=="string"&&w.reason?{reason:w.reason}:{},parameters:w.parameters}};g(z)}else if(st==="approval_complete"){let V=w.approvalId;if(V){let J={id:`approval-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:p(),approval:{id:V,status:(qa=w.decision)!=null?qa:"approved",agentId:(yn=ue==null?void 0:ue.agentId)!=null?yn:"virtual",executionId:(mr=(An=w.executionId)!=null?An:ue==null?void 0:ue.executionId)!=null?mr:"",toolName:(Sn=w.toolName)!=null?Sn:"",description:(zo=w.description)!=null?zo:"",resolvedAt:Date.now()}};g(J)}}else if(st==="artifact_start"||st==="artifact_delta"||st==="artifact_update"||st==="artifact_complete"){if(st==="artifact_start"){let V=w.artifactType,z=String(w.id),J=typeof w.title=="string"?w.title:void 0;if(n({type:"artifact_start",id:z,artifactType:V,title:J,component:typeof w.component=="string"?w.component:void 0}),ye.set(z,{markdown:"",title:J}),!ie.has(z)){ie.add(z);let G={id:`artifact-ref-${z}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:p(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:z,title:J,artifactType:V,status:"streaming"}})};ae.set(z,G),g(G)}}else if(st==="artifact_delta"){let V=String(w.id),z=typeof w.delta=="string"?w.delta:String((gr=w.delta)!=null?gr:"");n({type:"artifact_delta",id:V,artDelta:z});let J=ye.get(V);J&&(J.markdown+=z)}else if(st==="artifact_update"){let V=w.props&&typeof w.props=="object"&&!Array.isArray(w.props)?w.props:{};n({type:"artifact_update",id:String(w.id),props:V,component:typeof w.component=="string"?w.component:void 0})}else if(st==="artifact_complete"){let V=String(w.id);n({type:"artifact_complete",id:V});let z=ae.get(V);if(z){z.streaming=!1;try{let J=JSON.parse((bn=z.rawContent)!=null?bn:"{}");if(J.props){J.props.status="complete";let G=ye.get(V);G!=null&&G.markdown&&(J.props.markdown=G.markdown)}z.rawContent=JSON.stringify(J)}catch{}ye.delete(V),g(z),ae.delete(V)}}}else if(st==="transcript_insert"){let V=w.message;if(!V||typeof V!="object")continue;let z=String((Rr=V.id)!=null?Rr:`msg-${p()}`),J=V.role,Oe={id:z,role:J==="user"?"user":J==="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(g(Oe),Oe.rawContent)try{let ot=JSON.parse(Oe.rawContent),dt=(xs=ot==null?void 0:ot.props)==null?void 0:xs.artifactId;typeof dt=="string"&&ie.add(dt)}catch{}b=null,T.current=null,ce.delete(z),Re.delete(z)}else if(st==="error"){if(w.recoverable===!1&&w.error!=null&&w.error!==""){let V=typeof w.error=="string"?w.error:((Vo=w.error)==null?void 0:Vo.message)!=null?String(w.error.message):"Execution error";n({type:"error",error:new Error(V)});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}else if(st==="step_error"||st==="dispatch_error"||st==="flow_error"){let V=null;if(w.error instanceof Error)V=w.error;else if(st==="dispatch_error"){let z=(vs=w.message)!=null?vs:w.error;z!=null&&z!==""&&(V=new Error(String(z)))}else{let z=w.error;typeof z=="string"&&z!==""?V=new Error(z):z!=null&&typeof z=="object"&&Reflect.has(z,"message")&&(V=new Error(String((uo=z.message)!=null?uo:z)))}if(V){n({type:"error",error:V});let z=b;z&&z.streaming&&(z.streaming=!1,g(z)),n({type:"status",status:"idle"})}}}}}lt.length=0};;){let{done:k,value:me}=await s.read();if(k)break;i+=a.decode(me,{stream:!0});let Ee=i.split(`
12
12
 
13
13
  `);i=(vr=Ee.pop())!=null?vr:"";for(let Le of Ee){let Be=Le.split(`
14
14
  `),rt="message",Ye="",yt=null;for(let de of Be)de.startsWith("event:")?rt=de.replace("event:","").trim():de.startsWith("data:")?Ye+=de.replace("data:","").trim():de.startsWith("id:")&&(yt=de.slice(3).trim());let ge=()=>{yt!==null&&yt!==""&&n({type:"cursor",id:yt})};if(!Ye){ge();continue}let D;try{D=JSON.parse(Ye)}catch(de){n({type:"error",error:de instanceof Error?de:new Error("Failed to parse chat stream payload")});continue}let ve=rt!=="message"?rt:(wr=D.type)!=null?wr:"message";if((qe=this.onSSEEvent)==null||qe.call(this,ve,D),this.parseSSEEvent){T.current=b;let de=await this.handleCustomSSEEvent(D,n,T,g,p,E);if(T.current&&T.current!==b&&(b=T.current),de){ge();continue}}lt.push({payloadType:ve,payload:D}),Ke(),ge()}}Ke()}};function cg(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Bs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Lo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var gi="[Image]";function dg(e){return typeof e=="string"?[{type:"text",text:e}]:e}function pg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function ug(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function mg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ca(e){return{type:"text",text:e}}function gg(e,t){return{type:"image",image:e,...(t==null?void 0:t.mimeType)&&{mimeType:t.mimeType},...(t==null?void 0:t.alt)&&{alt:t.alt}}}async function fg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function hg(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var yg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],zy=["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"],Yr=[...yg,...zy];function Vy(e){return yg.includes(e)||e.startsWith("image/")}function fi(e){return Vy(e.type)}async function bg(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;fi(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function xg(e,t=Yr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function Ky(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function vg(e,t){let n=Ky(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}Ol();var wg=16e3,Gy=24e3,Jy=4096,Xy=1380533830;function Qy(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===Xy?new Uint8Array(e,44):new Uint8Array(e)}function Yy(e){var r;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((r=window.location)==null?void 0:r.protocol)==="https:"?"wss:":"ws:"}//${t}`}var Aa=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var s,a,i,d;if(this.callLive)return;let t=(s=this.config)==null?void 0:s.agentId,n=(a=this.config)==null?void 0:a.clientToken,r=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!n)throw new Error("Runtype voice requires a clientToken");if(!r)throw new Error("Runtype voice requires a host (or widget apiUrl)");let o=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let c=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:wg,channelCount:1,echoCancellation:!0}});if(o!==this.callGeneration){c.getTracks().forEach(v=>v.stop());return}this.mediaStream=c;let p=window.AudioContext||window.webkitAudioContext,u=new p({sampleRate:wg});u.state==="suspended"&&await u.resume().catch(()=>{}),this.captureContext=u;let f=(d=this.config)!=null&&d.createPlaybackEngine?await this.config.createPlaybackEngine():new Ds(Gy);if(o!==this.callGeneration){f.destroy(),c.getTracks().forEach(v=>v.stop()),u.close().catch(()=>{});return}this.playback=f,f.onFinished(()=>{o===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let g=`${Yy(r)}/ws/agents/${encodeURIComponent(t)}/voice`,b=new WebSocket(g,["runtype.bearer",n]);b.binaryType="arraybuffer",this.ws=b,b.onopen=()=>{o===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(u,c,b,o))},b.onmessage=v=>this.handleMessage(v,o),b.onerror=()=>{o===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},b.onclose=v=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(o===this.callGeneration){if(v.code!==1e3){let T=v.code?` (code ${v.code})`:"";this.emitError(new Error(`Voice connection closed${T}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(c){throw this.cleanup(),this.emitError(c),this.emitStatus("error"),c}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,n,r,o){let s=t.createMediaStreamSource(n);this.sourceNode=s;let a=t.createScriptProcessor(Jy,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 u=Math.max(-1,Math.min(1,d[p]));c[p]=u<0?u*32768:u*32767}r.send(c.buffer)},s.connect(a),a.connect(t.destination)}handleMessage(t,n){var o,s;if(n!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,n);return}let r;try{r=JSON.parse(t.data)}catch{return}switch(r.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(o=r.text)!=null?o:"",!1);break;case"transcript_final":{let a=r.role==="assistant"?"assistant":"user";this.emitStatus(a==="user"?"processing":"speaking"),this.emitTranscript(a,(s=r.text)!=null?s:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:r.llm_ms,ttsMs:r.tts_ms,firstAudioMs:r.first_audio_ms,totalMs:r.total_ms});break;case"error":this.emitError(new Error(r.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,n){if(n!==this.callGeneration||!this.playback)return;let r=Qy(t);r.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(r))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(n=>n(t))}emitError(t){this.errorCallbacks.forEach(n=>n(t))}emitTranscript(t,n,r){this.transcriptCallbacks.forEach(o=>o(t,n,r))}emitMetrics(t){this.metricsCallbacks.forEach(n=>n(t))}};var as=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Po(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Aa(e.runtype);case"browser":if(!as.isSupported())throw new Error("Browser speech recognition not supported");return new as(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let n=typeof t=="function"?t():t;if(!n||typeof n.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return n}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function hi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return Po({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Po({type:"runtype",runtype:e.runtype});if(as.isSupported())return Po({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Sa(e){try{return hi(e),!0}catch{return!1}}function Ns(e){var n;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let r of t){let o=e.find(s=>s.name===r);if(o)return o}return(n=e.find(r=>r.lang.startsWith("en")))!=null?n:e[0]}var Io=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,n){var a;if(!e.isSupported()){(a=n.onError)==null||a.call(n,new Error("Web Speech API is unavailable"));return}let r=window.speechSynthesis;r.cancel();let o=new SpeechSynthesisUtterance(t.text),s=r.getVoices();if(t.voice){let i=s.find(d=>d.name===t.voice);i&&(o.voice=i)}else s.length>0&&(o.voice=this.options.pickVoice?this.options.pickVoice(s):Ns(s));t.rate!==void 0&&(o.rate=t.rate),t.pitch!==void 0&&(o.pitch=t.pitch),o.onend=()=>{var i;return(i=n.onEnd)==null?void 0:i.call(n)},o.onerror=i=>{var c,p;let d=i.error;d==="canceled"||d==="interrupted"?(c=n.onEnd)==null||c.call(n):(p=n.onError)==null||p.call(n,new Error(d||"Speech synthesis failed"))},setTimeout(()=>{var i;r.speak(o),(i=n.onStart)==null||i.call(n)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var is=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,n;return(n=(t=this.engine)==null?void 0:t.supportsPause)!=null?n:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,n){var r,o;if(this.activeId===t){if(this.state==="playing"){(r=this.engine)!=null&&r.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(o=this.engine)==null||o.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,n)}async play(t,n){var o;let r=++this.generation;(o=this.engine)==null||o.stop(),this.set(t,"loading");try{if(!this.engine){let s=await this.resolveEngine();if(r!==this.generation)return;if(!s){this.set(null,"idle");return}this.engine=s}this.engine.speak(n,{onStart:()=>{r===this.generation&&this.set(t,"playing")},onEnd:()=>{r===this.generation&&this.set(null,"idle")},onError:()=>{r===this.generation&&this.set(null,"idle")}})}catch{r===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,n;this.stop(),(n=(t=this.engine)==null?void 0:t.destroy)==null||n.call(t),this.engine=null,this.listeners.clear()}set(t,n){this.activeId=n==="idle"?null:t,this.state=n;for(let r of this.listeners)r(this.activeId,this.state)}};function Fl(e){if(!e)return"";let t=Zy(e);return Cg(t!==null?t:e)}function Zy(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(n&&(t=n[1].trim()),!t.startsWith("{"))return null;try{let r=JSON.parse(t);if(r&&typeof r=="object"&&typeof r.text=="string")return r.text}catch{}return null}function Cg(e){if(!e)return"";let t=e;return t=t.replace(/```[\s\S]*?```/g," "),t=t.replace(/~~~[\s\S]*?~~~/g," "),t=t.replace(/`([^`]+)`/g,"$1"),t=t.replace(/!\[([^\]]*)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\([^)]*\)/g,"$1"),t=t.replace(/\[([^\]]+)\]\[[^\]]*\]/g,"$1"),t=t.replace(/<\/?[a-zA-Z][^>]*>/g," "),t=t.replace(/^[ \t]*#{1,6}[ \t]+/gm,""),t=t.replace(/^[ \t]*>[ \t]?/gm,""),t=t.replace(/^[ \t]*[-*+][ \t]+/gm,""),t=t.replace(/^[ \t]*\d+\.[ \t]+/gm,""),t=t.replace(/^[ \t]*([-*_])([ \t]*\1){2,}[ \t]*$/gm," "),t=t.replace(/(\*\*|__)(.*?)\1/g,"$2"),t=t.replace(/(\*|_)(.*?)\1/g,"$2"),t=t.replace(/~~(.*?)~~/g,"$1"),t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," "),t=t.replace(/[ \t]*\n[ \t]*/g,`
15
15
  `),t=t.replace(/\n{2,}/g,`
16
16
  `),t.trim()}var Mg=null;var _l=()=>Mg?Mg():Promise.resolve().then(()=>(Eg(),Tg));var ob=["apiUrl","clientToken","flowId","agentId","target","targetProviders","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function sb(e,t){return ob.some(n=>e[n]!==t[n])}function $l(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
17
17
 
18
- _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]}),Pg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ig=e=>Ao(e)||e===br,Os=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 is(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ao(f.name)||f.name===br&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ss(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||_l().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Sa((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Io.isSupported()?new Io({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return _l().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Po(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!sb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new ss(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?Bs():n==="assistant"?Lo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?Bs():o==="assistant"?Lo():`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:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,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(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Bs(),s=Lo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||gi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let T=$l(b,this.config.errorMessage);if(T){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Lo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(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 u=$l(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}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(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.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(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.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 t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let T=null;if(v instanceof Response){if(!v.ok){let E=await v.json().catch(()=>null);throw new Error((f=E==null?void 0:E.error)!=null?f:`Approval request failed: ${v.status}`)}T=v.body}else v instanceof ReadableStream&&(T=v);T?await this.connectStream(T,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,T,E,P,I,M,L;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(v=t.toolCall)==null?void 0:v.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let U=typeof((T=R[0])==null?void 0:T.question)=="string"?R[0].question:"";U&&(a={[U]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(P=t.toolCall)==null?void 0:P.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,U])=>`${R}: ${Array.isArray(U)?U.join(", "):U}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((R,U)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((I=R==null?void 0:R.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 R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(L=(M=this.callbacks).onError)==null||L.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==br)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var L,C,R,U,j,W,O;let g=(L=f.toolCall)==null?void 0:L.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let T=this.markWebMcpToolRunning(f),E=(U=(R=f.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?U:g;if(g===br)return{dedupeKey:v,resumeKey:E,output:Rl(),toolMessage:f,startedAt:T,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let I=this.client.executeWebMcpToolCall(g,(j=f.toolCall)==null?void 0:j.args,P.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 ee=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return ee||(O=(W=this.callbacks).onError)==null||O.call(W,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(f,Ta(ee?"Aborted by cancel()":Pg(F)),T),this.webMcpInflightKeys.delete(v),null}return P.signal.aborted?(this.markWebMcpToolComplete(f,Ta("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:E,output:M,toolMessage:f,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===br?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,Ta("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,T,E,P,I,M,L,C,R,U,j;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(T=t.toolCall)==null?void 0:T.id;if(!n){(P=(E=this.callbacks).onError)==null||P.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(W)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===br,p=(L=t.toolCall)==null?void 0:L.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let W;if(c?W=Rl():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ta("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;f="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(f==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,Ta(O||d.aborted?"Aborted by cancel()":Pg(W)),a),O||(j=(U=this.callbacks).onError)==null||j.call(U,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{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(()=>(Lg(),kg)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>$l(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Lo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Fl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ns(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Fl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,T,E,P,I,M,L,C,R,U;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(g=W.toolType)!=null?g:j.toolType,reason:(b=W.reason)!=null?b:j.reason,parameters:(v=W.parameters)!=null?v:j.parameters}}let i=(T=n.toolCall)==null?void 0:T.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,c=(P=n.toolCall)==null?void 0:P.id;if(i&&Ig(i)&&d&&c&&((I=n.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let j=`${d}:${c}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),F=(M=o.toolCall)==null?void 0:M.name,ee=((L=o.agentMetadata)==null?void 0:L.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&Ig(F)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||ee)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),ab={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},he=(e,t=24,n="currentColor",r=2)=>{let o=ab[e];return o?ib(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ib(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var xi={allowedTypes:Yr,maxFileSize:10*1024*1024,maxFiles:4};function lb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ls=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:xi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:xi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:xi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:xi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=xg(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await bg(c),f=fi(c)?URL.createObjectURL(c):null,g={id:lb(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=fi(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=cb(t.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=vg(t.file.type,t.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=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Rg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ea(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Rg(s)&&Rg(o)?n[r]=Ea(s,o):n[r]=o}return n}var zn="min(440px, calc(100vw - 24px))",vi="440px",db={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:zn,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:db,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 Wg(e,t){if(!(!e&&!t))return e?t?Ea(e,t):e:t}function wi(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L;return e?{...Bt,...e,theme:Wg(Bt.theme,e.theme),darkTheme:Wg(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(t=Bt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce;let C=(oe=Bt.features)==null?void 0:oe.artifacts,R=(ae=e.features)==null?void 0:ae.artifacts,U=(ie=Bt.features)==null?void 0:ie.scrollToBottom,j=(ye=e.features)==null?void 0:ye.scrollToBottom,W=(je=Bt.features)==null?void 0:je.scrollBehavior,O=(K=e.features)==null?void 0:K.scrollBehavior,F=(Y=Bt.features)==null?void 0:Y.streamAnimation,ee=(ke=e.features)==null?void 0:ke.streamAnimation,Me=(X=Bt.features)==null?void 0:X.askUserQuestion,pe=(ce=e.features)==null?void 0:ce.askUserQuestion,te=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Pe=U===void 0&&j===void 0?void 0:{...U,...j},Ie=W===void 0&&O===void 0?void 0:{...W,...O},re=F===void 0&&ee===void 0?void 0:{...F,...ee},Se=Me===void 0&&pe===void 0?void 0:{...Me,...pe,styles:{...Me==null?void 0:Me.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...te!==void 0?{artifacts:te}:{},...re!==void 0?{streamAnimation:re}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Bt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(I=e.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var jl={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"}},Ul={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"}},ql={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:zn,maxWidth:vi,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 Fs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Fs(e,r):r}function Ci(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Fs(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function zl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Hg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Hg(s,o):n[r]=o}return n}function pb(e,t){return t?Hg(e,t):e}function _s(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,T;let n={palette:jl,semantic:Ul,components:ql},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:pb(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=zl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(P=>P.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function Ai(e){var v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe,Q,lt,Ke,Te,Ce,et,zt,xe,ue,wn,At,hn,vr,wr,qe,k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co;let t=Ci(e),n={};for(let[Ae,Ur]of Object.entries(t)){let Qn=Ae.replace(/\./g,"-");n[`--persona-${Qn}`]=Ur.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(T=n["--persona-semantic-colors-secondary"])!=null?T:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(P=n["--persona-semantic-colors-surface"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(I=n["--persona-semantic-colors-background"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(L=n["--persona-semantic-colors-text"])!=null?L:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(U=n["--persona-semantic-colors-border"])!=null?U:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(F=n["--persona-components-voice-processing-icon"])!=null?F:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ee=n["--persona-components-voice-speaking-icon"])!=null?ee:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(te=n["--persona-components-approval-requested-text"])!=null?te:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Pe=n["--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)",n["--persona-approval-approve-bg"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ae=n["--persona-semantic-typography-fontFamily"])!=null?ae:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ie=n["--persona-semantic-typography-fontSize"])!=null?ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(je=n["--persona-semantic-typography-lineHeight"])!=null?je:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(Y=n["--persona-palette-radius-md"])!=null?Y:"0.375rem",n["--persona-radius-lg"]=(ke=n["--persona-palette-radius-lg"])!=null?ke:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(ce=n["--persona-palette-radius-full"])!=null?ce:"9999px",n["--persona-launcher-radius"]=(be=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?be:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(ft=n["--persona-components-launcher-foreground"])!=null?ft:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ht=n["--persona-components-launcher-border"])!=null?Ht:n["--persona-border"],n["--persona-button-primary-bg"]=(nt=n["--persona-components-button-primary-background"])!=null?nt:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(lt=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-panel-radius"]=(Te=(Ke=n["--persona-components-panel-borderRadius"])!=null?Ke:n["--persona-radius-xl"])!=null?Te:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(zt=(et=n["--persona-components-panel-shadow"])!=null?et:n["--persona-palette-shadows-xl"])!=null?zt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(xe=n["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(wn=(ue=n["--persona-components-input-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?wn:"0.5rem",n["--persona-message-user-radius"]=(hn=(At=n["--persona-components-message-user-borderRadius"])!=null?At:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(wr=(vr=n["--persona-components-message-assistant-borderRadius"])!=null?vr:n["--persona-radius-lg"])!=null?wr:"0.5rem",n["--persona-header-bg"]=(qe=n["--persona-components-header-background"])!=null?qe:n["--persona-surface"],n["--persona-header-border"]=(k=n["--persona-components-header-border"])!=null?k:n["--persona-divider"],n["--persona-header-icon-bg"]=(me=n["--persona-components-header-iconBackground"])!=null?me:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ee=n["--persona-components-header-iconForeground"])!=null?Ee:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Le=n["--persona-components-header-titleForeground"])!=null?Le:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(rt=n["--persona-components-header-actionIconForeground"])!=null?rt:n["--persona-muted"];let r=(Ye=e.components)==null?void 0:Ye.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(ge=n["--persona-components-introCard-background"])!=null?ge:n["--persona-surface"],n["--persona-intro-card-radius"]=(D=n["--persona-components-introCard-borderRadius"])!=null?D:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(ht=(de=o==null?void 0:o.shadow)!=null?de:n["--persona-components-introCard-shadow"])!=null?ht:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Xe=n["--persona-components-input-background"])!=null?Xe:n["--persona-surface"],n["--persona-input-placeholder"]=(Pt=n["--persona-components-input-placeholder"])!=null?Pt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(kt=n["--persona-components-message-user-background"])!=null?kt:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Wt=n["--persona-components-message-user-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(tn=n["--persona-components-message-assistant-border"])!=null?tn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Cr=n["--persona-components-message-assistant-shadow"])!=null?Cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ar=(Fr=n["--persona-components-scrollToBottom-background"])!=null?Fr:n["--persona-button-primary-bg"])!=null?ar:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(no=(ir=n["--persona-components-scrollToBottom-foreground"])!=null?ir:n["--persona-button-primary-fg"])!=null?no:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Vt=n["--persona-components-scrollToBottom-border"])!=null?Vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(_r=n["--persona-components-scrollToBottom-borderRadius"])!=null?_r:n["--persona-button-radius"])!=null?Bn:n["--persona-radius-full"])!=null?Ln:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Dn=n["--persona-components-scrollToBottom-shadow"])!=null?Dn:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Ar=n["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(ro=n["--persona-components-scrollToBottom-gap"])!=null?ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(oo=(Gn=n["--persona-components-scrollToBottom-fontSize"])!=null?Gn:n["--persona-palette-typography-fontSize-sm"])!=null?oo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(St=n["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",n["--persona-tool-bubble-shadow"]=(Sr=n["--persona-components-toolBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Tr=n["--persona-components-reasoningBubble-shadow"])!=null?Tr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($r=n["--persona-components-composer-shadow"])!=null?$r:"none",n["--persona-md-inline-code-bg"]=(dr=n["--persona-components-markdown-inlineCode-background"])!=null?dr:n["--persona-container"],n["--persona-md-inline-code-color"]=(bt=n["--persona-components-markdown-inlineCode-foreground"])!=null?bt:n["--persona-text"],n["--persona-md-link-color"]=(Er=(Fo=n["--persona-components-markdown-link-foreground"])!=null?Fo:n["--persona-accent"])!=null?Er:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(_o=n["--persona-components-markdown-codeBlock-background"])!=null?_o:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Pn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(fs=n["--persona-components-markdown-codeBlock-textColor"])!=null?fs:"inherit",n["--persona-md-table-header-bg"]=(so=n["--persona-components-markdown-table-headerBackground"])!=null?so:n["--persona-container"],n["--persona-md-table-border-color"]=(jr=n["--persona-components-markdown-table-borderColor"])!=null?jr:n["--persona-border"],n["--persona-md-hr-color"]=(ao=n["--persona-components-markdown-hr-color"])!=null?ao:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(io=n["--persona-components-markdown-blockquote-borderColor"])!=null?io:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=($o=n["--persona-components-markdown-blockquote-background"])!=null?$o:"transparent",n["--persona-md-blockquote-text-color"]=(jo=n["--persona-components-markdown-blockquote-textColor"])!=null?jo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(lo=n["--persona-components-collapsibleWidget-container"])!=null?lo:n["--persona-surface"],n["--cw-surface"]=(wt=n["--persona-components-collapsibleWidget-surface"])!=null?wt:n["--persona-surface"],n["--cw-border"]=(Nn=n["--persona-components-collapsibleWidget-border"])!=null?Nn:n["--persona-border"],n["--persona-message-border"]=(On=n["--persona-components-message-border"])!=null?On:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ae=b.toolbar;Ae.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ae.iconHoverColor),Ae.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ae.iconHoverBackground),Ae.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ae.iconPadding),Ae.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ae.iconBorderRadius),Ae.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ae.iconBorder),Ae.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ae.toggleGroupGap),Ae.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ae.toggleBorderRadius),Ae.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ae.copyBackground),Ae.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ae.copyBorder),Ae.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ae.copyColor),Ae.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ae.copyBorderRadius),Ae.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ae.copyPadding),Ae.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ae.copyMenuBackground,n["--persona-dropdown-bg"]=(Cn=n["--persona-dropdown-bg"])!=null?Cn:Ae.copyMenuBackground),Ae.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ae.copyMenuBorder,n["--persona-dropdown-border"]=(Tt=n["--persona-dropdown-border"])!=null?Tt:Ae.copyMenuBorder),Ae.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ae.copyMenuShadow,n["--persona-dropdown-shadow"]=(Jn=n["--persona-dropdown-shadow"])!=null?Jn:Ae.copyMenuShadow),Ae.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ae.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Xn=n["--persona-dropdown-radius"])!=null?Xn:Ae.copyMenuBorderRadius),Ae.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ae.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fn=n["--persona-dropdown-item-hover-bg"])!=null?Fn:Ae.copyMenuItemHoverBackground),Ae.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ae.iconBackground),Ae.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ae.toolbarBorder)}if(b!=null&&b.tab){let Ae=b.tab;Ae.background&&(n["--persona-artifact-tab-bg"]=Ae.background),Ae.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ae.activeBackground),Ae.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ae.activeBorder),Ae.borderRadius&&(n["--persona-artifact-tab-radius"]=Ae.borderRadius),Ae.textColor&&(n["--persona-artifact-tab-color"]=Ae.textColor),Ae.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ae.hoverBackground),Ae.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ae.listBackground),Ae.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ae.listBorderColor),Ae.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ae.listPadding)}if(b!=null&&b.pane){let Ae=b.pane;if(Ae.toolbarBackground){let Ur=(co=Fs(e,Ae.toolbarBackground))!=null?co:Ae.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ur}}return n}var Bg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ub={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"}}},Dg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ma=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},mb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ma()},Vl=e=>mb(e),gb=e=>_s(e),fb=e=>{var n;let t=_s(void 0,{validate:!1});return _s({...e,palette:{...t.palette,colors:{...ub.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},$s=e=>{let t=Vl(e),n=Dg(e==null?void 0:e.theme),r=Dg(e==null?void 0:e.darkTheme);return t==="dark"?fb(Ea(n!=null?n:{},r!=null?r:{})):gb(n)},hb=e=>Ai(e),Ro=(e,t)=>{let n=$s(t),r=hb(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},Si=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ma())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ma());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Ng=require("idiomorph"),Ti=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ng.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-preserve-animation")){if(s instanceof HTMLElement&&!s.hasAttribute("data-preserve-animation"))return;if(s instanceof HTMLElement&&s.hasAttribute("data-preserve-animation")){let d=(a=o.textContent)!=null?a:"",c=(i=s.textContent)!=null?i:"";if(d!==c)return}return!1}}}}})};var Og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ei={index:-1,draft:""};function Fg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ei}}}function _g(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(T=(v=e.toolCall)==null?void 0:v.name)!=null?T:"",(I=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?I:0,(R=(C=(L=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((U=e.toolCall)==null?void 0:U.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(F=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?F:0,(te=(pe=(Me=(ee=e.reasoning)==null?void 0:ee.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?te:0,(Se=(re=(Ie=(Pe=e.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?Se:"",(ae=(oe=e.contentParts)==null?void 0:oe.length)!=null?ae:0,(ie=e.stopReason)!=null?ie:"",t].join("\0")}function $g(){return new Map}function jg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ug(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function qg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Mi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Nr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Nr(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Li(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function zg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Kg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var rn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,Ho=vn+1;var ka={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yb=["pre","code","a","script","style"],Pi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ka.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ka.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ka.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ka.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ka.buffer}},Jg=[{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"}],La=new Map;for(let e of Jg)La.set(e.name,e);var Xg=e=>{La.set(e.name,e)},Qg=e=>{Jg.some(t=>t.name===e)||La.delete(e)},Yg=()=>Array.from(La.keys()),js=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=La.get(e))!=null?r:null},Ii=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
18
+ _Details: ${n.message}_`:r}var Ta=e=>({isError:!0,content:[{type:"text",text:e}]}),Pg=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,Ig=e=>Ao(e)||e===br,Os=class{constructor(t={},n){this.config=t;this.callbacks=n;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 is(()=>this.createSpeechEngine());this.handleEvent=t=>{var n,r,o,s,a,i,d,c,p,u;if(t.type==="message"){this.upsertMessage(t.message),t.message.role==="assistant"&&!t.message.variant&&t.message.streaming&&(this.activeAssistantMessageId=t.message.id);let f=t.message.toolCall,g=!!(f!=null&&f.name)&&(Ao(f.name)||f.name===br&&((r=(n=this.config.features)==null?void 0:n.suggestReplies)==null?void 0:r.enabled)!==!1);((o=t.message.agentMetadata)==null?void 0:o.awaitingLocalTool)===!0&&g&&this.enqueueWebMcpAwait(t.message),(s=t.message.agentMetadata)!=null&&s.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(a=t.message.agentMetadata.agentName)!=null?a:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="cursor")this.trackCursor(t.id);else if(t.type==="status"){if(t.status==="idle"&&!t.terminal&&this.isDurableDrop()){this.beginReconnect();return}if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let f=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((d=this.agentExecution)==null?void 0:d.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":f||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.clearResumable(),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((c=this.agentExecution)==null?void 0:c.status)==="running"&&(this.agentExecution.status="error"),(u=(p=this.callbacks).onError)==null||u.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var r,o;this.messages=[...(r=t.initialMessages)!=null?r:[]].map(s=>{var a;return{...s,sequence:(a=s.sequence)!=null?a:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new ss(t),this.wireDefaultWebMcpConfirm();for(let s of(o=t.initialArtifacts)!=null?o:[])this.artifacts.set(s.id,{...s,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var o,s,a,i,d,c;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let n=(o=t.host)!=null?o:this.config.apiUrl,r=(c=(d=t.agentId)!=null?d:(i=(a=(s=this.config.voiceRecognition)==null?void 0:s.provider)==null?void 0:a.runtype)==null?void 0:i.agentId)!=null?c:this.config.agentId;!n||!r||!this.config.clientToken||_l().catch(()=>{})}setSSEEventCallback(t){this.client.setSSEEventCallback(t)}isClientTokenMode(){return this.client.isClientTokenMode()}isAgentMode(){return this.client.isAgentMode()}getAgentExecution(){return this.agentExecution}isAgentExecuting(){var t;return((t=this.agentExecution)==null?void 0:t.status)==="running"}isVoiceSupported(){var t;return Sa((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,n,r;return(r=(n=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:n.call(t))!=null?r:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var r,o,s,a,i,d;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let n=Io.isSupported()?new Io({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let c=(r=t.host)!=null?r:this.config.apiUrl,p=(d=(i=t.agentId)!=null?i:(a=(s=(o=this.config.voiceRecognition)==null?void 0:o.provider)==null?void 0:s.runtype)==null?void 0:a.agentId)!=null?d:this.config.agentId,u=this.config.clientToken,f=t.browserFallback!==!1;if(c&&p&&u)return _l().then(({RuntypeSpeechEngine:g,FallbackSpeechEngine:b})=>{let v=new g({host:c,agentId:p,clientToken:u,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return f&&n?new b(v,n,{onFallback:T=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${T.message}`)}):v});if(f&&n)return u&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),n}return n}setupVoice(t){var n,r;try{let o=t||this.getVoiceConfigFromConfig();if(!o)throw new Error("Voice configuration not provided");this.voiceProvider=Po(o);let a=(r=((n=this.config.voiceRecognition)!=null?n:{}).processingErrorText)!=null?r:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,d,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(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var n,r,o,s,a,i,d,c,p,u,f,g;if(!((n=this.config.voiceRecognition)!=null&&n.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(s=(o=(r=t.runtype)==null?void 0:r.agentId)!=null?o:this.config.agentId)!=null?s:"",clientToken:(i=(a=t.runtype)==null?void 0:a.clientToken)!=null?i:this.config.clientToken,host:(c=(d=t.runtype)==null?void 0:d.host)!=null?c:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(u=t.runtype)==null?void 0:u.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((f=t.browser)==null?void 0:f.language)||"en-US",continuous:(g=t.browser)==null?void 0:g.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,n;if(!this.isClientTokenMode())return null;try{let r=await this.client.initSession();return this.setClientSession(r),r}catch(r){return(n=(t=this.callbacks).onError)==null||n.call(t,r instanceof Error?r:new Error(String(r))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let n={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(n)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,n){return this.client.submitMessageFeedback(t,n)}async submitCSATFeedback(t,n){return this.client.submitCSATFeedback(t,n)}async submitNPSFeedback(t,n){return this.client.submitNPSFeedback(t,n)}updateConfig(t){let n={...this.config,...t};if(!sb(this.config,n)){this.config=n,this.client.updateConfig(n);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let r=this.client.getSSEEventCallback();this.config=n,this.client=new ss(this.config),this.wireDefaultWebMcpConfirm(),r&&this.client.setSSEEventCallback(r)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:n,content:r,llmContent:o,contentParts:s,id:a,createdAt:i,sequence:d,streaming:c=!1,voiceProcessing:p,rawContent:u}=t,g={id:a!=null?a:n==="user"?Bs():n==="assistant"?Lo():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:r,createdAt:i!=null?i:new Date().toISOString(),sequence:d!=null?d:this.nextSequence(),streaming:c,...o!==void 0&&{llmContent:o},...s!==void 0&&{contentParts:s},...p!==void 0&&{voiceProcessing:p},...u!==void 0&&{rawContent:u}};return this.upsertMessage(g),g}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let n=[];for(let r of t){let{role:o,content:s,llmContent:a,contentParts:i,id:d,createdAt:c,sequence:p,streaming:u=!1,voiceProcessing:f,rawContent:g}=r,v={id:d!=null?d:o==="user"?Bs():o==="assistant"?Lo():`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:u,...a!==void 0&&{llmContent:a},...i!==void 0&&{contentParts:i},...f!==void 0&&{voiceProcessing:f},...g!==void 0&&{rawContent:g}};n.push(v)}return this.messages=this.sortMessages([...this.messages,...n]),this.callbacks.onMessagesChanged([...this.messages]),n}injectComponentDirective(t){let{component:n,props:r={},text:o="",llmContent:s,id:a,createdAt:i,sequence:d}=t,c={text:o,component:n,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(t,n){var c,p,u,f,g;let r=t.trim();if(!r&&(!(n!=null&&n.contentParts)||n.contentParts.length===0))return;this.stopSpeaking(),(c=this.abortController)==null||c.abort(),this.abortWebMcpResolves(),this.teardownReconnect();let o=Bs(),s=Lo();this.activeAssistantMessageId=null;let a={id:o,role:"user",content:r||gi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(n==null?void 0:n.viaVoice)||!1,...(n==null?void 0:n.contentParts)&&n.contentParts.length>0&&{contentParts:n.contentParts}};this.appendMessage(a),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let d=[...this.messages];try{await this.client.dispatch({messages:d,signal:i.signal,assistantMessageId:s},this.handleEvent)}catch(b){if(this.status==="resuming"||this.reconnecting)return;let v=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));if(!v){let T=$l(b,this.config.errorMessage);if(T){let E={id:s,role:"assistant",createdAt:new Date().toISOString(),content:T,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,v||(b instanceof Error?(u=(p=this.callbacks).onError)==null||u.call(p,b):(g=(f=this.callbacks).onError)==null||g.call(f,new Error(String(b))))}}async continueConversation(){var o,s,a,i,d;if(this.streaming)return;(o=this.abortController)==null||o.abort(),this.teardownReconnect();let t=Lo();this.activeAssistantMessageId=null,this.setStreaming(!0);let n=new AbortController;this.abortController=n;let r=[...this.messages];try{await this.client.dispatch({messages:r,signal:n.signal,assistantMessageId:t},this.handleEvent)}catch(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 u=$l(c,this.config.errorMessage);if(u){let f={id:t,role:"assistant",createdAt:new Date().toISOString(),content:u,sequence:this.nextSequence()};this.appendMessage(f)}}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(t,n){var s,a,i;if(this.streaming&&!(n!=null&&n.allowReentry))return;n!=null&&n.allowReentry||(s=this.abortController)==null||s.abort(),n!=null&&n.preserveAssistantId&&n.assistantMessageId&&(this.activeAssistantMessageId=n.assistantMessageId);let r=n!=null&&n.preserveAssistantId?n.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(t,this.handleEvent,n==null?void 0:n.assistantMessageId,n==null?void 0:n.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 t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(n=>this.requestWebMcpApproval(n))}requestWebMcpApproval(t){var o,s,a;try{if(((s=(o=this.config.webmcp)==null?void 0:o.autoApprove)==null?void 0:s.call(o,t))===!0)return Promise.resolve(!0)}catch{}let n={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(a=t.description)!=null?a:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},r=`approval-${n.id}`;return this.upsertMessage({id:r,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:n}),new Promise(i=>{this.webMcpApprovalResolvers.set(r,i)})}resolveWebMcpApproval(t,n){let r=this.webMcpApprovalResolvers.get(t);if(!r)return;this.webMcpApprovalResolvers.delete(t);let o=this.messages.find(s=>s.id===t);o!=null&&o.approval&&this.upsertMessage({...o,approval:{...o.approval,status:n,resolvedAt:Date.now()}}),r(n==="approved")}async resolveApproval(t,n,r){var p,u,f,g,b;let o=`approval-${t.id}`,s={...t,status:n,resolvedAt:Date.now()},a=this.messages.find(v=>v.id===o),i={id:o,role:"assistant",content:"",createdAt:(p=a==null?void 0:a.createdAt)!=null?p:new Date().toISOString(),...(a==null?void 0:a.sequence)!==void 0?{sequence:a.sequence}:{},streaming:!1,variant:"approval",approval:s};this.upsertMessage(i),(u=this.abortController)==null||u.abort(),this.abortController=new AbortController,this.setStreaming(!0);let d=this.config.approval,c=d&&typeof d=="object"?d.onDecision:void 0;try{let v;if(c?v=await c({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},n,r):v=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},n),v){let T=null;if(v instanceof Response){if(!v.ok){let E=await v.json().catch(()=>null);throw new Error((f=E==null?void 0:E.error)!=null?f:`Approval request failed: ${v.status}`)}T=v.body}else v instanceof ReadableStream&&(T=v);T?await this.connectStream(T,{allowReentry:!0}):(n==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(v){let T=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,T||(b=(g=this.callbacks).onError)==null||b.call(g,v instanceof Error?v:new Error(String(v)))}}persistAskUserQuestionProgress(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,askUserQuestionAnswers:n.answers,askUserQuestionIndex:n.currentIndex}})}markAskUserQuestionResolved(t,n){let r=this.messages.find(o=>o.id===t.id);r&&this.upsertMessage({...r,agentMetadata:{...r.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...n?{askUserQuestionAnswers:n}:{}}})}async resolveAskUserQuestion(t,n){var p,u,f,g,b,v,T,E,P,I,M,L;let r=this.messages.find(C=>C.id===t.id);if(((p=r==null?void 0:r.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let o=(u=t.agentMetadata)==null?void 0:u.executionId,s=(f=t.toolCall)==null?void 0:f.name;if(!o||!s){(b=(g=this.callbacks).onError)==null||b.call(g,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let a=typeof n=="string"?void 0:n;if(a===void 0&&typeof n=="string"){let C=(v=t.toolCall)==null?void 0:v.args,R=Array.isArray(C==null?void 0:C.questions)?C.questions:[];if(R.length===1){let U=typeof((T=R[0])==null?void 0:T.question)=="string"?R[0].question:"";U&&(a={[U]:n})}}this.markAskUserQuestionResolved(t,a),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,d=(P=t.toolCall)==null?void 0:P.args,c=Array.isArray(d==null?void 0:d.questions)?d.questions:[];if(c.length===0){let C=typeof n=="string"?n:Object.entries(n).map(([R,U])=>`${R}: ${Array.isArray(U)?U.join(", "):U}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:C,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let C=a!=null?a:{};c.forEach((R,U)=>{let j=typeof(R==null?void 0:R.question)=="string"?R.question:"";if(!j)return;let W=C[j],O=Array.isArray(W)?W.join(", "):typeof W=="string"?W:"";this.appendMessage({id:`ask-user-q-${i}-${U}`,role:"assistant",content:j,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${U}`,role:"user",content:O||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let C=await this.client.resumeFlow(o,{[s]:n});if(!C.ok){let R=await C.json().catch(()=>null);throw new Error((I=R==null?void 0:R.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 R=C instanceof Error&&(C.name==="AbortError"||C.message.includes("aborted")||C.message.includes("abort"));this.setStreaming(!1),this.abortController=null,R||(L=(M=this.callbacks).onError)==null||L.call(M,C instanceof Error?C:new Error(String(C)))}}enqueueWebMcpAwait(t){var s,a;let n=(s=t.agentMetadata)==null?void 0:s.executionId,r=(a=t.toolCall)==null?void 0:a.id;if(!n||!r){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let o=this.webMcpAwaitBatches.get(n);o||(o={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(n,o)),!o.seen.has(r)&&(o.seen.add(r),o.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let n of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(n)})}flushWebMcpAwaitBatch(t){let n=this.webMcpAwaitBatches.get(t);if(!n)return;this.webMcpAwaitBatches.delete(t);let{snapshots:r}=n;r.length===1?this.resolveWebMcpToolCall(r[0]):r.length>1&&this.resolveWebMcpToolCallBatch(t,r)}resolveWebMcpToolStartedAt(t){var o,s;let n=this.messages.find(a=>a.id===t.id),r=[(o=n==null?void 0:n.toolCall)==null?void 0:o.startedAt,(s=t.toolCall)==null?void 0:s.startedAt];for(let a of r)if(typeof a=="number"&&Number.isFinite(a))return a;return Date.now()}isSuggestRepliesAlreadyResolved(t){var r,o;if(((r=t.toolCall)==null?void 0:r.name)!==br)return!1;let n=this.messages.find(s=>s.id===t.id);return((o=(n!=null?n:t).agentMetadata)==null?void 0:o.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let n=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:n,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),n}markWebMcpToolComplete(t,n,r,o=Date.now(),s){this.messages.some(a=>a.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...s},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:n,startedAt:r,completedAt:o,duration:void 0,durationMs:Math.max(0,o-r)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,n){var d,c,p,u;let r=[],o=[],s=new AbortController;this.webMcpResolveControllers.add(s),this.setStreaming(!0);let a=await Promise.all(n.map(async f=>{var L,C,R,U,j,W,O;let g=(L=f.toolCall)==null?void 0:L.name,b=(C=f.toolCall)==null?void 0:C.id;if(!g||!b)return null;let v=`${t}:${b}`;if(this.webMcpInflightKeys.has(v)||this.webMcpResolvedKeys.has(v)||this.isSuggestRepliesAlreadyResolved(f))return null;this.webMcpInflightKeys.add(v),r.push(v);let T=this.markWebMcpToolRunning(f),E=(U=(R=f.agentMetadata)==null?void 0:R.webMcpToolCallId)!=null?U:g;if(g===br)return{dedupeKey:v,resumeKey:E,output:Rl(),toolMessage:f,startedAt:T,completedAt:Date.now()};let P=new AbortController;this.webMcpResolveControllers.add(P),o.push(P);let I=this.client.executeWebMcpToolCall(g,(j=f.toolCall)==null?void 0:j.args,P.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 ee=F instanceof Error&&(F.name==="AbortError"||F.message.includes("aborted")||F.message.includes("abort"));return ee||(O=(W=this.callbacks).onError)==null||O.call(W,F instanceof Error?F:new Error(String(F))),this.markWebMcpToolComplete(f,Ta(ee?"Aborted by cancel()":Pg(F)),T),this.webMcpInflightKeys.delete(v),null}return P.signal.aborted?(this.markWebMcpToolComplete(f,Ta("Aborted by cancel()"),T),this.webMcpInflightKeys.delete(v),null):{dedupeKey:v,resumeKey:E,output:M,toolMessage:f,startedAt:T,completedAt:Date.now()}})),i=[];try{if(i=a.filter(b=>b!==null),i.length===0)return;let f={};for(let b of i)f[b.resumeKey]=b.output;let g=await this.client.resumeFlow(t,f,{signal:s.signal});if(!g.ok){let b=await g.json().catch(()=>null);throw new Error((d=b==null?void 0:b.error)!=null?d:`Resume failed: ${g.status}`)}for(let b of i)this.webMcpResolvedKeys.add(b.dedupeKey),this.markWebMcpToolComplete(b.toolMessage,b.output,b.startedAt,b.completedAt,((c=b.toolMessage.toolCall)==null?void 0:c.name)===br?{suggestRepliesResolved:!0}:void 0);g.body&&await this.connectStream(g.body,{allowReentry:!0})}catch(f){if(!(f instanceof Error&&(f.name==="AbortError"||f.message.includes("aborted")||f.message.includes("abort"))))(u=(p=this.callbacks).onError)==null||u.call(p,f instanceof Error?f:new Error(String(f)));else for(let b of i)this.markWebMcpToolComplete(b.toolMessage,Ta("Aborted by cancel()"),b.startedAt)}finally{for(let f of r)this.webMcpInflightKeys.delete(f);for(let f of o)this.webMcpResolveControllers.delete(f);this.webMcpResolveControllers.delete(s),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var b,v,T,E,P,I,M,L,C,R,U,j;let n=(b=t.agentMetadata)==null?void 0:b.executionId,r=(v=t.toolCall)==null?void 0:v.name,o=(T=t.toolCall)==null?void 0:T.id;if(!n){(P=(E=this.callbacks).onError)==null||P.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!r)return;if(!o){let W=`${n}:__no_tool_id__:${r}`;if(this.webMcpInflightKeys.has(W)||this.webMcpResolvedKeys.has(W))return;this.webMcpInflightKeys.add(W);try{await this.resumeWithToolOutput(n,r,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(W)}catch(O){(M=(I=this.callbacks).onError)==null||M.call(I,O instanceof Error?O:new Error(String(O)))}finally{this.webMcpInflightKeys.delete(W)}return}let s=`${n}:${o}`;if(this.webMcpInflightKeys.has(s)||this.webMcpResolvedKeys.has(s)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(s);let a=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:d}=i;this.setStreaming(!0);let c=r===br,p=(L=t.toolCall)==null?void 0:L.args,u=c?null:this.client.executeWebMcpToolCall(r,p,d),f="execute",g=a;try{let W;if(c?W=Rl():u?W=await u:W={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},g=Date.now(),d.aborted){this.markWebMcpToolComplete(t,Ta("Aborted by cancel()"),a);return}let O=(R=(C=t.agentMetadata)==null?void 0:C.webMcpToolCallId)!=null?R:r;f="resume",await this.resumeWithToolOutput(n,O,W,{onHttpOk:()=>{this.webMcpResolvedKeys.add(s),this.markWebMcpToolComplete(t,W,a,g,c?{suggestRepliesResolved:!0}:void 0)},signal:d})}catch(W){let O=W instanceof Error&&(W.name==="AbortError"||W.message.includes("aborted")||W.message.includes("abort"));(f==="execute"||O||d.aborted)&&this.markWebMcpToolComplete(t,Ta(O||d.aborted?"Aborted by cancel()":Pg(W)),a),O||(j=(U=this.callbacks).onError)==null||j.call(U,W instanceof Error?W:new Error(String(W)))}finally{this.webMcpInflightKeys.delete(s),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,n,r,o){var a,i;let s=await this.client.resumeFlow(t,{[n]:r},{signal:o==null?void 0:o.signal});if(!s.ok){let d=await s.json().catch(()=>null);throw new Error((a=d==null?void 0:d.error)!=null?a:`Resume failed: ${s.status}`)}(i=o==null?void 0:o.onHttpOk)==null||i.call(o),s.body?await this.connectStream(s.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var o;let n=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let s={id:n,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(n,s),this.selectedArtifactId=n,this.emitArtifactsState(),s}let r={id:n,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(o=t.props)!=null?o:{}};return this.artifacts.set(n,r),this.selectedArtifactId=n,this.emitArtifactsState(),r}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,n;(n=(t=this.callbacks).onArtifactsState)==null||n.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var n,r;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(n=t.component)!=null?n:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="markdown"&&(o.markdown=((r=o.markdown)!=null?r:"")+t.artDelta);break}case"artifact_update":{let o=this.artifacts.get(t.id);(o==null?void 0:o.artifactType)==="component"&&(o.props={...o.props,...t.props},t.component&&(o.component=t.component));break}case"artifact_complete":{let o=this.artifacts.get(t.id);o&&(o.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var n;(n=this.abortController)==null||n.abort(),this.abortController=null,this.teardownReconnect(),this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(r=>{var o;return{...r,streaming:!1,sequence:(o=r.sequence)!=null?o:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,n=null){this.artifacts.clear();for(let r of t)this.artifacts.set(r.id,{...r,status:"complete"});this.selectedArtifactId=n,this.emitArtifactsState()}trackCursor(t){var o,s;let n=(o=this.agentExecution)==null?void 0:o.executionId;if(!n||!this.activeAssistantMessageId||((s=this.agentExecution)==null?void 0:s.status)!=="running")return;let r=this.resumable===null;this.resumable={executionId:n,lastEventId:t,assistantMessageId:this.activeAssistantMessageId,status:"running"},this.notifyExecutionState(r)}isDurableDrop(){var t;return this.resumable!==null&&typeof this.config.reconnectStream=="function"&&((t=this.abortController)==null?void 0:t.signal.aborted)!==!0&&this.webMcpResolveControllers.size===0&&this.webMcpAwaitBatches.size===0&&!this.isAwaitPending()}isAwaitPending(){return this.messages.some(t=>{var n,r,o;return((n=t.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&((r=t.agentMetadata)==null?void 0:r.askUserQuestionAnswered)!==!0||t.variant==="approval"&&((o=t.approval)==null?void 0:o.status)==="pending"})}beginReconnect(){var t,n;this.reconnecting||!this.resumable||typeof this.config.reconnectStream!="function"||(this.reconnecting=!0,(n=(t=this.callbacks).onReconnect)==null||n.call(t,{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(()=>(Lg(),kg)).then(({createReconnectController:t})=>{let n=t(this.buildReconnectHost());return this.reconnectController=n,n})),this.reconnectControllerPromise)}buildReconnectHost(){let t=this;return{get config(){return t.config},getResumable:()=>t.resumable,clearResumable:()=>t.clearResumable(),getStatus:()=>t.status,setStatus:n=>t.setStatus(n),setStreaming:n=>t.setStreaming(n),setReconnecting:n=>{t.reconnecting=n},setAbortController:n=>{t.abortController=n},getMessages:()=>t.messages,notifyMessagesChanged:()=>t.callbacks.onMessagesChanged([...t.messages]),resumeConnect:(n,r,o)=>t.connectStream(n,{assistantMessageId:r,allowReentry:!0,preserveAssistantId:!0,seedContent:o}),appendMessage:n=>t.appendMessage(n),nextSequence:()=>t.nextSequence(),emitReconnect:n=>{var r,o;return(o=(r=t.callbacks).onReconnect)==null?void 0:o.call(r,n)},buildErrorContent:n=>$l(new Error(n),t.config.errorMessage),onError:n=>{var r,o;return(o=(r=t.callbacks).onError)==null?void 0:o.call(r,n)}}}reconnectNow(){var t;if(this.reconnecting){(t=this.reconnectController)==null||t.wake();return}this.beginReconnect()}resumeFromHandle(t){if(typeof this.config.reconnectStream!="function"||this.reconnecting)return;let n=this.reopenTrailingAssistant();n||(n=Lo(),this.appendMessage({id:n,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:this.nextSequence()})),this.activeAssistantMessageId=n,this.agentExecution||(this.agentExecution={executionId:t.executionId,agentId:"",agentName:"",status:"running",currentIteration:0,maxTurns:0}),this.resumable={executionId:t.executionId,lastEventId:t.after,assistantMessageId:n,status:"running"},this.beginReconnect()}reopenTrailingAssistant(){for(let t=this.messages.length-1;t>=0;t--){let n=this.messages[t];if(n.role==="assistant"&&!n.variant)return n.streaming=!0,this.callbacks.onMessagesChanged([...this.messages]),n.id;if(n.role==="user")break}return null}teardownReconnect(){var t;this.reconnecting=!1,(t=this.reconnectController)==null||t.teardown(),this.clearResumable()}clearResumable(){var n,r;this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null);let t=this.resumable!==null;this.resumable=null,t&&((r=(n=this.config).onExecutionState)==null||r.call(n,null))}notifyExecutionState(t){let n=this.config.onExecutionState;if(n){if(t){this.executionStateTimer&&(clearTimeout(this.executionStateTimer),this.executionStateTimer=null),n(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(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let n=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),n&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let r=[...this.messages].reverse().find(s=>s.role==="assistant"&&s.content&&!s.voiceProcessing);if(!r)return;if(this.ttsSpokenMessageIds.has(r.id)){this.ttsSpokenMessageIds.delete(r.id);return}let o=Fl(r.content);o.trim()&&this.readAloud.play(r.id,{text:o,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ns(t)}toggleReadAloud(t){let n=this.messages.find(s=>s.id===t);if(!n||n.role!=="assistant")return;let r=Fl(n.content||"");if(!r.trim())return;let o=this.config.textToSpeech;this.readAloud.toggle(t,{text:r,voice:o==null?void 0:o.voice,rate:o==null?void 0:o.rate,pitch:o==null?void 0:o.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let n=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,n]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let n=this.ensureSequence(t),r=this.messages.findIndex(o=>o.id===n.id);if(r===-1){this.appendMessage(n);return}this.messages=this.messages.map((o,s)=>{var p,u,f,g,b,v,T,E,P,I,M,L,C,R,U;if(s!==r)return o;let a={...o,...n};if(((p=o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&n.agentMetadata&&(a.agentMetadata={...n.agentMetadata,askUserQuestionAnswered:!0,...o.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:o.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((u=o.agentMetadata)==null?void 0:u.suggestRepliesResolved)===!0&&n.agentMetadata&&(a.agentMetadata={...(f=a.agentMetadata)!=null?f:n.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),o.approval&&n.approval&&o.approval.id===n.approval.id){let j=o.approval,W=n.approval;a.approval={...j,...W,executionId:W.executionId||j.executionId,toolName:W.toolName||j.toolName,description:W.description||j.description,toolType:(g=W.toolType)!=null?g:j.toolType,reason:(b=W.reason)!=null?b:j.reason,parameters:(v=W.parameters)!=null?v:j.parameters}}let i=(T=n.toolCall)==null?void 0:T.name,d=(E=n.agentMetadata)==null?void 0:E.executionId,c=(P=n.toolCall)==null?void 0:P.id;if(i&&Ig(i)&&d&&c&&((I=n.agentMetadata)==null?void 0:I.awaitingLocalTool)===!0){let j=`${d}:${c}`,W=this.webMcpInflightKeys.has(j),O=this.webMcpResolvedKeys.has(j),F=(M=o.toolCall)==null?void 0:M.name,ee=((L=o.agentMetadata)==null?void 0:L.executionId)===d&&((C=o.toolCall)==null?void 0:C.id)===c&&F!==void 0&&Ig(F)&&((R=o.toolCall)==null?void 0:R.status)==="complete";(W||O||ee)&&(a.agentMetadata={...(U=a.agentMetadata)!=null?U:{},awaitingLocalTool:!1},a.toolCall=o.toolCall,a.streaming=o.streaming)}return a}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((n,r)=>{var d,c;let o=new Date(n.createdAt).getTime(),s=new Date(r.createdAt).getTime();if(!Number.isNaN(o)&&!Number.isNaN(s)&&o!==s)return o-s;let a=(d=n.sequence)!=null?d:0,i=(c=r.sequence)!=null?c:0;return a!==i?a-i:n.id.localeCompare(r.id)})}};var A=require("lucide"),ab={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},he=(e,t=24,n="currentColor",r=2)=>{let o=ab[e];return o?ib(o,t,n,r):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function ib(e,t,n,r){if(!Array.isArray(e))return null;let o=document.createElementNS("http://www.w3.org/2000/svg","svg");return o.setAttribute("width",String(t)),o.setAttribute("height",String(t)),o.setAttribute("viewBox","0 0 24 24"),o.setAttribute("fill","none"),o.setAttribute("stroke",n),o.setAttribute("stroke-width",String(r)),o.setAttribute("stroke-linecap","round"),o.setAttribute("stroke-linejoin","round"),o.setAttribute("aria-hidden","true"),e.forEach(s=>{if(!Array.isArray(s)||s.length<2)return;let a=s[0],i=s[1];if(!i)return;let d=document.createElementNS("http://www.w3.org/2000/svg",a);Object.entries(i).forEach(([c,p])=>{c!=="stroke"&&d.setAttribute(c,String(p))}),o.appendChild(d)}),o}var xi={allowedTypes:Yr,maxFileSize:10*1024*1024,maxFiles:4};function lb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function cb(e){return e==="application/pdf"||e.startsWith("text/")||e.includes("word")?"file-text":e.includes("excel")||e.includes("spreadsheet")?"file-spreadsheet":e==="application/json"?"file-code":"file"}var ls=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var n,r,o;this.config={allowedTypes:(n=t.allowedTypes)!=null?n:xi.allowedTypes,maxFileSize:(r=t.maxFileSize)!=null?r:xi.maxFileSize,maxFiles:(o=t.maxFiles)!=null?o:xi.maxFiles,onFileRejected:t.onFileRejected,onAttachmentsChange:t.onAttachmentsChange}}setPreviewsContainer(t){this.previewsContainer=t}updateConfig(t){t.allowedTypes!==void 0&&(this.config.allowedTypes=t.allowedTypes.length>0?t.allowedTypes:xi.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var n,r,o,s,a,i,d;if(t.length){for(let c of t){if(this.attachments.length>=this.config.maxFiles){(r=(n=this.config).onFileRejected)==null||r.call(n,c,"count");continue}let p=xg(c,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let u=(o=p.error)!=null&&o.includes("type")?"type":"size";(a=(s=this.config).onFileRejected)==null||a.call(s,c,u);continue}try{let u=await bg(c),f=fi(c)?URL.createObjectURL(c):null,g={id:lb(),file:c,previewUrl:f,contentPart:u};this.attachments.push(g),this.renderPreview(g)}catch(u){console.error("[AttachmentManager] Failed to process file:",u)}}this.updatePreviewsVisibility(),(d=(i=this.config).onAttachmentsChange)==null||d.call(i,this.getAttachments())}}removeAttachment(t){var s,a,i;let n=this.attachments.findIndex(d=>d.id===t);if(n===-1)return;let r=this.attachments[n];r.previewUrl&&URL.revokeObjectURL(r.previewUrl),this.attachments.splice(n,1);let o=(s=this.previewsContainer)==null?void 0:s.querySelector(`[data-attachment-id="${t}"]`);o&&o.remove(),this.updatePreviewsVisibility(),(i=(a=this.config).onAttachmentsChange)==null||i.call(a,this.getAttachments())}clearAttachments(){var t,n;for(let r of this.attachments)r.previewUrl&&URL.revokeObjectURL(r.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(n=(t=this.config).onAttachmentsChange)==null||n.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let n=fi(t.file),r=y("div","persona-attachment-preview persona-relative persona-inline-block");if(r.setAttribute("data-attachment-id",t.id),r.style.width="48px",r.style.height="48px",n&&t.previewUrl){let a=y("img");a.src=t.previewUrl,a.alt=t.file.name,a.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",a.style.width="48px",a.style.height="48px",a.style.objectFit="cover",a.style.borderRadius="8px",r.appendChild(a)}else{let a=y("div");a.style.width="48px",a.style.height="48px",a.style.borderRadius="8px",a.style.backgroundColor="var(--persona-container, #f3f4f6)",a.style.border="1px solid var(--persona-border, #e5e7eb)",a.style.display="flex",a.style.flexDirection="column",a.style.alignItems="center",a.style.justifyContent="center",a.style.gap="2px",a.style.overflow="hidden";let i=cb(t.file.type),d=he(i,20,"var(--persona-muted, #6b7280)",1.5);d&&a.appendChild(d);let c=y("span");c.textContent=vg(t.file.type,t.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=y("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");o.type="button",o.setAttribute("aria-label","Remove attachment"),o.style.position="absolute",o.style.top="-4px",o.style.right="-4px",o.style.width="18px",o.style.height="18px",o.style.borderRadius="50%",o.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",o.style.border="none",o.style.cursor="pointer",o.style.display="flex",o.style.alignItems="center",o.style.justifyContent="center",o.style.padding="0";let s=he("x",10,"var(--persona-text-inverse, #ffffff)",2);s?o.appendChild(s):(o.textContent="\xD7",o.style.color="var(--persona-text-inverse, #ffffff)",o.style.fontSize="14px",o.style.lineHeight="1"),o.addEventListener("click",a=>{a.preventDefault(),a.stopPropagation(),this.removeAttachment(t.id)}),r.appendChild(o),this.previewsContainer.appendChild(r)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,n){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:n})}};var Rg=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function Ea(e,t){if(!e)return t;if(!t)return e;let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];Rg(s)&&Rg(o)?n[r]=Ea(s,o):n[r]=o}return n}var zn="min(440px, calc(100vw - 24px))",vi="440px",db={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:zn,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:db,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 Wg(e,t){if(!(!e&&!t))return e?t?Ea(e,t):e:t}function wi(e){var t,n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L;return e?{...Bt,...e,theme:Wg(Bt.theme,e.theme),darkTheme:Wg(Bt.darkTheme,e.darkTheme),launcher:{...Bt.launcher,...e.launcher,dock:{...(t=Bt.launcher)==null?void 0:t.dock,...(n=e.launcher)==null?void 0:n.dock},clearChat:{...(r=Bt.launcher)==null?void 0:r.clearChat,...(o=e.launcher)==null?void 0:o.clearChat}},copy:{...Bt.copy,...e.copy},sendButton:{...Bt.sendButton,...e.sendButton},statusIndicator:{...Bt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Bt.voiceRecognition,...e.voiceRecognition},features:(()=>{var oe,ae,ie,ye,je,K,Y,ke,X,ce;let C=(oe=Bt.features)==null?void 0:oe.artifacts,R=(ae=e.features)==null?void 0:ae.artifacts,U=(ie=Bt.features)==null?void 0:ie.scrollToBottom,j=(ye=e.features)==null?void 0:ye.scrollToBottom,W=(je=Bt.features)==null?void 0:je.scrollBehavior,O=(K=e.features)==null?void 0:K.scrollBehavior,F=(Y=Bt.features)==null?void 0:Y.streamAnimation,ee=(ke=e.features)==null?void 0:ke.streamAnimation,Me=(X=Bt.features)==null?void 0:X.askUserQuestion,pe=(ce=e.features)==null?void 0:ce.askUserQuestion,te=C===void 0&&R===void 0?void 0:{...C,...R,layout:{...C==null?void 0:C.layout,...R==null?void 0:R.layout}},Pe=U===void 0&&j===void 0?void 0:{...U,...j},Ie=W===void 0&&O===void 0?void 0:{...W,...O},re=F===void 0&&ee===void 0?void 0:{...F,...ee},Se=Me===void 0&&pe===void 0?void 0:{...Me,...pe,styles:{...Me==null?void 0:Me.styles,...pe==null?void 0:pe.styles}};return{...Bt.features,...e.features,...Pe!==void 0?{scrollToBottom:Pe}:{},...Ie!==void 0?{scrollBehavior:Ie}:{},...te!==void 0?{artifacts:te}:{},...re!==void 0?{streamAnimation:re}:{},...Se!==void 0?{askUserQuestion:Se}:{}}})(),suggestionChips:(s=e.suggestionChips)!=null?s:Bt.suggestionChips,suggestionChipsConfig:{...Bt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Bt.layout,...e.layout,header:{...(a=Bt.layout)==null?void 0:a.header,...(i=e.layout)==null?void 0:i.header},messages:{...(d=Bt.layout)==null?void 0:d.messages,...(c=e.layout)==null?void 0:c.messages,avatar:{...(u=(p=Bt.layout)==null?void 0:p.messages)==null?void 0:u.avatar,...(g=(f=e.layout)==null?void 0:f.messages)==null?void 0:g.avatar},timestamp:{...(v=(b=Bt.layout)==null?void 0:b.messages)==null?void 0:v.timestamp,...(E=(T=e.layout)==null?void 0:T.messages)==null?void 0:E.timestamp}},slots:{...(P=Bt.layout)==null?void 0:P.slots,...(I=e.layout)==null?void 0:I.slots}},markdown:{...Bt.markdown,...e.markdown,options:{...(M=Bt.markdown)==null?void 0:M.options,...(L=e.markdown)==null?void 0:L.options}},messageActions:{...Bt.messageActions,...e.messageActions}}:Bt}var jl={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"}},Ul={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"}},ql={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:zn,maxWidth:vi,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 Fs(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let n=t.split("."),r=e;for(let o of n){if(r==null)return;r=r[o]}return typeof r=="string"&&(r.startsWith("palette.")||r.startsWith("semantic.")||r.startsWith("components."))?Fs(e,r):r}function Ci(e){let t={};function n(r,o){for(let[s,a]of Object.entries(r)){let i=`${o}.${s}`;if(typeof a=="string"){let d=Fs(e,a);d!==void 0&&(t[i]={path:i,value:d,type:o.includes("color")?"color":o.includes("spacing")?"spacing":o.includes("typography")?"typography":o.includes("shadow")?"shadow":o.includes("border")?"border":"color"})}else typeof a=="object"&&a!==null&&n(a,i)}}return n(e.palette,"palette"),n(e.semantic,"semantic"),n(e.components,"components"),t}function zl(e){let t=[],n=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||n.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||n.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:n}}function Hg(e,t){let n={...e};for(let[r,o]of Object.entries(t)){let s=n[r];s&&typeof s=="object"&&!Array.isArray(s)&&o&&typeof o=="object"&&!Array.isArray(o)?n[r]=Hg(s,o):n[r]=o}return n}function pb(e,t){return t?Hg(e,t):e}function _s(e,t={}){var o,s,a,i,d,c,p,u,f,g,b,v,T;let n={palette:jl,semantic:Ul,components:ql},r={palette:{...n.palette,...e==null?void 0:e.palette,colors:{...n.palette.colors,...(o=e==null?void 0:e.palette)==null?void 0:o.colors},spacing:{...n.palette.spacing,...(s=e==null?void 0:e.palette)==null?void 0:s.spacing},typography:{...n.palette.typography,...(a=e==null?void 0:e.palette)==null?void 0:a.typography},shadows:{...n.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...n.palette.borders,...(d=e==null?void 0:e.palette)==null?void 0:d.borders},radius:{...n.palette.radius,...(c=e==null?void 0:e.palette)==null?void 0:c.radius}},semantic:{...n.semantic,...e==null?void 0:e.semantic,colors:{...n.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...n.semantic.colors.interactive,...(f=(u=e==null?void 0:e.semantic)==null?void 0:u.colors)==null?void 0:f.interactive},feedback:{...n.semantic.colors.feedback,...(b=(g=e==null?void 0:e.semantic)==null?void 0:g.colors)==null?void 0:b.feedback}},spacing:{...n.semantic.spacing,...(v=e==null?void 0:e.semantic)==null?void 0:v.spacing},typography:{...n.semantic.typography,...(T=e==null?void 0:e.semantic)==null?void 0:T.typography}},components:pb(n.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=zl(r);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(P=>P.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)r=E.transform(r);return r}function Ai(e){var v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie,ye,je,K,Y,ke,X,ce,Re,be,Ge,ft,Ht,nt,fe,Q,lt,Ke,Te,Ce,et,zt,xe,ue,wn,At,hn,vr,wr,qe,k,me,Ee,Le,Be,rt,Ye,yt,ge,D,ve,de,ht,Xe,Pt,kt,vt,Wt,Qt,Ft,tn,Cr,Fr,ar,ir,no,Vt,lr,_r,Bn,Ln,Dn,cr,Ar,ro,Gn,oo,St,Sr,Tr,$r,dr,bt,Fo,Er,_o,Pn,fs,so,jr,ao,io,$o,jo,lo,wt,Nn,On,Cn,Tt,Jn,Xn,Fn,co;let t=Ci(e),n={};for(let[Ae,Ur]of Object.entries(t)){let Qn=Ae.replace(/\./g,"-");n[`--persona-${Qn}`]=Ur.value}n["--persona-primary"]=(v=n["--persona-semantic-colors-primary"])!=null?v:n["--persona-palette-colors-primary-500"],n["--persona-secondary"]=(T=n["--persona-semantic-colors-secondary"])!=null?T:n["--persona-palette-colors-secondary-500"],n["--persona-accent"]=(E=n["--persona-semantic-colors-accent"])!=null?E:n["--persona-palette-colors-accent-500"],n["--persona-surface"]=(P=n["--persona-semantic-colors-surface"])!=null?P:n["--persona-palette-colors-gray-50"],n["--persona-background"]=(I=n["--persona-semantic-colors-background"])!=null?I:n["--persona-palette-colors-gray-50"],n["--persona-container"]=(M=n["--persona-semantic-colors-container"])!=null?M:n["--persona-palette-colors-gray-100"],n["--persona-text"]=(L=n["--persona-semantic-colors-text"])!=null?L:n["--persona-palette-colors-gray-900"],n["--persona-text-muted"]=(C=n["--persona-semantic-colors-text-muted"])!=null?C:n["--persona-palette-colors-gray-500"],n["--persona-text-inverse"]=(R=n["--persona-semantic-colors-text-inverse"])!=null?R:n["--persona-palette-colors-gray-50"],n["--persona-border"]=(U=n["--persona-semantic-colors-border"])!=null?U:n["--persona-palette-colors-gray-200"],n["--persona-divider"]=(j=n["--persona-semantic-colors-divider"])!=null?j:n["--persona-palette-colors-gray-200"],n["--persona-muted"]=n["--persona-text-muted"],n["--persona-voice-recording-indicator"]=(W=n["--persona-components-voice-recording-indicator"])!=null?W:n["--persona-palette-colors-error-500"],n["--persona-voice-recording-bg"]=(O=n["--persona-components-voice-recording-background"])!=null?O:n["--persona-palette-colors-error-50"],n["--persona-voice-processing-icon"]=(F=n["--persona-components-voice-processing-icon"])!=null?F:n["--persona-palette-colors-primary-500"],n["--persona-voice-speaking-icon"]=(ee=n["--persona-components-voice-speaking-icon"])!=null?ee:n["--persona-palette-colors-success-500"],n["--persona-approval-bg"]=(Me=n["--persona-components-approval-requested-background"])!=null?Me:n["--persona-surface"],n["--persona-approval-border"]=(pe=n["--persona-components-approval-requested-border"])!=null?pe:n["--persona-border"],n["--persona-approval-text"]=(te=n["--persona-components-approval-requested-text"])!=null?te:n["--persona-palette-colors-gray-900"],n["--persona-approval-shadow"]=(Pe=n["--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)",n["--persona-approval-approve-bg"]=(Ie=n["--persona-components-approval-approve-background"])!=null?Ie:n["--persona-button-primary-bg"],n["--persona-approval-deny-bg"]=(re=n["--persona-components-approval-deny-background"])!=null?re:n["--persona-container"],n["--persona-attachment-image-bg"]=(Se=n["--persona-components-attachment-image-background"])!=null?Se:n["--persona-palette-colors-gray-100"],n["--persona-attachment-image-border"]=(oe=n["--persona-components-attachment-image-border"])!=null?oe:n["--persona-palette-colors-gray-200"],n["--persona-font-family"]=(ae=n["--persona-semantic-typography-fontFamily"])!=null?ae:n["--persona-palette-typography-fontFamily-sans"],n["--persona-font-size"]=(ie=n["--persona-semantic-typography-fontSize"])!=null?ie:n["--persona-palette-typography-fontSize-base"],n["--persona-font-weight"]=(ye=n["--persona-semantic-typography-fontWeight"])!=null?ye:n["--persona-palette-typography-fontWeight-normal"],n["--persona-line-height"]=(je=n["--persona-semantic-typography-lineHeight"])!=null?je:n["--persona-palette-typography-lineHeight-normal"],n["--persona-input-font-family"]=n["--persona-font-family"],n["--persona-input-font-weight"]=n["--persona-font-weight"],n["--persona-radius-sm"]=(K=n["--persona-palette-radius-sm"])!=null?K:"0.125rem",n["--persona-radius-md"]=(Y=n["--persona-palette-radius-md"])!=null?Y:"0.375rem",n["--persona-radius-lg"]=(ke=n["--persona-palette-radius-lg"])!=null?ke:"0.5rem",n["--persona-radius-xl"]=(X=n["--persona-palette-radius-xl"])!=null?X:"0.75rem",n["--persona-radius-full"]=(ce=n["--persona-palette-radius-full"])!=null?ce:"9999px",n["--persona-launcher-radius"]=(be=(Re=n["--persona-components-launcher-borderRadius"])!=null?Re:n["--persona-palette-radius-full"])!=null?be:"9999px",n["--persona-launcher-bg"]=(Ge=n["--persona-components-launcher-background"])!=null?Ge:n["--persona-primary"],n["--persona-launcher-fg"]=(ft=n["--persona-components-launcher-foreground"])!=null?ft:n["--persona-text-inverse"],n["--persona-launcher-border"]=(Ht=n["--persona-components-launcher-border"])!=null?Ht:n["--persona-border"],n["--persona-button-primary-bg"]=(nt=n["--persona-components-button-primary-background"])!=null?nt:n["--persona-primary"],n["--persona-button-primary-fg"]=(fe=n["--persona-components-button-primary-foreground"])!=null?fe:n["--persona-text-inverse"],n["--persona-button-radius"]=(lt=(Q=n["--persona-components-button-primary-borderRadius"])!=null?Q:n["--persona-palette-radius-full"])!=null?lt:"9999px",n["--persona-panel-radius"]=(Te=(Ke=n["--persona-components-panel-borderRadius"])!=null?Ke:n["--persona-radius-xl"])!=null?Te:"0.75rem",n["--persona-panel-border"]=(Ce=n["--persona-components-panel-border"])!=null?Ce:`1px solid ${n["--persona-border"]}`,n["--persona-panel-shadow"]=(zt=(et=n["--persona-components-panel-shadow"])!=null?et:n["--persona-palette-shadows-xl"])!=null?zt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",n["--persona-launcher-shadow"]=(xe=n["--persona-components-launcher-shadow"])!=null?xe:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",n["--persona-input-radius"]=(wn=(ue=n["--persona-components-input-borderRadius"])!=null?ue:n["--persona-radius-lg"])!=null?wn:"0.5rem",n["--persona-message-user-radius"]=(hn=(At=n["--persona-components-message-user-borderRadius"])!=null?At:n["--persona-radius-lg"])!=null?hn:"0.5rem",n["--persona-message-assistant-radius"]=(wr=(vr=n["--persona-components-message-assistant-borderRadius"])!=null?vr:n["--persona-radius-lg"])!=null?wr:"0.5rem",n["--persona-header-bg"]=(qe=n["--persona-components-header-background"])!=null?qe:n["--persona-surface"],n["--persona-header-border"]=(k=n["--persona-components-header-border"])!=null?k:n["--persona-divider"],n["--persona-header-icon-bg"]=(me=n["--persona-components-header-iconBackground"])!=null?me:n["--persona-primary"],n["--persona-header-icon-fg"]=(Ee=n["--persona-components-header-iconForeground"])!=null?Ee:n["--persona-text-inverse"],n["--persona-header-title-fg"]=(Le=n["--persona-components-header-titleForeground"])!=null?Le:n["--persona-primary"],n["--persona-header-subtitle-fg"]=(Be=n["--persona-components-header-subtitleForeground"])!=null?Be:n["--persona-text-muted"],n["--persona-header-action-icon-fg"]=(rt=n["--persona-components-header-actionIconForeground"])!=null?rt:n["--persona-muted"];let r=(Ye=e.components)==null?void 0:Ye.header;r!=null&&r.shadow&&(n["--persona-header-shadow"]=r.shadow),r!=null&&r.borderBottom&&(n["--persona-header-border-bottom"]=r.borderBottom);let o=(yt=e.components)==null?void 0:yt.introCard;n["--persona-intro-card-bg"]=(ge=n["--persona-components-introCard-background"])!=null?ge:n["--persona-surface"],n["--persona-intro-card-radius"]=(D=n["--persona-components-introCard-borderRadius"])!=null?D:"1rem",n["--persona-intro-card-padding"]=(ve=n["--persona-components-introCard-padding"])!=null?ve:"1.5rem",n["--persona-intro-card-shadow"]=(ht=(de=o==null?void 0:o.shadow)!=null?de:n["--persona-components-introCard-shadow"])!=null?ht:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-input-background"]=(Xe=n["--persona-components-input-background"])!=null?Xe:n["--persona-surface"],n["--persona-input-placeholder"]=(Pt=n["--persona-components-input-placeholder"])!=null?Pt:n["--persona-text-muted"],n["--persona-message-user-bg"]=(kt=n["--persona-components-message-user-background"])!=null?kt:n["--persona-accent"],n["--persona-message-user-text"]=(vt=n["--persona-components-message-user-text"])!=null?vt:n["--persona-text-inverse"],n["--persona-message-user-shadow"]=(Wt=n["--persona-components-message-user-shadow"])!=null?Wt:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-message-assistant-bg"]=(Qt=n["--persona-components-message-assistant-background"])!=null?Qt:n["--persona-surface"],n["--persona-message-assistant-text"]=(Ft=n["--persona-components-message-assistant-text"])!=null?Ft:n["--persona-text"],n["--persona-message-assistant-border"]=(tn=n["--persona-components-message-assistant-border"])!=null?tn:n["--persona-border"],n["--persona-message-assistant-shadow"]=(Cr=n["--persona-components-message-assistant-shadow"])!=null?Cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-bg"]=(ar=(Fr=n["--persona-components-scrollToBottom-background"])!=null?Fr:n["--persona-button-primary-bg"])!=null?ar:n["--persona-accent"],n["--persona-scroll-to-bottom-fg"]=(no=(ir=n["--persona-components-scrollToBottom-foreground"])!=null?ir:n["--persona-button-primary-fg"])!=null?no:n["--persona-text-inverse"],n["--persona-scroll-to-bottom-border"]=(Vt=n["--persona-components-scrollToBottom-border"])!=null?Vt:n["--persona-primary"],n["--persona-scroll-to-bottom-size"]=(lr=n["--persona-components-scrollToBottom-size"])!=null?lr:"40px",n["--persona-scroll-to-bottom-radius"]=(Ln=(Bn=(_r=n["--persona-components-scrollToBottom-borderRadius"])!=null?_r:n["--persona-button-radius"])!=null?Bn:n["--persona-radius-full"])!=null?Ln:"9999px",n["--persona-scroll-to-bottom-shadow"]=(cr=(Dn=n["--persona-components-scrollToBottom-shadow"])!=null?Dn:n["--persona-palette-shadows-sm"])!=null?cr:"0 1px 2px 0 rgb(0 0 0 / 0.05)",n["--persona-scroll-to-bottom-padding"]=(Ar=n["--persona-components-scrollToBottom-padding"])!=null?Ar:"0.5rem 0.875rem",n["--persona-scroll-to-bottom-gap"]=(ro=n["--persona-components-scrollToBottom-gap"])!=null?ro:"0.5rem",n["--persona-scroll-to-bottom-font-size"]=(oo=(Gn=n["--persona-components-scrollToBottom-fontSize"])!=null?Gn:n["--persona-palette-typography-fontSize-sm"])!=null?oo:"0.875rem",n["--persona-scroll-to-bottom-icon-size"]=(St=n["--persona-components-scrollToBottom-iconSize"])!=null?St:"14px",n["--persona-tool-bubble-shadow"]=(Sr=n["--persona-components-toolBubble-shadow"])!=null?Sr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-reasoning-bubble-shadow"]=(Tr=n["--persona-components-reasoningBubble-shadow"])!=null?Tr:"0 5px 15px rgba(15, 23, 42, 0.08)",n["--persona-composer-shadow"]=($r=n["--persona-components-composer-shadow"])!=null?$r:"none",n["--persona-md-inline-code-bg"]=(dr=n["--persona-components-markdown-inlineCode-background"])!=null?dr:n["--persona-container"],n["--persona-md-inline-code-color"]=(bt=n["--persona-components-markdown-inlineCode-foreground"])!=null?bt:n["--persona-text"],n["--persona-md-link-color"]=(Er=(Fo=n["--persona-components-markdown-link-foreground"])!=null?Fo:n["--persona-accent"])!=null?Er:"#0f0f0f";let s=n["--persona-components-markdown-heading-h1-fontSize"];s&&(n["--persona-md-h1-size"]=s);let a=n["--persona-components-markdown-heading-h1-fontWeight"];a&&(n["--persona-md-h1-weight"]=a);let i=n["--persona-components-markdown-heading-h2-fontSize"];i&&(n["--persona-md-h2-size"]=i);let d=n["--persona-components-markdown-heading-h2-fontWeight"];d&&(n["--persona-md-h2-weight"]=d);let c=n["--persona-components-markdown-prose-fontFamily"];c&&c!=="inherit"&&(n["--persona-md-prose-font-family"]=c),n["--persona-md-code-block-bg"]=(_o=n["--persona-components-markdown-codeBlock-background"])!=null?_o:n["--persona-container"],n["--persona-md-code-block-border-color"]=(Pn=n["--persona-components-markdown-codeBlock-borderColor"])!=null?Pn:n["--persona-border"],n["--persona-md-code-block-text-color"]=(fs=n["--persona-components-markdown-codeBlock-textColor"])!=null?fs:"inherit",n["--persona-md-table-header-bg"]=(so=n["--persona-components-markdown-table-headerBackground"])!=null?so:n["--persona-container"],n["--persona-md-table-border-color"]=(jr=n["--persona-components-markdown-table-borderColor"])!=null?jr:n["--persona-border"],n["--persona-md-hr-color"]=(ao=n["--persona-components-markdown-hr-color"])!=null?ao:n["--persona-divider"],n["--persona-md-blockquote-border-color"]=(io=n["--persona-components-markdown-blockquote-borderColor"])!=null?io:n["--persona-palette-colors-gray-900"],n["--persona-md-blockquote-bg"]=($o=n["--persona-components-markdown-blockquote-background"])!=null?$o:"transparent",n["--persona-md-blockquote-text-color"]=(jo=n["--persona-components-markdown-blockquote-textColor"])!=null?jo:n["--persona-palette-colors-gray-500"],n["--cw-container"]=(lo=n["--persona-components-collapsibleWidget-container"])!=null?lo:n["--persona-surface"],n["--cw-surface"]=(wt=n["--persona-components-collapsibleWidget-surface"])!=null?wt:n["--persona-surface"],n["--cw-border"]=(Nn=n["--persona-components-collapsibleWidget-border"])!=null?Nn:n["--persona-border"],n["--persona-message-border"]=(On=n["--persona-components-message-border"])!=null?On:n["--persona-border"];let p=e.components,u=p==null?void 0:p.iconButton;u&&(u.background&&(n["--persona-icon-btn-bg"]=u.background),u.border&&(n["--persona-icon-btn-border"]=u.border),u.color&&(n["--persona-icon-btn-color"]=u.color),u.padding&&(n["--persona-icon-btn-padding"]=u.padding),u.borderRadius&&(n["--persona-icon-btn-radius"]=u.borderRadius),u.hoverBackground&&(n["--persona-icon-btn-hover-bg"]=u.hoverBackground),u.hoverColor&&(n["--persona-icon-btn-hover-color"]=u.hoverColor),u.activeBackground&&(n["--persona-icon-btn-active-bg"]=u.activeBackground),u.activeBorder&&(n["--persona-icon-btn-active-border"]=u.activeBorder));let f=p==null?void 0:p.labelButton;f&&(f.background&&(n["--persona-label-btn-bg"]=f.background),f.border&&(n["--persona-label-btn-border"]=f.border),f.color&&(n["--persona-label-btn-color"]=f.color),f.padding&&(n["--persona-label-btn-padding"]=f.padding),f.borderRadius&&(n["--persona-label-btn-radius"]=f.borderRadius),f.hoverBackground&&(n["--persona-label-btn-hover-bg"]=f.hoverBackground),f.fontSize&&(n["--persona-label-btn-font-size"]=f.fontSize),f.gap&&(n["--persona-label-btn-gap"]=f.gap));let g=p==null?void 0:p.toggleGroup;g&&(g.gap&&(n["--persona-toggle-group-gap"]=g.gap),g.borderRadius&&(n["--persona-toggle-group-radius"]=g.borderRadius));let b=p==null?void 0:p.artifact;if(b!=null&&b.toolbar){let Ae=b.toolbar;Ae.iconHoverColor&&(n["--persona-artifact-toolbar-icon-hover-color"]=Ae.iconHoverColor),Ae.iconHoverBackground&&(n["--persona-artifact-toolbar-icon-hover-bg"]=Ae.iconHoverBackground),Ae.iconPadding&&(n["--persona-artifact-toolbar-icon-padding"]=Ae.iconPadding),Ae.iconBorderRadius&&(n["--persona-artifact-toolbar-icon-radius"]=Ae.iconBorderRadius),Ae.iconBorder&&(n["--persona-artifact-toolbar-icon-border"]=Ae.iconBorder),Ae.toggleGroupGap&&(n["--persona-artifact-toolbar-toggle-group-gap"]=Ae.toggleGroupGap),Ae.toggleBorderRadius&&(n["--persona-artifact-toolbar-toggle-radius"]=Ae.toggleBorderRadius),Ae.copyBackground&&(n["--persona-artifact-toolbar-copy-bg"]=Ae.copyBackground),Ae.copyBorder&&(n["--persona-artifact-toolbar-copy-border"]=Ae.copyBorder),Ae.copyColor&&(n["--persona-artifact-toolbar-copy-color"]=Ae.copyColor),Ae.copyBorderRadius&&(n["--persona-artifact-toolbar-copy-radius"]=Ae.copyBorderRadius),Ae.copyPadding&&(n["--persona-artifact-toolbar-copy-padding"]=Ae.copyPadding),Ae.copyMenuBackground&&(n["--persona-artifact-toolbar-copy-menu-bg"]=Ae.copyMenuBackground,n["--persona-dropdown-bg"]=(Cn=n["--persona-dropdown-bg"])!=null?Cn:Ae.copyMenuBackground),Ae.copyMenuBorder&&(n["--persona-artifact-toolbar-copy-menu-border"]=Ae.copyMenuBorder,n["--persona-dropdown-border"]=(Tt=n["--persona-dropdown-border"])!=null?Tt:Ae.copyMenuBorder),Ae.copyMenuShadow&&(n["--persona-artifact-toolbar-copy-menu-shadow"]=Ae.copyMenuShadow,n["--persona-dropdown-shadow"]=(Jn=n["--persona-dropdown-shadow"])!=null?Jn:Ae.copyMenuShadow),Ae.copyMenuBorderRadius&&(n["--persona-artifact-toolbar-copy-menu-radius"]=Ae.copyMenuBorderRadius,n["--persona-dropdown-radius"]=(Xn=n["--persona-dropdown-radius"])!=null?Xn:Ae.copyMenuBorderRadius),Ae.copyMenuItemHoverBackground&&(n["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=Ae.copyMenuItemHoverBackground,n["--persona-dropdown-item-hover-bg"]=(Fn=n["--persona-dropdown-item-hover-bg"])!=null?Fn:Ae.copyMenuItemHoverBackground),Ae.iconBackground&&(n["--persona-artifact-toolbar-icon-bg"]=Ae.iconBackground),Ae.toolbarBorder&&(n["--persona-artifact-toolbar-border"]=Ae.toolbarBorder)}if(b!=null&&b.tab){let Ae=b.tab;Ae.background&&(n["--persona-artifact-tab-bg"]=Ae.background),Ae.activeBackground&&(n["--persona-artifact-tab-active-bg"]=Ae.activeBackground),Ae.activeBorder&&(n["--persona-artifact-tab-active-border"]=Ae.activeBorder),Ae.borderRadius&&(n["--persona-artifact-tab-radius"]=Ae.borderRadius),Ae.textColor&&(n["--persona-artifact-tab-color"]=Ae.textColor),Ae.hoverBackground&&(n["--persona-artifact-tab-hover-bg"]=Ae.hoverBackground),Ae.listBackground&&(n["--persona-artifact-tab-list-bg"]=Ae.listBackground),Ae.listBorderColor&&(n["--persona-artifact-tab-list-border-color"]=Ae.listBorderColor),Ae.listPadding&&(n["--persona-artifact-tab-list-padding"]=Ae.listPadding)}if(b!=null&&b.pane){let Ae=b.pane;if(Ae.toolbarBackground){let Ur=(co=Fs(e,Ae.toolbarBackground))!=null?co:Ae.toolbarBackground;n["--persona-artifact-toolbar-bg"]=Ur}}return n}var Bg={header:"Widget header bar",messages:"Message list area","user-message":"User message bubble","assistant-message":"Assistant message bubble",composer:"Footer / composer area",container:"Main widget container","artifact-pane":"Artifact sidebar","artifact-toolbar":"Artifact toolbar"};var ub={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"}}},Dg=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},Ma=()=>{var e;return typeof document!="undefined"&&document.documentElement.classList.contains("dark")||typeof window!="undefined"&&((e=window.matchMedia)!=null&&e.call(window,"(prefers-color-scheme: dark)").matches)?"dark":"light"},mb=e=>{var n;let t=(n=e==null?void 0:e.colorScheme)!=null?n:"light";return t==="light"?"light":t==="dark"?"dark":Ma()},Vl=e=>mb(e),gb=e=>_s(e),fb=e=>{var n;let t=_s(void 0,{validate:!1});return _s({...e,palette:{...t.palette,colors:{...ub.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors}}},{validate:!1})},$s=e=>{let t=Vl(e),n=Dg(e==null?void 0:e.theme),r=Dg(e==null?void 0:e.darkTheme);return t==="dark"?fb(Ea(n!=null?n:{},r!=null?r:{})):gb(n)},hb=e=>Ai(e),Ro=(e,t)=>{let n=$s(t),r=hb(n);for(let[o,s]of Object.entries(r))e.style.setProperty(o,s)},Si=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let n=new MutationObserver(()=>{e(Ma())});n.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>n.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let n=window.matchMedia("(prefers-color-scheme: dark)"),r=()=>e(Ma());n.addEventListener?(n.addEventListener("change",r),t.push(()=>n.removeEventListener("change",r))):n.addListener&&(n.addListener(r),t.push(()=>n.removeListener(r)))}return()=>{t.forEach(n=>n())}};var Ng=require("idiomorph"),Ti=(e,t,n={})=>{let{preserveTypingAnimation:r=!0}=n;Ng.Idiomorph.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(o,s){var a,i;if(o instanceof HTMLElement&&r){if(o.classList.contains("persona-animate-typing")||o.hasAttribute("data-preserve-runtime"))return!1;if(o.hasAttribute("data-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 Og=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Ei={index:-1,draft:""};function Fg(e){let{direction:t,history:n,currentValue:r,atStart:o,state:s}=e,a=s.index!==-1;if(n.length===0)return{handled:!1,state:s};if(t==="up"){if(!a&&!o)return{handled:!1,state:s};if(!a){let i=n.length-1;return{handled:!0,value:n[i],state:{index:i,draft:r}}}if(s.index>0){let i=s.index-1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,state:s}}if(!a)return{handled:!1,state:s};if(s.index<n.length-1){let i=s.index+1;return{handled:!0,value:n[i],state:{index:i,draft:s.draft}}}return{handled:!0,value:s.draft,state:{...Ei}}}function _g(e,t){var n,r,o,s,a,i,d,c,p,u,f,g,b,v,T,E,P,I,M,L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se,oe,ae,ie;return[e.id,e.role,(r=(n=e.content)==null?void 0:n.length)!=null?r:0,(s=(o=e.content)==null?void 0:o.slice(-32))!=null?s:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(a=e.variant)!=null?a:"",(d=(i=e.rawContent)==null?void 0:i.length)!=null?d:0,(p=(c=e.llmContent)==null?void 0:c.length)!=null?p:0,(f=(u=e.approval)==null?void 0:u.status)!=null?f:"",(b=(g=e.toolCall)==null?void 0:g.status)!=null?b:"",(T=(v=e.toolCall)==null?void 0:v.name)!=null?T:"",(I=(P=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:P.length)!=null?I:0,(R=(C=(L=(M=e.toolCall)==null?void 0:M.chunks)==null?void 0:L[e.toolCall.chunks.length-1])==null?void 0:C.slice(-32))!=null?R:"",typeof((U=e.toolCall)==null?void 0:U.args)=="string"?e.toolCall.args.length:(j=e.toolCall)!=null&&j.args?JSON.stringify(e.toolCall.args).length:0,(F=(O=(W=e.reasoning)==null?void 0:W.chunks)==null?void 0:O.length)!=null?F:0,(te=(pe=(Me=(ee=e.reasoning)==null?void 0:ee.chunks)==null?void 0:Me[e.reasoning.chunks.length-1])==null?void 0:pe.length)!=null?te:0,(Se=(re=(Ie=(Pe=e.reasoning)==null?void 0:Pe.chunks)==null?void 0:Ie[e.reasoning.chunks.length-1])==null?void 0:re.slice(-32))!=null?Se:"",(ae=(oe=e.contentParts)==null?void 0:oe.length)!=null?ae:0,(ie=e.stopReason)!=null?ie:"",t].join("\0")}function $g(){return new Map}function jg(e,t,n){let r=e.get(t);return r&&r.fingerprint===n?r.wrapper:null}function Ug(e,t,n,r){e.set(t,{fingerprint:n,wrapper:r})}function qg(e,t){for(let n of e.keys())t.has(n)||e.delete(n)}function Mi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function Nr(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function Wo(e,t){return Nr(e)-e.scrollTop<=t}function ki(e){let{following:t,currentScrollTop:n,lastScrollTop:r,nearBottom:o,userScrollThreshold:s,isAutoScrolling:a=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:d=!0,resumeRequiresDownwardScroll:c=!1}=e,p=n-r;return a||Math.abs(p)<s?{action:"none",delta:p,nextLastScrollTop:n}:!t&&o&&(!c||p>0)?{action:"resume",delta:p,nextLastScrollTop:n}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:n}:t&&d&&!o?{action:"pause",delta:p,nextLastScrollTop:n}:{action:"none",delta:p,nextLastScrollTop:n}}function Li(e){let{following:t,deltaY:n,nearBottom:r=!1,resumeWhenNearBottom:o=!1}=e;return t&&n<0?"pause":!t&&o&&n>0&&r?"resume":"none"}function zg(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function Vg(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),n=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:n}}function Kg(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var rn={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline",paused:"Connection lost\u2026",resuming:"Reconnecting\u2026"},vn=1e5,Ho=vn+1;var ka={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},yb=["pre","code","a","script","style"],Pi=e=>{var t,n,r,o,s;return{type:(t=e==null?void 0:e.type)!=null?t:ka.type,placeholder:(n=e==null?void 0:e.placeholder)!=null?n:ka.placeholder,speed:(r=e==null?void 0:e.speed)!=null?r:ka.speed,duration:(o=e==null?void 0:e.duration)!=null?o:ka.duration,buffer:(s=e==null?void 0:e.buffer)!=null?s:ka.buffer}},Jg=[{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"}],La=new Map;for(let e of Jg)La.set(e.name,e);var Xg=e=>{La.set(e.name,e)},Qg=e=>{Jg.some(t=>t.name===e)||La.delete(e)},Yg=()=>Array.from(La.keys()),js=(e,t)=>{var n,r;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(n=t[e])!=null?n:null:(r=La.get(e))!=null?r:null},Ii=(e,t,n,r,o)=>{if(!o)return e;if(n!=null&&n.bufferContent)return n.bufferContent(e,r);if(!e)return e;if(t==="word"){let s=e.search(/\s(?=\S*$)/);return s<0?"":e.slice(0,s)}if(t==="line"){let s=e.lastIndexOf(`
19
19
  `);return s<0?"":e.slice(0,s)}return e},bb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-char",o.id=`stream-c-${n}-${r}`,o.style.setProperty("--char-index",String(r)),o.textContent=t,o},xb=(e,t,n,r)=>{let o=e.createElement("span");return o.className="persona-stream-word",o.id=`stream-w-${n}-${r}`,o.style.setProperty("--word-index",String(r)),o.textContent=t,o},Kl=/\s/,vb=(e,t)=>{let n=e.parentNode;for(;n;){if(n.nodeType===1){let r=n;if(t.has(r.tagName.toLowerCase()))return!0}n=n.parentNode}return!1},wb=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=0;for(;i<s.length;)if(Kl.test(s[i])){let c=i;for(;c<s.length&&Kl.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&&!Kl.test(s[p]);)c.appendChild(bb(r,s[p],t,n.value)),n.value+=1,p+=1;a.appendChild(c),i=p}o.replaceChild(a,e)},Cb=(e,t,n)=>{var d;let r=e.ownerDocument,o=e.parentNode;if(!r||!o)return;let s=(d=e.nodeValue)!=null?d:"";if(!s)return;let a=r.createDocumentFragment(),i=s.split(/(\s+)/);for(let c of i)c&&(/^\s+$/.test(c)?a.appendChild(r.createTextNode(c)):(a.appendChild(xb(r,c,t,n.value)),n.value+=1));o.replaceChild(a,e)},Pa=(e,t,n,r)=>{var u,f;if(!e||typeof document=="undefined")return e;let o=document.createElement("div");o.innerHTML=e;let s=new Set(((u=r==null?void 0:r.skipTags)!=null?u:yb).map(g=>g.toLowerCase())),a=document.createTreeWalker(o,NodeFilter.SHOW_TEXT,null),i=[],d=a.nextNode();for(;d;)vb(d,s)||i.push(d),d=a.nextNode();let c={value:(f=r==null?void 0:r.startIndex)!=null?f:0},p=t==="char"?wb:Cb;for(let g of i)p(g,n,c);return o.innerHTML},Ri=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ia=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let n=e.createElement("div");return n.className="persona-stream-skeleton-line",t.appendChild(n),t},Gg=new WeakMap,Ab=(e,t)=>{var s;if(!e.styles)return;let n=Gg.get(t);if(n||(n=new Set,Gg.set(t,n)),n.has(e.name)){let a=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${a}"]`))return;n.delete(e.name)}n.add(e.name);let o=(t instanceof ShadowRoot?t.ownerDocument:(s=t.ownerDocument)!=null?s:document).createElement("style");o.setAttribute("data-persona-animation",e.name),o.textContent=e.styles,t.appendChild(o)},Gl=new WeakMap,Sb=(e,t)=>{if(!e.onAttach)return;let n=Gl.get(t);if(n||(n=new Map,Gl.set(t,n)),n.has(e.name))return;let r=e.onAttach(t);n.set(e.name,r)},Zg=e=>{let t=Gl.get(e);if(t){for(let n of t.values())typeof n=="function"&&n();t.clear()}},Wi=(e,t)=>{Ab(e,t),Sb(e,t)};function Jl(e,t=vn){let n=e.style.position,r=e.style.zIndex,o=e.style.isolation,s=getComputedStyle(e),a=s.position==="static"||s.position==="";return a&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{a&&(e.style.position=n),e.style.zIndex=r,e.style.isolation=o}}var Ra=0,Bo=null;function Xl(e=document){var n;if(Ra++,Ra===1){let r=e.body,s=((n=e.defaultView)!=null?n:window).scrollY||e.documentElement.scrollTop;Bo={originalOverflow:r.style.overflow,originalPosition:r.style.position,originalTop:r.style.top,originalWidth:r.style.width,scrollY:s},r.style.overflow="hidden",r.style.position="fixed",r.style.top=`-${s}px`,r.style.width="100%"}let t=!1;return()=>{var r;if(!t&&(t=!0,Ra=Math.max(0,Ra-1),Ra===0&&Bo)){let o=e.body,s=(r=e.defaultView)!=null?r:window;o.style.overflow=Bo.originalOverflow,o.style.position=Bo.originalPosition,o.style.top=Bo.originalTop,o.style.width=Bo.originalWidth,s.scrollTo(0,Bo.scrollY),Bo=null}}}var Wa={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},on=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="docked"},Do=e=>{var t,n;return((n=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?n:"floating")==="composer-bar"},Vn=e=>{var n,r,o,s,a,i;let t=(n=e==null?void 0:e.launcher)==null?void 0:n.dock;return{side:(r=t==null?void 0:t.side)!=null?r:Wa.side,width:(o=t==null?void 0:t.width)!=null?o:Wa.width,animate:(s=t==null?void 0:t.animate)!=null?s:Wa.animate,reveal:(a=t==null?void 0:t.reveal)!=null?a:Wa.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Wa.maxHeight}};var xr={"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 Tb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Hi=(e,t={})=>{var T,E,P,I,M,L;let{showClose:n=!0,wrapperClassName:r=Tb,buttonSize:o,iconSize:s="28px"}=t,a=(T=e==null?void 0:e.launcher)!=null?T:{},i=(E=o!=null?o:a.closeButtonSize)!=null?E:"32px",d=y("div",r),c=(P=a.closeButtonTooltipText)!=null?P:"Close chat",p=(I=a.closeButtonShowTooltip)!=null?I:!0,u=(M=a.closeButtonIconName)!=null?M:"x",f=(L=a.closeButtonIconText)!=null?L:"\xD7",g=!!(a.closeButtonBorderWidth||a.closeButtonBorderColor),b=Mt("button",{className:ma("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!a.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!g&&"persona-border-none",!a.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":c},style:{height:i,width:i,display:n?void 0:"none",color:a.closeButtonColor||kn.actionIconColor,backgroundColor:a.closeButtonBackgroundColor||void 0,border:g?`${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}}),v=he(u,s,"currentColor",1);if(v?(v.style.display="block",b.appendChild(v)):b.textContent=f,d.appendChild(b),p&&c){let C=null,R=()=>{if(C)return;let j=b.ownerDocument,W=j.body;if(!W)return;C=Dr(j,"div","persona-clear-chat-tooltip"),C.textContent=c;let O=Dr(j,"div");O.className="persona-clear-chat-tooltip-arrow",C.appendChild(O);let F=b.getBoundingClientRect();C.style.position="fixed",C.style.zIndex=String(Ho),C.style.left=`${F.left+F.width/2}px`,C.style.top=`${F.top-8}px`,C.style.transform="translate(-50%, -100%)",W.appendChild(C)},U=()=>{C&&C.parentNode&&(C.parentNode.removeChild(C),C=null)};d.addEventListener("mouseenter",R),d.addEventListener("mouseleave",U),b.addEventListener("focus",R),b.addEventListener("blur",U),d._cleanupTooltip=()=>{U(),d.removeEventListener("mouseenter",R),d.removeEventListener("mouseleave",U),b.removeEventListener("focus",R),b.removeEventListener("blur",U)}}return{button:b,wrapper:d}},Eb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Bi=(e,t={})=>{var C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie;let{wrapperClassName:n=Eb,buttonSize:r,iconSize:o="20px"}=t,a=(R=((C=e==null?void 0:e.launcher)!=null?C:{}).clearChat)!=null?R:{},i=(U=r!=null?r:a.size)!=null?U:"32px",d=(j=a.iconName)!=null?j:"refresh-cw",c=(W=a.iconColor)!=null?W:"",p=(O=a.backgroundColor)!=null?O:"",u=(F=a.borderWidth)!=null?F:"",f=(ee=a.borderColor)!=null?ee:"",g=(Me=a.borderRadius)!=null?Me:"",b=(pe=a.paddingX)!=null?pe:"",v=(te=a.paddingY)!=null?te:"",T=(Pe=a.tooltipText)!=null?Pe:"Clear chat",E=(Ie=a.showTooltip)!=null?Ie:!0,P=y("div",n),I=!!(u||f),M=Mt("button",{className:ma("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!I&&"persona-border-none",!g&&"persona-rounded-full"),attrs:{type:"button","aria-label":T},style:{height:i,width:i,color:c||kn.actionIconColor,backgroundColor:p||void 0,border:I?`${u||"0px"} solid ${f||"transparent"}`:void 0,borderRadius:g||void 0,paddingLeft:b||void 0,paddingRight:b||void 0,paddingTop:v||void 0,paddingBottom:v||void 0}}),L=he(d,o,"currentColor",1);if(L&&(L.style.display="block",M.appendChild(L)),P.appendChild(M),E&&T){let re=null,Se=()=>{if(re)return;let ae=M.ownerDocument,ie=ae.body;if(!ie)return;re=Dr(ae,"div","persona-clear-chat-tooltip"),re.textContent=T;let ye=Dr(ae,"div");ye.className="persona-clear-chat-tooltip-arrow",re.appendChild(ye);let je=M.getBoundingClientRect();re.style.position="fixed",re.style.zIndex=String(Ho),re.style.left=`${je.left+je.width/2}px`,re.style.top=`${je.top-8}px`,re.style.transform="translate(-50%, -100%)",ie.appendChild(re)},oe=()=>{re&&re.parentNode&&(re.parentNode.removeChild(re),re=null)};P.addEventListener("mouseenter",Se),P.addEventListener("mouseleave",oe),M.addEventListener("focus",Se),M.addEventListener("blur",oe),P._cleanupTooltip=()=>{oe(),P.removeEventListener("mouseenter",Se),P.removeEventListener("mouseleave",oe),M.removeEventListener("focus",Se),M.removeEventListener("blur",oe)}}return{button:M,wrapper:P}};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))"},Zr=e=>{var L,C,R,U,j,W,O,F,ee,Me,pe,te,Pe,Ie,re,Se;let{config:t,showClose:n=!0}=e,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=(L=t==null?void 0:t.launcher)!=null?L:{},s=(C=o.headerIconSize)!=null?C:"48px",a=(R=o.closeButtonPlacement)!=null?R:"inline",i=(U=o.headerIconHidden)!=null?U:!1,d=o.headerIconName,c=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:s,width:s,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(d){let oe=parseFloat(s)||24,ae=he(d,oe*.6,"currentColor",1);ae?c.replaceChildren(ae):c.textContent=(W=(j=t==null?void 0:t.launcher)==null?void 0:j.agentIconText)!=null?W:"\u{1F4AC}"}else if((O=t==null?void 0:t.launcher)!=null&&O.iconUrl){let oe=y("img");oe.src=t.launcher.iconUrl,oe.alt="",oe.className="persona-rounded-xl persona-object-cover",oe.style.height=s,oe.style.width=s,c.replaceChildren(oe)}else c.textContent=(ee=(F=t==null?void 0:t.launcher)==null?void 0:F.agentIconText)!=null?ee:"\u{1F4AC}";let p=y("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),u=Mt("span",{className:"persona-text-base persona-font-semibold",text:(pe=(Me=t==null?void 0:t.launcher)==null?void 0:Me.title)!=null?pe:"Chat Assistant",style:{color:kn.titleColor}}),f=Mt("span",{className:"persona-text-xs",text:(Pe=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Pe:"Here to help you get answers fast",style:{color:kn.subtitleColor}});p.append(u,f),i?r.append(p):r.append(c,p);let g=(Ie=o.clearChat)!=null?Ie:{},b=(re=g.enabled)!=null?re:!0,v=(Se=g.placement)!=null?Se:"inline",T=null,E=null;if(b){let ae=Bi(t,{wrapperClassName:v==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});T=ae.button,E=ae.wrapper,v==="top-right"&&(E.style.right="48px"),v==="inline"&&r.appendChild(E)}let P=a==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":b&&v==="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}=Hi(t,{showClose:n,wrapperClassName:P});return a!=="top-right"&&r.appendChild(M),{header:r,iconHolder:c,headerTitle:u,headerSubtitle:f,closeButton:I,closeButtonWrapper:M,clearChatButton:T,clearChatButtonWrapper:E}},cs=(e,t,n)=>{var a,i,d,c;let r=(a=n==null?void 0:n.launcher)!=null?a:{},o=(i=r.closeButtonPlacement)!=null?i:"inline",s=(c=(d=r.clearChat)==null?void 0:d.placement)!=null?c:"inline";e.appendChild(t.header),o==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&s==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function No(e){let{items:t,onSelect:n,anchor:r,position:o="bottom-left",portal:s}=e,a=y("div","persona-dropdown-menu persona-hidden");a.setAttribute("role","menu"),a.setAttribute("data-persona-theme-zone","dropdown"),s?(a.style.position="fixed",a.style.zIndex=String(Ho)):(a.style.position="absolute",a.style.top="100%",a.style.marginTop="4px",o==="bottom-right"?a.style.right="0":a.style.left="0");for(let g of t){if(g.dividerBefore){let T=document.createElement("hr");a.appendChild(T)}let b=document.createElement("button");if(b.type="button",b.setAttribute("role","menuitem"),b.setAttribute("data-dropdown-item-id",g.id),g.destructive&&b.setAttribute("data-destructive",""),g.icon){let T=he(g.icon,16,"currentColor",1.5);T&&b.appendChild(T)}let v=document.createElement("span");v.textContent=g.label,b.appendChild(v),b.addEventListener("click",T=>{T.stopPropagation(),p(),n(g.id)}),a.appendChild(b)}let i=null;function d(){if(!s)return;let g=r.getBoundingClientRect();a.style.top=`${g.bottom+4}px`,o==="bottom-right"?(a.style.right=`${window.innerWidth-g.right}px`,a.style.left="auto"):(a.style.left=`${g.left}px`,a.style.right="auto")}function c(){d(),a.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let g=b=>{!a.contains(b.target)&&!r.contains(b.target)&&p()};document.addEventListener("click",g,!0),i=()=>document.removeEventListener("click",g,!0)})}function p(){a.classList.add("persona-hidden"),i==null||i(),i=null}function u(){a.classList.contains("persona-hidden")?c():p()}function f(){p(),a.remove()}return s&&s.appendChild(a),{element:a,show:c,hide:p,toggle:u,destroy:f}}function Gt(e){let{icon:t,label:n,size:r,strokeWidth:o,className:s,onClick:a,aria:i}=e,d=y("button","persona-icon-btn"+(s?" "+s:""));d.type="button",d.setAttribute("aria-label",n),d.title=n;let c=he(t,r!=null?r:16,"currentColor",o!=null?o:2);if(c&&d.appendChild(c),a&&d.addEventListener("click",a),i)for(let[p,u]of Object.entries(i))d.setAttribute(p,u);return d}function Ha(e){let{icon:t,label:n,variant:r="default",size:o="sm",iconSize:s,className:a,onClick:i,aria:d}=e,c="persona-label-btn";r!=="default"&&(c+=" persona-label-btn--"+r),c+=" persona-label-btn--"+o,a&&(c+=" "+a);let p=y("button",c);if(p.type="button",p.setAttribute("aria-label",n),t){let f=he(t,s!=null?s:14,"currentColor",2);f&&p.appendChild(f)}let u=y("span");if(u.textContent=n,p.appendChild(u),i&&p.addEventListener("click",i),d)for(let[f,g]of Object.entries(d))p.setAttribute(f,g);return p}function Ba(e){let{items:t,selectedId:n,onSelect:r,className:o}=e,s=y("div","persona-toggle-group"+(o?" "+o:""));s.setAttribute("role","group");let a=n,i=[];function d(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===a?"true":"false")}for(let p of t){let u;p.icon?u=Gt({icon:p.icon,label:p.label,onClick:()=>{a=p.id,d(),r(p.id)}}):(u=y("button","persona-icon-btn"),u.type="button",u.setAttribute("aria-label",p.label),u.title=p.label,u.textContent=p.label,u.addEventListener("click",()=>{a=p.id,d(),r(p.id)})),u.setAttribute("aria-pressed",p.id===a?"true":"false"),i.push({id:p.id,btn:u}),s.appendChild(u)}function c(p){a=p,d()}return{element:s,setSelected:c}}function Di(e){var g,b;let{label:t,icon:n="chevron-down",menuItems:r,onSelect:o,position:s="bottom-left",portal:a,className:i,hover:d}=e,c=y("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",t);let p=y("span","persona-combo-btn-label");p.textContent=t,c.appendChild(p);let u=he(n,14,"currentColor",2);u&&(u.style.marginLeft="4px",u.style.opacity="0.6",c.appendChild(u)),d&&(c.style.borderRadius=(g=d.borderRadius)!=null?g:"10px",c.style.padding=(b=d.padding)!=null?b:"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 v,T;c.style.backgroundColor=(v=d.background)!=null?v:"",c.style.borderColor=(T=d.border)!=null?T:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}));let f=No({items:r,onSelect:v=>{c.setAttribute("aria-expanded","false"),o(v)},anchor:c,position:s,portal:a});return a||c.appendChild(f.element),c.addEventListener("click",v=>{v.stopPropagation();let T=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",T?"false":"true"),f.toggle()}),c.addEventListener("keydown",v=>{(v.key==="Enter"||v.key===" ")&&(v.preventDefault(),c.click())}),{element:c,setLabel:v=>{p.textContent=v,c.setAttribute("aria-label",v)},open:()=>{c.setAttribute("aria-expanded","true"),f.show()},close:()=>{c.setAttribute("aria-expanded","false"),f.hide()},toggle:()=>{let v=!f.element.classList.contains("persona-hidden");c.setAttribute("aria-expanded",v?"false":"true"),f.toggle()},destroy:()=>{f.destroy(),c.remove()}}}var Ql=e=>{var r;let t=Zr({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),n=(r=e.layoutHeaderConfig)==null?void 0:r.onTitleClick;if(n){let o=t.headerTitle.parentElement;o&&(o.style.cursor="pointer",o.setAttribute("role","button"),o.setAttribute("tabindex","0"),o.addEventListener("click",()=>n()),o.addEventListener("keydown",s=>{(s.key==="Enter"||s.key===" ")&&(s.preventDefault(),n())}))}return t};function Mb(e,t,n){var r,o,s;if(t!=null&&t.length)for(let a of t){let i=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(o=(r=a.ariaLabel)!=null?r:a.label)!=null?o:a.id),a.icon){let d=he(a.icon,14,"currentColor",2);d&&i.appendChild(d)}else a.label&&(i.textContent=a.label);if((s=a.menuItems)!=null&&s.length){let d=y("div","persona-relative");d.appendChild(i);let c=No({items:a.menuItems,onSelect:p=>n==null?void 0:n(p),anchor:d,position:"bottom-left"});d.appendChild(c.element),i.addEventListener("click",p=>{p.stopPropagation(),c.toggle()}),e.appendChild(d)}else i.addEventListener("click",()=>n==null?void 0:n(a.id)),e.appendChild(i)}}var Yl=e=>{var P,I,M,L,C,R,U,j,W;let{config:t,showClose:n=!0,onClose:r,layoutHeaderConfig:o,onHeaderAction:s}=e,a=(P=t==null?void 0:t.launcher)!=null?P:{},i=y("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let d=o==null?void 0:o.titleMenu,c,p;if(d)c=Di({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=y("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=y("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=kn.titleColor,p.textContent=(L=a.title)!=null?L:"Chat Assistant",c.appendChild(p),Mb(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",ee=>{ee.target.closest("button")||F()}),c.addEventListener("keydown",ee=>{(ee.key==="Enter"||ee.key===" ")&&(ee.preventDefault(),F())})}let O=o==null?void 0:o.titleRowHover;O&&(c.style.borderRadius=(R=O.borderRadius)!=null?R:"10px",c.style.padding=(U=O.padding)!=null?U:"6px 4px 6px 12px",c.style.margin="-6px 0 -6px -12px",c.style.border="1px solid transparent",c.style.transition="background-color 0.15s ease, border-color 0.15s ease",c.style.width="fit-content",c.style.flex="none",c.addEventListener("mouseenter",()=>{var F,ee;c.style.backgroundColor=(F=O.background)!=null?F:"",c.style.borderColor=(ee=O.border)!=null?ee:""}),c.addEventListener("mouseleave",()=>{c.style.backgroundColor="",c.style.borderColor="transparent"}))}i.appendChild(c);let u=(j=a.closeButtonSize)!=null?j:"32px",f=y("div",""),g=y("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");g.style.height=u,g.style.width=u,g.type="button",g.setAttribute("aria-label","Close chat"),g.style.display=n?"":"none",g.style.color=a.closeButtonColor||kn.actionIconColor;let b=(W=a.closeButtonIconName)!=null?W:"x",v=he(b,"28px","currentColor",1);v?g.appendChild(v):g.textContent="\xD7",r&&g.addEventListener("click",r),f.appendChild(g),i.appendChild(f);let T=y("div");T.style.display="none";let E=y("span");return E.style.display="none",{header:i,iconHolder:T,headerTitle:p,headerSubtitle:E,closeButton:g,closeButtonWrapper:f,clearChatButton:null,clearChatButtonWrapper:null}},Ni={default:Ql,minimal:Yl},Zl=e=>{var t;return(t=Ni[e])!=null?t:Ni.default},Us=(e,t,n)=>{var a,i,d;if(t!=null&&t.render){let c=t.render({config:e,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=y("div");p.style.display="none";let u=y("span"),f=y("span"),g=y("button");g.style.display="none";let b=y("div");return b.style.display="none",{header:c,iconHolder:p,headerTitle:u,headerSubtitle:f,closeButton:g,closeButtonWrapper:b,clearChatButton:null,clearChatButtonWrapper:null}}let r=(a=t==null?void 0:t.layout)!=null?a:"default",s=Zl(r)({config:e,showClose:(d=(i=t==null?void 0:t.showCloseButton)!=null?i:n==null?void 0:n.showClose)!=null?d:!0,onClose:n==null?void 0:n.onClose,onClearChat:n==null?void 0:n.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(s.iconHolder.style.display="none"),t.showTitle===!1&&(s.headerTitle.style.display="none"),t.showSubtitle===!1&&(s.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(s.closeButton.style.display="none"),t.showClearChat===!1&&s.clearChatButtonWrapper&&(s.clearChatButtonWrapper.style.display="none")),s};var Oi=e=>{var a,i;let t=y("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(a=e==null?void 0:e.copy)==null?void 0:a.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let n=3,r=20;t.style.maxHeight=`${n*r}px`,t.style.overflowY="auto";let o=()=>{let d=parseFloat(t.style.maxHeight);return Number.isFinite(d)&&d>0?d:n*r},s=()=>{t.addEventListener("input",()=>{t.style.height="auto";let d=Math.min(t.scrollHeight,o());t.style.height=`${d}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:s}},Fi=e=>{var L,C,R,U,j,W,O,F,ee,Me,pe,te;let t=(L=e==null?void 0:e.sendButton)!=null?L:{},n=(C=t.useIcon)!=null?C:!1,r=(R=t.iconText)!=null?R:"\u2191",o=t.iconName,s=(U=t.stopIconName)!=null?U:"square",a=(j=t.tooltipText)!=null?j:"Send message",i=(W=t.stopTooltipText)!=null?W:"Stop generating",d=(F=(O=e==null?void 0:e.copy)==null?void 0:O.sendButtonLabel)!=null?F:"Send",c=(Me=(ee=e==null?void 0:e.copy)==null?void 0:ee.stopButtonLabel)!=null?Me:"Stop",p=(pe=t.showTooltip)!=null?pe:!1,u=(te=t.size)!=null?te:"40px",f=t.backgroundColor,g=t.textColor,b=y("div","persona-send-button-wrapper"),v=Mt("button",{className:ma("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",n?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",n&&!f&&"persona-bg-persona-primary",!n&&!g&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:n?u:void 0,height:n?u:void 0,minWidth:n?u:void 0,minHeight:n?u:void 0,fontSize:n?"18px":void 0,lineHeight:n?"1":void 0,color:n?g||"var(--persona-button-primary-fg, #ffffff)":g||void 0,backgroundColor:n&&f||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),T=null,E=null;if(n){let Pe=parseFloat(u)||24,Ie=(g==null?void 0:g.trim())||"currentColor";o?(T=he(o,Pe,Ie,2),T?v.appendChild(T):v.textContent=r):v.textContent=r,E=he(s,Pe,Ie,2)}else v.textContent=d;let P=null;p&&a&&(P=y("div","persona-send-button-tooltip"),P.textContent=a,b.appendChild(P)),v.setAttribute("aria-label",a),b.appendChild(v);let I="send";return{button:v,wrapper:b,setMode:Pe=>{if(Pe===I)return;I=Pe;let Ie=Pe==="stop"?i:a;if(v.setAttribute("aria-label",Ie),P&&(P.textContent=Ie),n){if(T&&E){let re=Pe==="stop"?E:T;v.replaceChildren(re)}}else v.textContent=Pe==="stop"?c:d}}},_i=e=>{var P,I,M,L,C,R,U,j,W,O,F,ee;let t=(P=e==null?void 0:e.voiceRecognition)!=null?P:{};if(!(t.enabled===!0))return null;let r=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),o=((I=t.provider)==null?void 0:I.type)==="runtype";if(!(r||o))return null;let a=(L=(M=e==null?void 0:e.sendButton)==null?void 0:M.size)!=null?L:"40px",i=(C=t.iconName)!=null?C:"mic",d=(R=t.iconSize)!=null?R:a,c=parseFloat(d)||24,p=(j=t.backgroundColor)!=null?j:(U=e==null?void 0:e.sendButton)==null?void 0:U.backgroundColor,u=(O=t.iconColor)!=null?O:(W=e==null?void 0:e.sendButton)==null?void 0:W.textColor,f=y("div","persona-send-button-wrapper"),g=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:u||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),v=he(i,c,u||"currentColor",1.5);v?g.appendChild(v):g.textContent="\u{1F3A4}",f.appendChild(g);let T=(F=t.tooltipText)!=null?F:"Start voice recognition";if(((ee=t.showTooltip)!=null?ee:!1)&&T){let Me=y("div","persona-send-button-tooltip");Me.textContent=T,f.appendChild(Me)}return{button:g,wrapper:f}},$i=e=>{var b,v,T,E,P,I,M,L;let t=(b=e==null?void 0:e.attachments)!=null?b:{};if(t.enabled!==!0)return null;let n=(T=(v=e==null?void 0:e.sendButton)==null?void 0:v.size)!=null?T:"40px",r=y("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");r.setAttribute("data-persona-composer-attachment-previews",""),r.style.display="none";let o=y("input");o.type="file",o.setAttribute("data-persona-composer-attachment-input",""),o.accept=((E=t.allowedTypes)!=null?E:Yr).join(","),o.multiple=((P=t.maxFiles)!=null?P:4)>1,o.style.display="none",o.setAttribute("aria-label","Attach files");let s=(I=t.buttonIconName)!=null?I:"paperclip",a=n,i=parseFloat(a)||40,d=Math.round(i*.6),c=y("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=t.buttonTooltipText)!=null?M:"Attach file"},style:{width:a,height:a,minWidth:a,minHeight:a,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let u=he(s,d,"currentColor",1.5);u?p.appendChild(u):p.textContent="\u{1F4CE}",p.addEventListener("click",C=>{C.preventDefault(),o.click()}),c.appendChild(p);let f=(L=t.buttonTooltipText)!=null?L:"Attach file",g=y("div","persona-send-button-tooltip");return g.textContent=f,c.appendChild(g),{button:p,wrapper:c,input:o,previewsContainer:r}},ji=e=>{var a,i,d;let t=(a=e==null?void 0:e.statusIndicator)!=null?a:{},n=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",r=y("div",`persona-mt-2 ${n} persona-text-xs persona-text-persona-muted`);r.setAttribute("data-persona-composer-status","");let o=(i=t.visible)!=null?i:!0;r.style.display=o?"":"none";let s=(d=t.idleText)!=null?d:"Online";if(t.idleLink){let c=y("a");c.href=t.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},Ui=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var qs=e=>{var b,v,T,E,P,I;let{config:t}=e,n=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=Ui(),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}=Oi(t);a();let i=Fi(t),d=_i(t),c=$i(t),p=ji(t);c&&(c.previewsContainer.style.gap="8px",o.append(c.previewsContainer,c.input)),o.append(s);let u=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),f=y("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),g=y("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return c&&f.append(c.wrapper),d&&g.append(d.wrapper),g.append(i.wrapper),u.append(f,g),o.append(u),o.addEventListener("click",M=>{M.target!==i.button&&M.target!==i.wrapper&&M.target!==(d==null?void 0:d.button)&&M.target!==(d==null?void 0:d.wrapper)&&M.target!==(c==null?void 0:c.button)&&M.target!==(c==null?void 0:c.wrapper)&&s.focus()}),n.append(r,o,p),{footer:n,suggestions:r,composerForm:o,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:p,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:u,leftActions:f,rightActions:g,setSendButtonMode:i.setMode}};var ef=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=y("span","persona-pill-peek__icon"),n=he("message-square",16,"currentColor",1.5);n&&t.appendChild(n);let r=y("span","persona-pill-peek__text"),o=y("span","persona-pill-peek__caret"),s=he("chevron-up",16,"currentColor",1.5);return s&&o.appendChild(s),e.append(t,r,o),{root:e,textNode:r}},tf=e=>{var b,v,T,E,P,I;let{config:t}=e,n=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),r=Ui();r.style.display="none";let o=ji(t);o.style.display="none";let{textarea:s,attachAutoResize:a}=Oi(t);s.style.maxHeight="100px",a();let i=Fi(t),d=_i(t),c=$i(t);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"}}),u=y("div","persona-widget-composer__left-actions persona-pill-composer__left");c&&u.append(c.wrapper);let f=y("div","persona-widget-composer__right-actions persona-pill-composer__right");d&&f.append(d.wrapper),f.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(u,s,f),c&&n.append(c.previewsContainer),n.append(p,r,o);let g=p;return{footer:n,suggestions:r,composerForm:p,textarea:s,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(b=d==null?void 0:d.button)!=null?b:null,micButtonWrapper:(v=d==null?void 0:d.wrapper)!=null?v:null,statusText:o,attachmentButton:(T=c==null?void 0:c.button)!=null?T:null,attachmentButtonWrapper:(E=c==null?void 0:c.wrapper)!=null?E:null,attachmentInput:(P=c==null?void 0:c.input)!=null?P:null,attachmentPreviewsContainer:(I=c==null?void 0:c.previewsContainer)!=null?I:null,actionsRow:g,leftActions:u,rightActions:f,setSendButtonMode:i.setMode}};var nf=e=>{var p,u,f,g,b,v,T,E,P,I,M,L,C,R,U,j,W;let t=(u=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?u:!0,n=on(e);if(Do(e)){let O=(g=(f=e==null?void 0:e.launcher)==null?void 0:f.composerBar)!=null?g:{},F=y("div","persona-widget-wrapper persona-fixed persona-transition");F.setAttribute("data-persona-composer-bar",""),F.dataset.state="collapsed",F.dataset.expandedSize=(b=O.expandedSize)!=null?b:"anchored",F.style.zIndex=String((T=(v=e==null?void 0:e.launcher)==null?void 0:v.zIndex)!=null?T:vn);let ee=y("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");ee.style.width="100%",F.appendChild(ee);let Me=y("div","persona-widget-pill-root");return Me.setAttribute("data-persona-composer-bar",""),Me.dataset.state="collapsed",Me.dataset.expandedSize=(E=O.expandedSize)!=null?E:"anchored",Me.style.zIndex=String((I=(P=e==null?void 0:e.launcher)==null?void 0:P.zIndex)!=null?I:vn),{wrapper:F,panel:ee,pillRoot:Me}}if(n){let O=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),F=y("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return O.appendChild(F),{wrapper:O,panel:F}}if(!t){let O=y("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),F=y("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),ee=(L=(M=e==null?void 0:e.launcher)==null?void 0:M.width)!=null?L:"100%";return O.style.width=ee,F.style.width="100%",O.appendChild(F),{wrapper:O,panel:F}}let o=(C=e==null?void 0:e.launcher)!=null?C:{},s=o.position&&xr[o.position]?xr[o.position]:xr["bottom-right"],a=y("div",`persona-widget-wrapper persona-fixed ${s} persona-transition`);a.style.zIndex=String((U=(R=e==null?void 0:e.launcher)==null?void 0:R.zIndex)!=null?U:vn);let i=y("div","persona-widget-panel persona-relative persona-min-h-[320px]"),d=(W=(j=e==null?void 0:e.launcher)==null?void 0:j.width)!=null?W:e==null?void 0:e.launcherWidth,c=d!=null?d:zn;return i.style.width=c,i.style.maxWidth=c,a.appendChild(i),{wrapper:a,panel:i}},kb=(e,t)=>{var M,L,C,R,U,j,W,O,F;let n=y("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");n.setAttribute("data-persona-theme-zone","container");let{button:r,wrapper:o}=Hi(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});o.style.position="absolute",o.style.top="8px",o.style.right="8px",o.style.zIndex="10";let s=(C=(L=(M=e==null?void 0:e.launcher)==null?void 0:M.clearChat)==null?void 0:L.enabled)!=null?C:!0,a=null,i=null;if(s){let ee=Bi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});a=ee.button,i=ee.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:(U=(R=e==null?void 0:e.copy)==null?void 0:R.welcomeTitle)!=null?U:"Hello \u{1F44B}"}),u=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(W=(j=e==null?void 0:e.copy)==null?void 0:j.welcomeSubtitle)!=null?W:"Ask anything about your account or products."}),f=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,u),g=y("div","persona-flex persona-flex-col persona-gap-3"),b=(O=e==null?void 0:e.layout)==null?void 0:O.contentMaxWidth;b&&(g.style.maxWidth=b,g.style.marginLeft="auto",g.style.marginRight="auto",g.style.width="100%"),((F=e==null?void 0:e.copy)==null?void 0:F.showWelcomeCard)!==!1||(f.style.display="none",c.classList.remove("persona-gap-6"),c.classList.add("persona-gap-3")),c.append(f,g);let T=Mt("div",{className:"persona-composer-overlay persona-pointer-events-none",attrs:{"data-persona-composer-overlay":""},style:{position:"absolute",left:"0",right:"0",bottom:"0",zIndex:"20"}}),E=tf({config:e}),{root:P,textNode:I}=ef();return n.append(d,o,c,T),i&&n.appendChild(i),{container:n,body:c,messagesWrapper:g,composerOverlay:T,suggestions:E.suggestions,textarea:E.textarea,sendButton:E.sendButton,sendButtonWrapper:E.sendButtonWrapper,micButton:E.micButton,micButtonWrapper:E.micButtonWrapper,composerForm:E.composerForm,statusText:E.statusText,introTitle:p,introSubtitle:u,closeButton:r,closeButtonWrapper:o,clearChatButton:a,clearChatButtonWrapper:i,iconHolder:y("span"),headerTitle:y("span"),headerSubtitle:y("span"),header:d,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:P,peekTextNode:I}},rf=(e,t=!0)=>{var T,E,P,I,M,L,C,R,U;if(Do(e))return kb(e,t);let n=Mt("div",{className:"persona-widget-container persona-flex persona-h-full persona-w-full persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary persona-bg-persona-surface persona-rounded-2xl persona-overflow-hidden persona-border persona-border-persona-border",attrs:{"data-persona-theme-zone":"container"}}),r=(T=e==null?void 0:e.layout)==null?void 0:T.header,o=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,s=r?Us(e,r,{showClose:t}):Zr({config:e,showClose:t}),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=(P=e==null?void 0:e.copy)==null?void 0:P.welcomeTitle)!=null?I:"Hello \u{1F44B}"}),d=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(L=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeSubtitle)!=null?L:"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:on(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,d),p=y("div","persona-flex persona-flex-col persona-gap-3"),u=(C=e==null?void 0:e.layout)==null?void 0:C.contentMaxWidth;u&&(p.style.maxWidth=u,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((R=e==null?void 0:e.copy)==null?void 0:R.showWelcomeCard)!==!1||(c.style.display="none",a.classList.remove("persona-gap-6"),a.classList.add("persona-gap-3")),a.append(c,p);let g=qs({config:e}),b=((U=e==null?void 0:e.layout)==null?void 0:U.showFooter)!==!1;o?cs(n,s,e):(s.header.style.display="none",cs(n,s,e)),n.append(a);let v=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 b||(g.footer.style.display="none"),n.append(g.footer),n.append(v),{container:n,body:a,messagesWrapper:p,composerOverlay:v,suggestions:g.suggestions,textarea:g.textarea,sendButton:g.sendButton,sendButtonWrapper:g.sendButtonWrapper,micButton:g.micButton,micButtonWrapper:g.micButtonWrapper,composerForm:g.composerForm,statusText:g.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:g.footer,attachmentButton:g.attachmentButton,attachmentButtonWrapper:g.attachmentButtonWrapper,attachmentInput:g.attachmentInput,attachmentPreviewsContainer:g.attachmentPreviewsContainer,actionsRow:g.actionsRow,leftActions:g.leftActions,rightActions:g.rightActions,setSendButtonMode:g.setSendButtonMode}};var ec=(e,t)=>{let n=y("button");n.type="button",n.innerHTML=`
20
20
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
21
21
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />