@runtypelabs/persona 4.3.0 → 4.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -9,7 +9,7 @@ ${t}`:"")+(e.description?`
9
9
  ${e.description}`:"");return window.confirm(r)},Ly=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)}},Py=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Ry=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var Iy="agent_",Wy="flow_";function yg(e){return e.startsWith(Iy)?{kind:"agentId",agentId:e}:e.startsWith(Wy)?{kind:"flowId",flowId:e}:null}function bg(e,t){let r=e.trim();if(!r)throw new Error("[Persona] `target` is empty.");let o=r.indexOf(":");if(o>0){let s=r.slice(0,o),i=r.slice(o+1);if(s==="runtype"){let l=yg(i);if(l)return l;throw new Error(`[Persona] target "runtype:${i}" is not a valid Runtype agent_/flow_ id.`)}let c=t==null?void 0:t[s];if(!c)throw new Error(`[Persona] No target provider registered for "${s}". Add a \`targetProviders.${s}\` resolver, or use a Runtype agent_/flow_ id.`);return{kind:"payload",payload:c(i).payload}}let n=yg(r);if(n)return n;let a=t==null?void 0:t.default;if(a)return{kind:"payload",payload:a(r).payload};throw new Error(`[Persona] target "${r}" has no provider prefix and is not a Runtype agent_/flow_ id. Use "<provider>:${r}", a Runtype TypeID, or register a \`targetProviders.default\` resolver.`)}var bn=Sa(Ys(),1);var w=(e,t)=>{let r=document.createElement(e);return t&&(r.className=t),r},No=(e,t,r)=>{let o=e.createElement(t);return r&&(o.className=r),o};var Mt=(e,t={},...r)=>{let o=document.createElement(e);if(t.className&&(o.className=t.className),t.text!==void 0&&(o.textContent=t.text),t.attrs)for(let[a,s]of Object.entries(t.attrs))o.setAttribute(a,s);if(t.style){let a=o.style,s=t.style;for(let i of Object.keys(s)){let c=s[i];c!=null&&(a[i]=c)}}let n=r.filter(a=>a!=null);return n.length>0&&o.append(...n),o},ss=(...e)=>e.filter(Boolean).join(" ");var ls="ask_user_question",is=8,Ea="data-persona-ask-sheet-for",Ny="Other",Oy="Other\u2026",Cg="Type your own answer here",Sg="Send",_y="Next",Uy="Back",qy="Submit all",Vy="Skip",zy=3,Ll="data-ask-current-index",Pl="data-ask-question-count",Ag="data-ask-answers",Rl="data-ask-grouped",Mg="data-ask-layout",$y=e=>e.layout==="pills"?"pills":"rows",jy=e=>e.getAttribute(Mg)==="pills"?"pills":"rows",wg=!1,Tg=e=>e.replace(/["\\]/g,"\\$&"),Qo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===ls,Zs=e=>{var t,r;return(r=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?r:{}},Yo=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let r=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:r};let o=t.chunks;if(!o||o.length===0)return{payload:null,complete:r};try{let n=o.join(""),a=(0,bn.parse)(n,bn.STR|bn.OBJ|bn.ARR);if(a&&typeof a=="object")return{payload:a,complete:r}}catch{}return{payload:null,complete:r}},ds=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>is&&!wg&&(wg=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${is}.`)),t.slice(0,is)},Gy=e=>{var t;return(t=ds(e)[0])!=null?t:null},Ky=(e,t)=>{var r;return(r=ds(e)[t])!=null?r:null},Eg=(e,t)=>{let r=t.styles;r&&(r.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",r.sheetBackground),r.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",r.sheetBorder),r.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",r.sheetShadow),r.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",r.pillBackground),r.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",r.pillBackgroundSelected),r.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",r.pillTextColor),r.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",r.pillTextColorSelected),r.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",r.pillBorderRadius),r.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",r.customInputBackground))},kg=(e,t,r)=>{if(e!=="rows")return null;let o=w("span","persona-ask-row-affordance");if(o.setAttribute("aria-hidden","true"),t){let n=w("span","persona-ask-row-check");o.appendChild(n)}else{let n=w("span","persona-ask-row-badge");n.textContent=String(r+1),o.appendChild(n)}return o},Xy=(e,t,r,o)=>{let a=w("button",r==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(a.type="button",a.setAttribute("role",o?"checkbox":"button"),a.setAttribute("aria-pressed","false"),a.setAttribute("data-ask-user-action","pick"),a.setAttribute("data-option-index",String(t)),a.setAttribute("data-option-label",e.label),r==="rows"){let s=w("span","persona-ask-row-content"),i=w("span","persona-ask-row-label");if(i.textContent=e.label,s.appendChild(i),e.description){let l=w("span","persona-ask-row-description");l.textContent=e.description,s.appendChild(l)}a.appendChild(s);let c=kg(r,o,t);c&&a.appendChild(c)}else a.textContent=e.label,e.description&&(a.title=e.description);return a},Jy=e=>{let r=w("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return r.setAttribute("aria-hidden","true"),r},Qy=(e,t,r,o)=>{var p,f,u;let a=w("div",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");a.setAttribute("role","group"),a.setAttribute("data-ask-pill-list","true");let s=!!(e!=null&&e.multiSelect),c=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(m=>m&&typeof m.label=="string"&&m.label.length>0);if(c.length===0&&!r){for(let m=0;m<zy;m++)a.appendChild(Jy(o));return a}if(c.forEach((m,x)=>{a.appendChild(Xy(m,x,o,s))}),(e==null?void 0:e.allowFreeText)!==!1){let m=o==="rows"?Ny:Oy;if(o==="rows"){let x=w("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");x.setAttribute("data-ask-user-action","focus-free-text"),x.setAttribute("data-option-index",String(c.length)),x.setAttribute("data-ask-other-row","true");let b=w("span","persona-ask-row-content"),L=document.createElement("input");L.type="text",L.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",L.placeholder=(p=t.freeTextPlaceholder)!=null?p:Cg,L.setAttribute("data-ask-free-text-input","true"),L.setAttribute("aria-label",(f=t.freeTextLabel)!=null?f:m),b.appendChild(L),x.appendChild(b);let E=kg(o,s,c.length);E&&x.appendChild(E),a.appendChild(x)}else{let x=w("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");x.type="button",x.setAttribute("data-ask-user-action","open-free-text"),x.textContent=(u=t.freeTextLabel)!=null?u:m,a.appendChild(x)}}return a},Lg=(e,t)=>{var a,s;let o=w("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");o.setAttribute("data-ask-free-text-row","true");let n=document.createElement("input");if(n.type="text",n.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",n.placeholder=(a=e.freeTextPlaceholder)!=null?a:Cg,n.setAttribute("data-ask-free-text-input","true"),o.appendChild(n),t!=="rows"){let i=w("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(s=e.submitLabel)!=null?s:Sg,i.setAttribute("data-ask-user-action","submit-free-text"),o.appendChild(i)}return o},Yy=e=>{var o;let t=w("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let r=w("button","persona-ask-multi-submit persona-pointer-events-auto");return r.type="button",r.textContent=(o=e.submitLabel)!=null?o:Sg,r.setAttribute("data-ask-user-action","submit-multi"),r.disabled=!0,t.appendChild(r),t},Zy=(e,t,r)=>{var l,p,f,u;let o=w("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");o.setAttribute("data-ask-nav-row","true");let n=w("button","persona-ask-nav-back persona-pointer-events-auto");n.type="button",n.textContent=(l=r.backLabel)!=null?l:Uy,n.setAttribute("data-ask-user-action","back"),n.disabled=e===0,o.appendChild(n);let a=w("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),s=w("button","persona-ask-nav-skip persona-pointer-events-auto");s.type="button",s.textContent=(p=r.skipLabel)!=null?p:Vy,s.setAttribute("data-ask-user-action","skip"),a.appendChild(s);let i=w("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let c=e===t-1;return i.textContent=c?(f=r.submitAllLabel)!=null?f:qy:(u=r.nextLabel)!=null?u:_y,i.setAttribute("data-ask-user-action",c?"submit-all":"next"),i.disabled=!0,a.appendChild(i),o.appendChild(a),o},Kn=e=>{let t=e.getAttribute(Ag);if(!t)return{};try{let r=JSON.parse(t);return r&&typeof r=="object"?r:{}}catch{return{}}},Pg=(e,t)=>{e.setAttribute(Ag,JSON.stringify(t))},co=e=>{var r;let t=Number((r=e.getAttribute(Ll))!=null?r:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},eb=(e,t)=>{e.setAttribute(Ll,String(Math.max(0,Math.floor(t))))},ka=e=>{var r;let t=Number((r=e.getAttribute(Pl))!=null?r:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vn=e=>e.getAttribute(Rl)==="true",tb=(e,t)=>{var n;let r=(n=e.agentMetadata)==null?void 0:n.askUserQuestionAnswers;if(!r||typeof r!="object")return{};let o={};return t.forEach((a,s)=>{let i=typeof(a==null?void 0:a.question)=="string"?a.question:"";if(i&&Object.prototype.hasOwnProperty.call(r,i)){let c=r[i];(typeof c=="string"||Array.isArray(c))&&(o[s]=c)}}),o},rb=(e,t)=>{var o;let r=(o=e.agentMetadata)==null?void 0:o.askUserQuestionIndex;return typeof r!="number"||!Number.isFinite(r)?0:Math.max(0,Math.min(t-1,Math.floor(r)))},ei=(e,t)=>{let{payload:r}=Yo(t),o=ds(r),n=Kn(e),a={},s=new Set;return o.forEach((i,c)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(s.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),s.add(l),Object.prototype.hasOwnProperty.call(n,c)&&(a[l]=n[c]))}),a},Rg=e=>{let t=Kn(e),r=co(e),o=t[r],n=new Set;typeof o=="string"?n.add(o):Array.isArray(o)&&o.forEach(c=>n.add(c));let a=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');a.forEach(c=>{var f;let l=(f=c.getAttribute("data-option-label"))!=null?f:"",p=n.has(l);c.setAttribute("aria-pressed",p?"true":"false"),c.classList.toggle("persona-ask-pill-selected",p)});let s=new Set(Array.from(a).map(c=>{var l;return(l=c.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof o=="string"&&o.length>0&&!s.has(o)){i.value=o;let c=i.closest('[data-ask-free-text-row="true"]');c==null||c.classList.remove("persona-hidden")}else i.value=""},Ig=e=>{if(!vn(e))return;let t=Kn(e),r=co(e),o=t[r],n=typeof o=="string"&&o.length>0||Array.isArray(o)&&o.length>0,a=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');a&&(a.disabled=!n);let s=e.querySelector('[data-ask-user-action="submit-multi"]');if(s){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));s.disabled=i.length===0}},Il=(e,t,r)=>{let o=Zs(r),n=jy(e),{payload:a,complete:s}=Yo(t),i=vn(e),c=co(e),l=ka(e),p=i?Ky(a,c):Gy(a),f=!!(p!=null&&p.multiSelect),u=e.querySelector('[data-ask-step-inline="true"]');u&&(u.textContent=i?`${c+1}/${l}`:"");let m=e.querySelector('[data-ask-stepper="true"]');m&&m.remove();let x=e.querySelector('[data-ask-question="true"]');if(x){let A=typeof(p==null?void 0:p.question)=="string"?p.question:"";x.textContent=A,x.classList.toggle("persona-ask-question-skeleton",!A&&!s)}let b=e.querySelector('[data-ask-pill-list="true"]');if(b){let A=Qy(p,o,s,n);b.replaceWith(A)}if(n!=="rows"){let A=e.querySelector('[data-ask-free-text-row="true"]');A&&A.replaceWith(Lg(o,n))}let L=e.querySelector('[data-ask-multi-actions="true"]');!i&&f&&!L?e.appendChild(Yy(o)):(!f||i)&&L&&L.remove(),e.setAttribute("data-multi-select",f?"true":"false");let E=e.querySelector('[data-ask-nav-row="true"]');if(i){let A=Zy(c,l,o);E?E.replaceWith(A):e.appendChild(A)}else E&&E.remove();Rg(e),Ig(e)},ob=(e,t,r)=>{let o=Zs(t),n=$y(o),a=e.toolCall.id,s=ds(r),i=Math.max(1,s.length),c=i>1,l=tb(e,s),p=c?rb(e,i):0,f=w("div",["persona-ask-sheet",`persona-ask-sheet--${n}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));f.setAttribute(Ea,a),f.setAttribute("data-tool-call-id",a),f.setAttribute("data-message-id",e.id),f.setAttribute(Pl,String(i)),f.setAttribute(Ll,String(p)),f.setAttribute(Rl,c?"true":"false"),f.setAttribute(Mg,n),Pg(f,l),f.setAttribute("role","group"),f.setAttribute("aria-label","Suggested answers"),o.slideInMs!==void 0&&f.style.setProperty("--persona-ask-sheet-duration",`${o.slideInMs}ms`),Eg(f,o);let u=w("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),m=w("div","persona-ask-sheet-question persona-flex-1");m.setAttribute("data-ask-question","true"),m.textContent="",u.appendChild(m);let x=w("span","persona-ask-sheet-step-inline");x.setAttribute("data-ask-step-inline","true"),x.textContent="",u.appendChild(x),f.appendChild(u);let L=w("div",n==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return L.setAttribute("data-ask-pill-list","true"),L.setAttribute("role","group"),f.appendChild(L),n!=="rows"&&f.appendChild(Lg(o,n)),Il(f,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>f.classList.remove("persona-ask-sheet-enter"))}),f},nb=(e,t,r)=>{let{payload:o}=Yo(t),n=Math.max(1,ds(o).length);n>ka(e)&&(e.setAttribute(Pl,String(n)),n>1&&!vn(e)&&e.setAttribute(Rl,"true")),Il(e,t,r)},Wg=(e,t)=>{let r=w("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");r.id=`bubble-${e.id}`,r.setAttribute("data-message-id",e.id),r.setAttribute("data-bubble-type","ask-user-question");let o=Zs(t);Eg(r,o);let n=w("span","persona-ask-stub-label"),{complete:a}=Yo(e);return n.textContent=a?"Awaiting your response\u2026":"Preparing options\u2026",r.appendChild(n),r},La=(e,t,r)=>{if(!r||!Qo(e)||Zs(t).enabled===!1)return;let n=e.toolCall.id;r.querySelectorAll(`[${Ea}]`).forEach(l=>{l.getAttribute(Ea)!==n&&l.remove()});let s=r.querySelector(`[${Ea}="${Tg(n)}"]`);if(s){nb(s,e,t);return}let{payload:i}=Yo(e),c=ob(e,t,i);r.appendChild(c)},wn=(e,t)=>{if(!e)return;let r=t?`[${Ea}="${Tg(t)}"]`:`[${Ea}]`;e.querySelectorAll(r).forEach(n=>{n.classList.add("persona-ask-sheet-leave");let a=Number.parseInt(getComputedStyle(n).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>n.remove(),Number.isFinite(a)?a:180)})},Wl=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),Cn=(e,t)=>{let r=Kn(e),o=co(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete r[o]:r[o]=t,Pg(e,r),Rg(e),Ig(e)},ti=(e,t,r,o)=>{let n=ka(e),a=Math.max(0,Math.min(n-1,o));eb(e,a),Il(e,t,r)};var wo="suggest_replies";var Hl={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:wo,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:Hl,origin:"sdk",annotations:{readOnlyHint:!0}},Bl=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),cs=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===wo},Dl=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let r=t==null?void 0:t.suggestions;if(!Array.isArray(r))return[];let o=r.filter(n=>typeof n=="string").map(n=>n.trim()).filter(n=>n.length>0);return o.length>4?(console.warn(`[persona] suggest_replies: ${o.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),o.slice(0,4)):o},oi=e=>{var t;for(let r=e.length-1;r>=0;r--){let o=e[r];if(o.role==="user")return null;if(!cs(o))continue;let n=Dl((t=o.toolCall)==null?void 0:t.args);return n.length>0?n:null}return null},Hg=e=>{var r;let t=(r=e==null?void 0:e.features)==null?void 0:r.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Fl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:is,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},Nl={name:ls,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:Fl,origin:"sdk",annotations:{readOnlyHint:!0}},ps=e=>{var o;let t=[],r=(o=e==null?void 0:e.features)==null?void 0:o.askUserQuestion;return(r==null?void 0:r.expose)===!0&&r.enabled!==!1&&t.push(Nl),Hg(e)&&t.push(ri),t};var Zo=Sa(Ys(),1),ni=e=>e.replace(/\\n/g,`
10
10
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Sn=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)}},ab=e=>{var s,i;let t=(s=e.completedAt)!=null?s:Date.now(),r=(i=e.startedAt)!=null?i:t,n=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-r))/1e3;return n<.1?"Thought for <0.1 seconds":`Thought for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`},Bg=e=>e.status==="complete"?ab(e):e.status==="pending"?"Waiting":"",sb=e=>{var n,a,s;let r=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(a=e.startedAt)!=null?a:e.completedAt)!=null?s:Date.now())))/1e3;return r<.1?"Used tool for <0.1 seconds":`Used tool for ${r>=10?Math.round(r).toString():r.toFixed(1).replace(/\.0$/,"")} seconds`};var Dg=e=>e.status==="complete"?sb(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`},fs=e=>{var r,o,n;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ai(t)},si=e=>{var r,o,n;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((r=e.completedAt)!=null?r:Date.now())-((n=(o=e.startedAt)!=null?o:e.completedAt)!=null?n:Date.now()));return ai(t)},Ol=(e,t,r)=>{var a;if(!t)return r;let o=((a=e.name)==null?void 0:a.trim())||"tool",n=fs(e);return t.replace(/\{toolName\}/g,o).replace(/\{duration\}/g,n)},ii=(e,t)=>{let r=e.replace(/\{toolName\}/g,t),o=[],n=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,a=0,s;for(;(s=n.exec(r))!==null;)s.index>a&&us(o,r.slice(a,s.index),[]),s[1]!==void 0?us(o,s[1],["bold"]):s[2]!==void 0?us(o,s[2],["italic"]):s[3]!==void 0&&us(o,s[3],["dim"]),a=s.index+s[0].length;return a<r.length&&us(o,r.slice(a),[]),o},us=(e,t,r)=>{let o=t.split("{duration}");for(let n=0;n<o.length;n++)o[n]&&e.push({text:o[n],styles:r}),n<o.length-1&&e.push({text:"{duration}",styles:r,isDuration:!0})},ib=()=>{let e=null,t=0,r=o=>{let n=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,a=o.match(n);if(a&&a[1])try{return a[1].replace(/\\n/g,`
11
11
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return a[1]}let s=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=o.match(s);if(i&&i[1])try{return i[1].replace(/\\n/g,`
12
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ib();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ci=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ni(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ni(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Fg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ni(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ng="4.3.0";var Xn=Ng;var db="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function cb(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _l=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 pb(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ub(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Og(r);if(!Og(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:db,this.headers={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:pb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ta(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=bg(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(_l).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,m=!!(u&&u.length>0),x=m?xg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(_l).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...ps(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(_l).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...ps(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Ht,Qt,_o,So;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Ae=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Ie=P.tools?P.tools.map(Ee=>({...Ee,chunks:Ee.chunks?[...Ee.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Ae,tools:Ie}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Ae=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Ae||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},D=P=>{var ee,Ae,Ie,Ee,He;return I((He=(Ee=(Ie=(Ae=(ee=P.stepId)!=null?ee:P.step_id)!=null?Ae:P.step)!=null?Ie:P.parentId)!=null?Ee:P.flowStepId)!=null?He:P.flow_step_id)},O=P=>{var ee,Ae,Ie,Ee,He,Ge,st;return I((st=(Ge=(He=(Ee=(Ie=(Ae=(ee=P.callId)!=null?ee:P.call_id)!=null?Ae:P.requestId)!=null?Ie:P.request_id)!=null?Ee:P.toolCallId)!=null?He:P.tool_call_id)!=null?Ge:P.stepId)!=null?st:P.step_id)},J=o,me=!1,ce=()=>{if(m)return m;let P,ee=E;return!me&&J?(P=J,me=!0):J&&ee?P=`${J}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Se=(P,ee)=>{var He;let Ae=(He=P.reasoningId)!=null?He:P.id,Ie=D(P);if(Ae){let Ge=String(Ae);return te(Ie,Ge),Ge}if(Ie){let Ge=W.byStep.get(Ie);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let Ee=`reason-${l()}`;return te(Ie,Ee),Ee},We=P=>{let ee=v.get(P);if(ee)return ee;let Ae={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Ae),u(Ae),Ae},de=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},ve=new Set,se=new Map,ie=new Set,pe=new Map,Ve=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},_e=(P,ee)=>{var He;let Ae=(He=P.toolId)!=null?He:P.id,Ie=O(P);if(Ae){let Ge=String(Ae);return de(Ie,Ge),Ge}if(Ie){let Ge=H.byCall.get(Ie);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let Ee=`tool-${l()}`;return de(Ie,Ee),Ee},G=P=>{let ee=M.get(P);if(ee)return ee;let Ae={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Ae),u(Ae),Ae},K=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Ae=Date.parse(P);if(!Number.isNaN(Ae))return Ae}return Date.now()},Me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Q=new Map,le=new Map,Re=new Map,rt=(P,ee,Ae)=>{var st;let Ie=Re.get(P);Ie||(Ie=[],Re.set(P,Ie));let Ee=0,He=Ie.length;for(;Ee<He;){let Lt=Ee+He>>>1;Ie[Lt].seq<ee?Ee=Lt+1:He=Lt}((st=Ie[Ee])==null?void 0:st.seq)===ee?Ie[Ee]={seq:ee,text:Ae}:Ie.splice(Ee,0,{seq:ee,text:Ae});let Ge="";for(let Lt=0;Lt<Ie.length;Lt++)Ge+=Ie[Lt].text;return Ge},vt=(P,ee)=>{let Ae=Me(ee),Ie=le.get(P.id),Ee=ub(Ie,Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=Y=>{var it;let Ce=(it=P.content)!=null?it:"";Y.trim()!==""&&(Ce.trim().length===0||Y.startsWith(Ce)||Y.trimStart().startsWith(Ce.trim()))&&(P.content=Y)},st=()=>{var Y;if(He){let Ce=(Y=He.close)==null?void 0:Y.call(He);Ce instanceof Promise&&Ce.catch(()=>{})}Q.delete(P.id),le.delete(P.id),P.streaming=!1,u(P)};if(!He){Ge(Ae),st();return}let Lt=ms(Ee);if(Lt!==null&&Lt.trim()!==""){Ge(Lt),st();return}let xt=Y=>{var Je;let Ce=typeof Y=="string"?Y:(Je=Y==null?void 0:Y.text)!=null?Je:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let it=He.getExtractedText();return it!==null&&it.trim()!==""?it:Ae},F;try{F=He.processChunk(Ee)}catch{Ge(Ae),st();return}if(F instanceof Promise){F.then(Y=>{Ge(xt(Y)),st()}).catch(()=>{Ge(Ae),st()});return}Ge(xt(F)),st()},Ut=null,jt=(P,ee,Ae,Ie)=>{var Lt;P.rawContent=ee,Q.has(P.id)||Q.set(P.id,this.createStreamParser());let Ee=Q.get(P.id),He=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(He&&le.set(P.id,ee),Ee.__isPlainTextParser===!0){P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P);return}let st=Ee.processChunk(ee);if(st instanceof Promise)st.then(xt=>{var Y;let F=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;F!==null&&F.trim()!==""?(P.content=F,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P)});else{let xt=typeof st=="string"?st:(Lt=st==null?void 0:st.text)!=null?Lt:null;xt!==null&&xt.trim()!==""?(P.content=xt,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}},at=(P,ee)=>{var Lt,xt;let Ae=ee!=null?ee:P.content;if(Ae==null||Ae===""){P.streaming=!1,u(P);return}let Ie=le.get(P.id),Ee=Ie!=null?Ie:Me(Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=null,st=!1;if(He&&(Ge=He.getExtractedText(),Ge===null&&(Ge=ms(Ee)),Ge===null)){let F=He.processChunk(Ee);F instanceof Promise?(st=!0,F.then(Y=>{var it;let Ce=typeof Y=="string"?Y:(it=Y==null?void 0:Y.text)!=null?it:null;Ce!==null&&(P.content=Ce,P.streaming=!1,Q.delete(P.id),le.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof F=="string"?F:(Lt=F==null?void 0:F.text)!=null?Lt:null}if(!st){Ge!==null&&Ge.trim()!==""?P.content=Ge:le.has(P.id)||(P.content=Me(Ae));let F=Q.get(P.id);if(F){let Y=(xt=F.close)==null?void 0:xt.call(F);Y instanceof Promise&&Y.catch(()=>{}),Q.delete(P.id)}le.delete(P.id),P.streaming=!1,u(P)}},Ne=(P,ee,Ae)=>{let Ie=y.get(P);if(Ie)return Ie;let Ee={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ae?{variant:Ae}:{},...Ae==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,Ee),u(Ee),Ee},j=[],$e,ze=new Map,ye=0,we="agent",Ze=!1,Nt=null,re=null,Oe=new Map,xr=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for($e=()=>{var P,ee,Ae,Ie,Ee,He,Ge,st,Lt,xt,F,Y,Ce,it,Je,qt,yr,yt,bt,Pt,wt,pr,Ot,_r,Tr,Er,wr,kr,uo,Ct,Ao,Mo,Uo,fo,pt,Rn,To,In,Br,da,nn,qo,an,sn,Wn,Hn,ln,ht,Ur,qr,Lr,St,to,ro,Vr,dn,Vo,cn,zr,Rt,Pr,oo,pn,zo,un,he,Dr,Eo,ut,ar,sr,ko,$a,$o,Bn,Lo,q,ca,Po,Ro,jo,Io,mo,pa,Fs,$r,jr,go,ho,Dn,Go,Cr,Wo,ua,Fn,fa,Ns,ma,Os,ga,ct,ja,no,Fr,_s;for(let ha=0;ha<j.length;ha++){let Ye=j[ha].payloadType,k=j[ha].payload;if(!Ze&&we!=="flow"&&typeof k.stepType=="string"&&(we="flow"),Ye==="reasoning_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V),Ne($,V,"reasoning");continue}let X=(P=Se(k,!0))!=null?P:`reason-${l()}`,ge=We(X);ge.reasoning=(ee=ge.reasoning)!=null?ee:{id:X,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Ie=ge.reasoning.startedAt)!=null?Ie:K((Ae=k.startedAt)!=null?Ae:k.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),ge.streaming=!0,ge.reasoning.status="streaming",u(ge)}else if(Ye==="reasoning_delta"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let De=y.get($),ft=(Ge=(He=(Ee=k.reasoningText)!=null?Ee:k.text)!=null?He:k.delta)!=null?Ge:"";ft&&k.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(ft)),u(De));continue}let V=(Lt=(st=Se(k,!1))!=null?st:Se(k,!0))!=null?Lt:`reason-${l()}`,X=We(V);X.reasoning=(xt=X.reasoning)!=null?xt:{id:V,status:"streaming",chunks:[]},X.reasoning.startedAt=(Y=X.reasoning.startedAt)!=null?Y:K((F=k.startedAt)!=null?F:k.timestamp);let ge=(Je=(it=(Ce=k.reasoningText)!=null?Ce:k.text)!=null?it:k.delta)!=null?Je:"";if(ge&&k.hidden!==!0){let De=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(De!==void 0){let ft=rt(V,De,String(ge));X.reasoning.chunks=[ft]}else X.reasoning.chunks.push(String(ge))}if(X.reasoning.status=k.done?"complete":"streaming",k.done){X.reasoning.completedAt=K((qt=k.completedAt)!=null?qt:k.timestamp);let De=(yr=X.reasoning.startedAt)!=null?yr:Date.now();X.reasoning.durationMs=Math.max(0,((yt=X.reasoning.completedAt)!=null?yt:Date.now())-De)}X.streaming=X.reasoning.status!=="complete",u(X)}else if(Ye==="reasoning_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let ft=y.get($);if(ft.reasoning){let ot=typeof k.text=="string"?k.text:"";ot&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(ot),ft.reasoning.status="complete",ft.streaming=!1,u(ft)}T.delete($),y.delete($);continue}let V=(Pt=(bt=Se(k,!1))!=null?bt:Se(k,!0))!=null?Pt:`reason-${l()}`,X=typeof k.text=="string"?k.text:"";!v.get(V)&&(X||k.scope==="loop")&&We(V);let ge=v.get(V);if(ge!=null&&ge.reasoning){(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),X&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(X),ge.reasoning.status="complete",ge.reasoning.completedAt=K((wt=k.completedAt)!=null?wt:k.timestamp);let ft=(pr=ge.reasoning.startedAt)!=null?pr:Date.now();ge.reasoning.durationMs=Math.max(0,((Ot=ge.reasoning.completedAt)!=null?Ot:Date.now())-ft),ge.streaming=!1,u(ge)}let De=D(k);De&&W.byStep.delete(De)}else if(Ye==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ye=k.iteration);let $=(Tr=(_r=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?_r:_e(k,!0))!=null?Tr:`tool-${l()}`,V=(Er=k.toolName)!=null?Er:k.name;if(Ve(V)){ve.add($);continue}de(O(k),$);let X=G($),ge=(wr=X.toolCall)!=null?wr:{id:$,status:"pending"};ge.name=V!=null?V:ge.name,ge.status="running",k.parameters!==void 0?ge.args=k.parameters:k.args!==void 0&&(ge.args=k.args),ge.startedAt=(uo=ge.startedAt)!=null?uo:K((kr=k.startedAt)!=null?kr:k.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,X.toolCall=ge,X.streaming=!0,k.executionId&&(X.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(X)}else if(Ye==="tool_output_delta"){let $=(Ao=(Ct=_e(k,!1))!=null?Ct:_e(k,!0))!=null?Ao:`tool-${l()}`;if(ve.has($))continue;let V=G($),X=(Mo=V.toolCall)!=null?Mo:{id:$,status:"running"};X.startedAt=(fo=X.startedAt)!=null?fo:K((Uo=k.startedAt)!=null?Uo:k.timestamp);let ge=(To=(Rn=(pt=k.text)!=null?pt:k.delta)!=null?Rn:k.message)!=null?To:"";ge&&(X.chunks=(In=X.chunks)!=null?In:[],X.chunks.push(String(ge))),X.status="running",V.toolCall=X,V.streaming=!0;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(nn=V.agentMetadata)!=null?nn:{executionId:(Br=De==null?void 0:De.executionId)!=null?Br:k.executionId,iteration:(da=De==null?void 0:De.iteration)!=null?da:k.iteration}),u(V)}else if(Ye==="tool_complete"){let $=(an=(qo=_e(k,!1))!=null?qo:_e(k,!0))!=null?an:`tool-${l()}`;if(ve.has($)){ve.delete($);continue}let V=G($),X=(sn=V.toolCall)!=null?sn:{id:$,status:"running"};X.status="complete",k.result!==void 0&&(X.result=k.result),typeof k.duration=="number"&&(X.duration=k.duration),X.completedAt=K((Wn=k.completedAt)!=null?Wn:k.timestamp);let ge=(Hn=k.duration)!=null?Hn:k.executionTime;if(typeof ge=="number")X.durationMs=ge;else{let ot=(ln=X.startedAt)!=null?ln:Date.now();X.durationMs=Math.max(0,((ht=X.completedAt)!=null?ht:Date.now())-ot)}V.toolCall=X,V.streaming=!1;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(Lr=V.agentMetadata)!=null?Lr:{executionId:(Ur=De==null?void 0:De.executionId)!=null?Ur:k.executionId,iteration:(qr=De==null?void 0:De.iteration)!=null?qr:k.iteration}),u(V);let ft=O(k);ft&&H.byCall.delete(ft)}else if(Ye==="await"&&k.toolName){let $=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(St=$!=null?$:k.toolId)!=null?St:`local-${l()}`,X=G(V),ge=k.toolName,De=k.origin==="webmcp"&&!yn(ge)?`webmcp:${ge}`:ge,ft=yn(De),ot=(to=X.toolCall)!=null?to:{id:V,status:"pending"};ot.name=De,ot.args=k.parameters,ot.status=ft?"running":"complete",ot.chunks=(ro=ot.chunks)!=null?ro:[],ot.startedAt=(Vo=ot.startedAt)!=null?Vo:K((dn=(Vr=k.startedAt)!=null?Vr:k.timestamp)!=null?dn:k.awaitedAt),ft?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(cn=ot.completedAt)!=null?cn:ot.startedAt,X.toolCall=ot,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=k.executionId)!=null?Rt:(zr=X.agentMetadata)==null?void 0:zr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(X)}else if(Ye==="text_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V);continue}let X=m;X&&(we==="flow"?(at(X),Ut=X):(X.streaming=!1,u(X)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ye==="text_delta"){let $=typeof k.id=="string"?k.id:null,V=$?T.get($):void 0;if($&&V){let ge=typeof k.delta=="string"?k.delta:"",De=((Pr=S.get($))!=null?Pr:"")+ge;if(S.set($,De),De.trim()==="")continue;let ft=Ne($,V);ft.agentMetadata={...ft.agentMetadata,executionId:k.executionId,parentToolId:V},jt(ft,De,ge,void 0);continue}if(E=typeof k.id=="string"?k.id:E,we==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(A+=ge,A.trim()==="")continue;let De=ce();De.agentMetadata={executionId:k.executionId,iteration:k.iteration},jt(De,A,ge,void 0),x=De;continue}let X=ce();X.content+=(oo=k.delta)!=null?oo:"",X.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Nt!=null?Nt:void 0,agentName:re==null?void 0:re.agentName},x=X,u(X)}else if(Ye==="text_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)){let X=y.get($);X&&at(X),T.delete($),S.delete($),y.delete($);continue}let V=m;V&&(we==="flow"?(at(V),Ut=V):(((pn=V.content)!=null?pn:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(Ye==="step_complete"){let $=k.stepType,V=k.executionType;if($==="tool"||V==="context")continue;if(k.success===!1){let X=k.error,ge=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((zo=X.message)!=null?zo:"Step failed"):"Step failed";r({type:"error",error:new Error(ge)});let De=m;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let X=Ut;Ut=null;let ge=k.stopReason,De=(un=k.result)==null?void 0:un.response;if(X)ge&&(X.stopReason=ge),De!=null?vt(X,De):X.streaming!==!1&&(Q.delete(X.id),le.delete(X.id),X.streaming=!1,u(X));else{let ft=De!=null&&De!=="";if(ft||ge){let ot=ce();ge&&(ot.stopReason=ge),ft?at(ot,De):(ot.streaming=!1,u(ot))}}continue}}else if(Ye==="execution_start")we=k.kind==="flow"?"flow":"agent",Ze=!0,we==="agent"&&(re={executionId:k.executionId,agentId:(he=k.agentId)!=null?he:"virtual",agentName:(Dr=k.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(Eo=k.maxTurns)!=null?Eo:1,startedAt:K(k.startedAt)});else if(Ye==="turn_start"){let $=typeof k.iteration=="number"?k.iteration:ye;if($!==ye){if(re&&(re.currentIteration=$),xr==="separate"&&$>1){let V=m;V&&(V.streaming=!1,u(V),Oe.set($-1,V),m=null)}ye=$}Nt=typeof k.id=="string"?k.id:null,x=null}else if(Ye==="tool_input_delta"){let $=(ut=k.toolCallId)!=null?ut:H.lastId;if($){let V=M.get($);V!=null&&V.toolCall&&(V.toolCall.chunks=(ar=V.toolCall.chunks)!=null?ar:[],V.toolCall.chunks.push((sr=k.delta)!=null?sr:""),u(V))}}else{if(Ye==="tool_input_complete")continue;if(Ye==="turn_complete"){let $=k.stopReason,V=m!=null?m:x;if($&&V!==null){let X=k.id;(!X||((ko=V.agentMetadata)==null?void 0:ko.turnId)===X)&&(V.stopReason=$,u(V))}Nt===k.id&&(Nt=null)}else if(Ye==="media_start"){let $=String(k.id);ze.set($,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ye==="media_delta"){let $=ze.get(String(k.id));$&&typeof k.delta=="string"&&$.parts.push(k.delta)}else if(Ye==="media_complete"){let $=String(k.id),V=ze.get($);ze.delete($);let X=($o=($a=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?$a:V==null?void 0:V.mediaType)!=null?$o:"application/octet-stream",ge=typeof k.data=="string"?k.data:void 0,De=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ft=null;if(ge)ft={type:"media",data:ge,mediaType:X};else if(De){let ur=X.toLowerCase();ft={type:ur==="image"||ur.startsWith("image/")?"image-url":"file-url",url:De,mediaType:X}}let ot=(Bn=k.toolCallId)!=null?Bn:V==null?void 0:V.toolCallId,Ga=ft?[ft]:[],Nr=[];for(let ur of Ga){if(!ur||typeof ur!="object")continue;let fr=ur,Nn=typeof fr.type=="string"?fr.type:void 0,Ko=typeof fr.mediaType=="string"?fr.mediaType.toLowerCase():"",Rr=null,br="";if(Nn==="media"){let Gr=typeof fr.data=="string"?fr.data:void 0;if(!Gr)continue;br=Ko.length>0?Ko:"application/octet-stream",Rr=`data:${br};base64,${Gr}`}else if(Nn==="image-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else if(Nn==="file-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else continue;if(Rr)if(Nn==="image-url"||br.startsWith("image/"))Nr.push({type:"image",image:Rr,...br.includes("/")?{mimeType:br}:{}});else if(br.startsWith("audio/"))Nr.push({type:"audio",audio:Rr,mimeType:br});else if(br.startsWith("video/"))Nr.push({type:"video",video:Rr,mimeType:br});else{let Gr=br||"application/octet-stream";Nr.push({type:"file",data:Rr,mimeType:Gr,filename:cb(Gr)})}}if(Nr.length>0){let ur=l(),fr=ot,Ko={id:`agent-media-${typeof fr=="string"&&fr.length>0?`${fr}-${ur}`:String(ur)}`,role:"assistant",content:"",contentParts:Nr,createdAt:new Date().toISOString(),streaming:!1,sequence:ur,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ye}};u(Ko);let Rr=m;Rr&&(Rr.streaming=!1,u(Rr)),m=null,b.current=null}}else if(Ye==="execution_complete"){let $=(Lo=k.kind)!=null?Lo:we;$==="agent"&&re&&(re.status=k.success?"complete":"error",re.completedAt=K(k.completedAt),re.stopReason=k.stopReason);let V=m;V&&($==="flow"&&V.streaming!==!1?at(V):(V.streaming=!1,u(V)),m=null),E=null,A="",Ut=null,r({type:"status",status:"idle"})}else if(Ye==="execution_error"){let $=typeof k.error=="string"?k.error:(ca=(q=k.error)==null?void 0:q.message)!=null?ca:"Execution error";r({type:"error",error:new Error($)})}else if(Ye!=="ping"){if(Ye==="approval_start"){let $=(Po=k.approvalId)!=null?Po:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ro=re==null?void 0:re.agentId)!=null?Ro:"virtual",executionId:(Io=(jo=k.executionId)!=null?jo:re==null?void 0:re.executionId)!=null?Io:"",toolName:(mo=k.toolName)!=null?mo:"",toolType:k.toolType,description:(Fs=k.description)!=null?Fs:`Execute ${(pa=k.toolName)!=null?pa:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let $=($r=k.approvalId)!=null?$r:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(jr=re==null?void 0:re.agentId)!=null?jr:"virtual",executionId:(ho=(go=k.executionId)!=null?go:re==null?void 0:re.executionId)!=null?ho:"",toolName:(Dn=k.toolName)!=null?Dn:"",toolType:k.toolType,description:(Cr=k.description)!=null?Cr:`Execute ${(Go=k.toolName)!=null?Go:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="approval_complete"){let $=k.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Wo=k.decision)!=null?Wo:"approved",agentId:(ua=re==null?void 0:re.agentId)!=null?ua:"virtual",executionId:(fa=(Fn=k.executionId)!=null?Fn:re==null?void 0:re.executionId)!=null?fa:"",toolName:(Ns=k.toolName)!=null?Ns:"",description:(ma=k.description)!=null?ma:"",resolvedAt:Date.now()}};u(X)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let $=k.artifactType,V=String(k.id),X=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:$,title:X,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:X}),!ie.has(V)){ie.add(V);let ge={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:X,artifactType:$,status:"streaming"}})};se.set(V,ge),u(ge)}}else if(Ye==="artifact_delta"){let $=String(k.id),V=typeof k.delta=="string"?k.delta:String((Os=k.delta)!=null?Os:"");r({type:"artifact_delta",id:$,artDelta:V});let X=pe.get($);X&&(X.markdown+=V)}else if(Ye==="artifact_update"){let $=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:$,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let $=String(k.id);r({type:"artifact_complete",id:$});let V=se.get($);if(V){V.streaming=!1;try{let X=JSON.parse((ga=V.rawContent)!=null?ga:"{}");if(X.props){X.props.status="complete";let ge=pe.get($);ge!=null&&ge.markdown&&(X.props.markdown=ge.markdown)}V.rawContent=JSON.stringify(X)}catch{}pe.delete($),u(V),se.delete($)}}}else if(Ye==="transcript_insert"){let $=k.message;if(!$||typeof $!="object")continue;let V=String((ct=$.id)!=null?ct:`msg-${l()}`),X=$.role,De={id:V,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(u(De),De.rawContent)try{let ft=JSON.parse(De.rawContent),ot=(ja=ft==null?void 0:ft.props)==null?void 0:ja.artifactId;typeof ot=="string"&&ie.add(ot)}catch{}m=null,b.current=null,Q.delete(V),le.delete(V)}else if(Ye==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let $=typeof k.error=="string"?k.error:((no=k.error)==null?void 0:no.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error($)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let $=null;if(k.error instanceof Error)$=k.error;else if(Ye==="dispatch_error"){let V=(Fr=k.message)!=null?Fr:k.error;V!=null&&V!==""&&($=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?$=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&($=new Error(String((_s=V.message)!=null?_s:V)))}if($){r({type:"error",error:$});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}j.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Ae=s.split(`
12
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async o=>{if(o.length<=t)return e!==null?{text:e,raw:o}:null;let n=o.trim();if(!n.startsWith("{")&&!n.startsWith("["))return null;let a=r(o);return a!==null&&(e=a),t=o.length,e!==null?{text:e,raw:o}:null},close:async()=>{}}},ms=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},li=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ib();return{processChunk:async r=>{let o=r.trim();return!o.startsWith("{")&&!o.startsWith("[")?null:e.processChunk(r)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},ci=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e!==null||e===""?{text:e||"",raw:r}:null;try{let n=(0,Zo.parse)(r,Zo.STR|Zo.OBJ);n&&typeof n=="object"&&(n.component&&typeof n.component=="string"?e=typeof n.text=="string"?ni(n.text):"":n.type==="init"&&n.form?e="":typeof n.text=="string"&&(e=ni(n.text)))}catch{}return t=r.length,e!==null?{text:e,raw:r}:null},close:()=>{}}},Fg=e=>{let t=null,r=0,n=e||(a=>{if(!a||typeof a!="object")return null;let s=i=>typeof i=="string"?ni(i):null;if(a.component&&typeof a.component=="string")return typeof a.text=="string"?ni(a.text):"";if(a.type==="init"&&a.form)return"";if(a.action)switch(a.action){case"nav_then_click":return s(a.on_load_text)||s(a.text)||null;case"message":case"message_and_click":case"checkout":return s(a.text)||null;default:return s(a.text)||s(a.display_text)||s(a.message)||null}return s(a.text)||s(a.display_text)||s(a.message)||s(a.content)||null});return{getExtractedText:()=>t,processChunk:a=>{let s=a.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;if(a.length<=r)return t!==null?{text:t,raw:a}:null;try{let i=(0,Zo.parse)(a,Zo.STR|Zo.OBJ),c=n(i);c!==null&&(t=c)}catch{}return r=a.length,{text:t||"",raw:a}},close:()=>{}}},pi=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let o=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return o&&o[1]?(e=o[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Ng="4.4.0";var Xn=Ng;var db="https://api.runtype.com/v1/dispatch",ui="https://api.runtype.com";function cb(e){var a,s;let t=e.toLowerCase(),o={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(o)return`attachment.${o}`;let n=t.indexOf("/");if(n>0){let i=(s=(a=t.slice(n+1).split(";")[0])==null?void 0:a.trim())!=null?s:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var _l=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 pb(e){switch(e){case"json":return ci;case"regex-json":return di;case"xml":return pi;default:return li}}var Og=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function ub(e,t){if(!e)return t;let r=e.trim(),o=t.trim();if(r.length===0)return t;if(o.length===0)return e;let n=Og(r);if(!Og(o))return e;if(!n||o===r||o.startsWith(r))return t;let s=ms(e);return ms(t)!==null&&s===null?t:e}var Jn=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var r,o,n,a;if(t.target&&(t.agentId||t.flowId||t.agent))throw new Error("[Persona] `target` is mutually exclusive with `agentId`, `flowId`, and `agent`. Set only one routing field.");this.apiUrl=(r=t.apiUrl)!=null?r:db,this.headers={"Content-Type":"application/json","X-Persona-Version":Xn,...t.headers},this.debug=!!t.debug,this.createStreamParser=(o=t.streamParser)!=null?o:pb(t.parserType),this.contextProviders=(n=t.contextProviders)!=null?n:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((a=t.webmcp)==null?void 0:a.enabled)===!0?new Ta(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var r;(r=this.webMcpBridge)==null||r.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,r,o){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,r,o):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}routing(){let{agentId:t,flowId:r,target:o,targetProviders:n}=this.config;if(!o)return{agentId:t,flowId:r};let a=bg(o,n);return a.kind==="agentId"?{agentId:a.agentId}:a.kind==="flowId"?{flowId:a.flowId}:{targetPayload:a.payload}}isAgentMode(){return!!(this.config.agent||this.routing().agentId)}getClientApiUrl(t){var o;return`${((o=this.config.apiUrl)==null?void 0:o.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,r;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let o=await this.sessionInitPromise;return this.clientSession=o,this.resetClientToolsFingerprint(),(r=(t=this.config).onSessionInit)==null||r.call(t,o),o}finally{this.sessionInitPromise=null}}async _doInitSession(){var i,c,l;let t=((c=(i=this.config).getStoredSessionId)==null?void 0:c.call(i))||null,r=this.routing(),o=(l=r.agentId)!=null?l:r.flowId,n={token:this.config.clientToken,...o&&{flowId:o},...t&&{sessionId:t}},a=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let p=await a.json().catch(()=>({error:"Session initialization failed"}));throw a.status===401?new Error(`Invalid client token: ${p.hint||p.error}`):a.status===403?new Error(`Origin not allowed: ${p.hint||p.error}`):new Error(p.error||"Failed to initialize session")}let s=await a.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(s.sessionId),{sessionId:s.sessionId,expiresAt:new Date(s.expiresAt),flow:s.flow,config:{welcomeMessage:s.config.welcomeMessage,placeholder:s.config.placeholder,theme:s.config.theme}}}clearClientSession(){this.clientSession=null,this.sessionInitPromise=null,this.resetClientToolsFingerprint()}resetClientToolsFingerprint(){this.lastSentClientToolsFingerprint=null,this.clientToolsFingerprintSessionId=null}getFeedbackApiUrl(){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/client/feedback`}async sendFeedback(t){var s,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let n={...t,...this.config.clientToken&&{token:this.config.clientToken}},a=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(n)});if(!a.ok){let c=await a.json().catch(()=>({error:"Feedback submission failed"}));throw a.status===401?(this.clientSession=null,(i=(s=this.config).onSessionExpired)==null||i.call(s),new Error("Session expired. Please refresh to continue.")):new Error(c.error||"Failed to submit feedback")}}async submitMessageFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,messageId:t,type:r})}async submitCSATFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"csat",rating:t,comment:r})}async submitNPSFeedback(t,r){let o=this.getClientSession();if(!o)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:o.sessionId,type:"nps",rating:t,comment:r})}async dispatch(t,r){return this.isClientTokenMode()?this.dispatchClientToken(t,r):this.isAgentMode()?this.dispatchAgent(t,r):this.dispatchProxy(t,r)}async dispatchClientToken(t,r){var n,a,s,i;let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});try{let c=await this.initSession();if(new Date>=new Date(c.expiresAt.getTime()-6e4)){this.clearClientSession(),(a=(n=this.config).onSessionExpired)==null||a.call(n);let y=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:y}),y}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([y])=>y!=="sessionId"&&y!=="session_id")):void 0,f={sessionId:c.sessionId,messages:t.messages.filter(_l).map(y=>{var S,v,M;return{id:y.id,role:y.role,content:(M=(v=(S=y.contentParts)!=null?S:y.llmContent)!=null?v:y.rawContent)!=null?M:y.content}}),...t.assistantMessageId&&{assistantMessageId:t.assistantMessageId},...p&&Object.keys(p).length>0&&{metadata:p},...l.inputs&&Object.keys(l.inputs).length>0&&{inputs:l.inputs},...l.context&&{context:l.context}},u=l.clientTools,m=!!(u&&u.length>0),x=m?xg(u):void 0,b=this.clientToolsFingerprintSessionId===c.sessionId,L=m&&b&&this.lastSentClientToolsFingerprint===x,E=!1,A=null,T;for(let y=0;;y++){let v={...f,...m&&(E||!L)&&u?{clientTools:u}:{},...x?{clientToolsFingerprint:x}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",v),T=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json","X-Persona-Version":Xn},body:JSON.stringify(v),signal:o.signal}),T.status===409&&y===0&&m){let M=await T.json().catch(()=>null);if((M==null?void 0:M.error)==="client_tools_resend_required"){E=!0,this.lastSentClientToolsFingerprint=null;continue}A=M!=null?M:{error:"Chat request failed"}}break}if(!T.ok){let y=A!=null?A:await T.json().catch(()=>({error:"Chat request failed"}));if(T.status===401){this.clearClientSession(),(i=(s=this.config).onSessionExpired)==null||i.call(s);let v=new Error("Session expired. Please refresh to continue.");throw r({type:"error",error:v}),v}if(T.status===429){let v=new Error(y.hint||"Message limit reached for this session.");throw r({type:"error",error:v}),v}let S=new Error(y.error||"Failed to send message");throw r({type:"error",error:S}),S}if(!T.body){let y=new Error("No response body received");throw r({type:"error",error:y}),y}this.lastSentClientToolsFingerprint=x!=null?x:null,this.clientToolsFingerprintSessionId=c.sessionId,r({type:"status",status:"connected"});try{await this.streamResponse(T.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}catch(c){let l=c instanceof Error?c:new Error(String(c));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&r({type:"error",error:l}),l}}async dispatchProxy(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Chat backend request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r)}finally{r({type:"status",status:"idle"})}}async dispatchAgent(t,r){let o=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>o.abort()),r({type:"status",status:"connecting"});let n=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",n);let a={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();a={...a,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let s;if(this.customFetch)try{s=await this.customFetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal},n)}catch(i){let c=i instanceof Error?i:new Error(String(i));throw r({type:"error",error:c}),c}else s=await fetch(this.apiUrl,{method:"POST",headers:a,body:JSON.stringify(n),signal:o.signal});if(!s.ok||!s.body){let i=new Error(`Agent execution request failed: ${s.status} ${s.statusText}`);throw r({type:"error",error:i}),i}r({type:"status",status:"connected"});try{await this.streamResponse(s.body,r,t.assistantMessageId)}finally{r({type:"status",status:"idle"})}}async processStream(t,r,o){r({type:"status",status:"connected"});try{await this.streamResponse(t,r,o)}finally{r({type:"status",status:"idle"})}}async resolveApproval(t,r){var s;let n=`${((s=this.config.apiUrl)==null?void 0:s.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||ui}/v1/agents/${t.agentId}/approve`,a={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(a,await this.getHeaders()),fetch(n,{method:"POST",headers:a,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:r,streamResponse:!0})})}async resumeFlow(t,r,o){var l,p;let n=this.isClientTokenMode(),a=n?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||ui}/resume`,s;n&&(s=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let c={executionId:t,toolOutputs:r,streamResponse:(p=o==null?void 0:o.streamResponse)!=null?p:!0};return s&&(c.sessionId=s),fetch(a,{method:"POST",headers:i,body:JSON.stringify(c),signal:o==null?void 0:o.signal})}async buildAgentPayload(t){var s,i,c;let r=this.routing().agentId;if(!this.config.agent&&!r)throw new Error("Agent configuration required for agent mode");let o=t.slice().filter(_l).filter(l=>l.role==="user"||l.role==="assistant"||l.role==="system").filter(l=>!l.variant||l.variant==="assistant").sort((l,p)=>{let f=new Date(l.createdAt).getTime(),u=new Date(p.createdAt).getTime();return f-u}).map(l=>{var p,f,u;return{role:l.role,content:(u=(f=(p=l.contentParts)!=null?p:l.llmContent)!=null?f:l.rawContent)!=null?u:l.content,createdAt:l.createdAt}}),n={agent:(s=this.config.agent)!=null?s:{agentId:r},messages:o,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},a=[...ps(this.config),...(c=await((i=this.webMcpBridge)==null?void 0:i.snapshotForDispatch()))!=null?c:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let l={};await Promise.all(this.contextProviders.map(async p=>{try{let f=await p({messages:t,config:this.config});f&&typeof f=="object"&&Object.assign(l,f)}catch(f){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",f)}})),Object.keys(l).length&&(n.context=l)}return n}async buildPayload(t){var s,i;let r=t.slice().filter(_l).sort((c,l)=>{let p=new Date(c.createdAt).getTime(),f=new Date(l.createdAt).getTime();return p-f}).map(c=>{var l,p,f;return{role:c.role,content:(f=(p=(l=c.contentParts)!=null?l:c.llmContent)!=null?p:c.rawContent)!=null?f:c.content,createdAt:c.createdAt}}),o=this.routing(),n={messages:r,...o.agentId?{agent:{agentId:o.agentId}}:o.flowId?{flowId:o.flowId}:{}};if(o.targetPayload)for(let[c,l]of Object.entries(o.targetPayload))c!=="messages"&&(n[c]=l);let a=[...ps(this.config),...(i=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?i:[]];if(a.length>0&&(n.clientTools=a),this.contextProviders.length){let c={};await Promise.all(this.contextProviders.map(async l=>{try{let p=await l({messages:t,config:this.config});p&&typeof p=="object"&&Object.assign(c,p)}catch(p){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",p)}})),Object.keys(c).length&&(n.context=c)}if(this.requestMiddleware)try{let c=await this.requestMiddleware({payload:{...n},config:this.config});if(c&&typeof c=="object"){let l=c;return n.clientTools!==void 0&&!("clientTools"in l)&&(l.clientTools=n.clientTools),l}}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",c)}return n}async handleCustomSSEEvent(t,r,o,n,a,s){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let c=p=>{let f={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:a(),...p!==void 0&&{partId:p}};return o.current=f,n(f),f},l=p=>o.current?o.current:c(p);if(i.text!==void 0){i.partId!==void 0&&s.current!==null&&i.partId!==s.current&&(o.current&&(o.current.streaming=!1,n(o.current)),c(i.partId)),i.partId!==void 0&&(s.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,n(p)}return i.done&&(o.current&&(o.current.streaming=!1,n(o.current)),s.current=null,r({type:"status",status:"idle"})),i.error&&(s.current=null,r({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,r,o){var Ht,Qt,_o,So;let n=t.getReader(),a=new TextDecoder,s="",i=Date.now(),c=0,l=()=>i+c++,p=P=>{let ee=P.reasoning?{...P.reasoning,chunks:[...P.reasoning.chunks]}:void 0,Ae=P.toolCall?{...P.toolCall,chunks:P.toolCall.chunks?[...P.toolCall.chunks]:void 0}:void 0,Ie=P.tools?P.tools.map(Ee=>({...Ee,chunks:Ee.chunks?[...Ee.chunks]:void 0})):void 0;return{...P,reasoning:ee,toolCall:Ae,tools:Ie}},f=P=>{if(P.role!=="assistant"||P.variant)return!0;let ee=Array.isArray(P.contentParts)&&P.contentParts.length>0,Ae=typeof P.rawContent=="string"&&P.rawContent.trim()!=="";return typeof P.content=="string"&&P.content.trim()!==""||ee||Ae||!!P.stopReason},u=P=>{f(P)&&r({type:"message",message:p(P)})},m=null,x=null,b={current:null},L={current:null},E=null,A="",T=new Map,y=new Map,S=new Map,v=new Map,M=new Map,W={lastId:null,byStep:new Map},H={lastId:null,byCall:new Map},I=P=>{if(P==null)return null;try{return String(P)}catch{return null}},D=P=>{var ee,Ae,Ie,Ee,He;return I((He=(Ee=(Ie=(Ae=(ee=P.stepId)!=null?ee:P.step_id)!=null?Ae:P.step)!=null?Ie:P.parentId)!=null?Ee:P.flowStepId)!=null?He:P.flow_step_id)},O=P=>{var ee,Ae,Ie,Ee,He,Ge,st;return I((st=(Ge=(He=(Ee=(Ie=(Ae=(ee=P.callId)!=null?ee:P.call_id)!=null?Ae:P.requestId)!=null?Ie:P.request_id)!=null?Ee:P.toolCallId)!=null?He:P.tool_call_id)!=null?Ge:P.stepId)!=null?st:P.step_id)},J=o,me=!1,ce=()=>{if(m)return m;let P,ee=E;return!me&&J?(P=J,me=!0):J&&ee?P=`${J}_${ee}`:P=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,m={id:P,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},u(m),m},te=(P,ee)=>{W.lastId=ee,P&&W.byStep.set(P,ee)},Se=(P,ee)=>{var He;let Ae=(He=P.reasoningId)!=null?He:P.id,Ie=D(P);if(Ae){let Ge=String(Ae);return te(Ie,Ge),Ge}if(Ie){let Ge=W.byStep.get(Ie);if(Ge)return W.lastId=Ge,Ge}if(W.lastId&&!ee)return W.lastId;if(!ee)return null;let Ee=`reason-${l()}`;return te(Ie,Ee),Ee},We=P=>{let ee=v.get(P);if(ee)return ee;let Ae={id:`reason-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:P,status:"streaming",chunks:[]}};return v.set(P,Ae),u(Ae),Ae},de=(P,ee)=>{H.lastId=ee,P&&H.byCall.set(P,ee)},ve=new Set,se=new Map,ie=new Set,pe=new Map,Ve=P=>{if(!P)return!1;let ee=P.replace(/_+/g,"_").replace(/^_|_$/g,"");return ee==="emit_artifact_markdown"||ee==="emit_artifact_component"},_e=(P,ee)=>{var He;let Ae=(He=P.toolId)!=null?He:P.id,Ie=O(P);if(Ae){let Ge=String(Ae);return de(Ie,Ge),Ge}if(Ie){let Ge=H.byCall.get(Ie);if(Ge)return H.lastId=Ge,Ge}if(H.lastId&&!ee)return H.lastId;if(!ee)return null;let Ee=`tool-${l()}`;return de(Ie,Ee),Ee},G=P=>{let ee=M.get(P);if(ee)return ee;let Ae={id:`tool-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:P,status:"pending"}};return M.set(P,Ae),u(Ae),Ae},K=P=>{if(typeof P=="number"&&Number.isFinite(P))return P;if(typeof P=="string"){let ee=Number(P);if(!Number.isNaN(ee)&&Number.isFinite(ee))return ee;let Ae=Date.parse(P);if(!Number.isNaN(Ae))return Ae}return Date.now()},Me=P=>{if(typeof P=="string")return P;if(P==null)return"";try{return JSON.stringify(P)}catch{return String(P)}},Q=new Map,le=new Map,Re=new Map,rt=(P,ee,Ae)=>{var st;let Ie=Re.get(P);Ie||(Ie=[],Re.set(P,Ie));let Ee=0,He=Ie.length;for(;Ee<He;){let Lt=Ee+He>>>1;Ie[Lt].seq<ee?Ee=Lt+1:He=Lt}((st=Ie[Ee])==null?void 0:st.seq)===ee?Ie[Ee]={seq:ee,text:Ae}:Ie.splice(Ee,0,{seq:ee,text:Ae});let Ge="";for(let Lt=0;Lt<Ie.length;Lt++)Ge+=Ie[Lt].text;return Ge},vt=(P,ee)=>{let Ae=Me(ee),Ie=le.get(P.id),Ee=ub(Ie,Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=Y=>{var it;let Ce=(it=P.content)!=null?it:"";Y.trim()!==""&&(Ce.trim().length===0||Y.startsWith(Ce)||Y.trimStart().startsWith(Ce.trim()))&&(P.content=Y)},st=()=>{var Y;if(He){let Ce=(Y=He.close)==null?void 0:Y.call(He);Ce instanceof Promise&&Ce.catch(()=>{})}Q.delete(P.id),le.delete(P.id),P.streaming=!1,u(P)};if(!He){Ge(Ae),st();return}let Lt=ms(Ee);if(Lt!==null&&Lt.trim()!==""){Ge(Lt),st();return}let xt=Y=>{var Je;let Ce=typeof Y=="string"?Y:(Je=Y==null?void 0:Y.text)!=null?Je:null;if(Ce!==null&&Ce.trim()!=="")return Ce;let it=He.getExtractedText();return it!==null&&it.trim()!==""?it:Ae},F;try{F=He.processChunk(Ee)}catch{Ge(Ae),st();return}if(F instanceof Promise){F.then(Y=>{Ge(xt(Y)),st()}).catch(()=>{Ge(Ae),st()});return}Ge(xt(F)),st()},Ut=null,jt=(P,ee,Ae,Ie)=>{var Lt;P.rawContent=ee,Q.has(P.id)||Q.set(P.id,this.createStreamParser());let Ee=Q.get(P.id),He=ee.trim().startsWith("{")||ee.trim().startsWith("[");if(He&&le.set(P.id,ee),Ee.__isPlainTextParser===!0){P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P);return}let st=Ee.processChunk(ee);if(st instanceof Promise)st.then(xt=>{var Y;let F=typeof xt=="string"?xt:(Y=xt==null?void 0:xt.text)!=null?Y:null;F!==null&&F.trim()!==""?(P.content=F,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}).catch(()=>{P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P)});else{let xt=typeof st=="string"?st:(Lt=st==null?void 0:st.text)!=null?Lt:null;xt!==null&&xt.trim()!==""?(P.content=xt,u(P)):!He&&!ee.trim().startsWith("<")&&(P.content=Ie!==void 0?ee:P.content+Ae,le.delete(P.id),Q.delete(P.id),P.rawContent=void 0,u(P))}},at=(P,ee)=>{var Lt,xt;let Ae=ee!=null?ee:P.content;if(Ae==null||Ae===""){P.streaming=!1,u(P);return}let Ie=le.get(P.id),Ee=Ie!=null?Ie:Me(Ae);P.rawContent=Ee;let He=Q.get(P.id),Ge=null,st=!1;if(He&&(Ge=He.getExtractedText(),Ge===null&&(Ge=ms(Ee)),Ge===null)){let F=He.processChunk(Ee);F instanceof Promise?(st=!0,F.then(Y=>{var it;let Ce=typeof Y=="string"?Y:(it=Y==null?void 0:Y.text)!=null?it:null;Ce!==null&&(P.content=Ce,P.streaming=!1,Q.delete(P.id),le.delete(P.id),u(P))}).catch(()=>{})):Ge=typeof F=="string"?F:(Lt=F==null?void 0:F.text)!=null?Lt:null}if(!st){Ge!==null&&Ge.trim()!==""?P.content=Ge:le.has(P.id)||(P.content=Me(Ae));let F=Q.get(P.id);if(F){let Y=(xt=F.close)==null?void 0:xt.call(F);Y instanceof Promise&&Y.catch(()=>{}),Q.delete(P.id)}le.delete(P.id),P.streaming=!1,u(P)}},Ne=(P,ee,Ae)=>{let Ie=y.get(P);if(Ie)return Ie;let Ee={id:`nested-${ee}-${P}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Ae?{variant:Ae}:{},...Ae==="reasoning"?{reasoning:{id:P,status:"streaming",chunks:[]}}:{},agentMetadata:{parentToolId:ee}};return y.set(P,Ee),u(Ee),Ee},j=[],$e,ze=new Map,ye=0,we="agent",Ze=!1,Nt=null,re=null,Oe=new Map,xr=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for($e=()=>{var P,ee,Ae,Ie,Ee,He,Ge,st,Lt,xt,F,Y,Ce,it,Je,qt,yr,yt,bt,Pt,wt,pr,Ot,_r,Tr,Er,wr,kr,uo,Ct,Ao,Mo,Uo,fo,pt,Rn,To,In,Br,da,nn,qo,an,sn,Wn,Hn,ln,ht,Ur,qr,Lr,St,to,ro,Vr,dn,Vo,cn,zr,Rt,Pr,oo,pn,zo,un,he,Dr,Eo,ut,ar,sr,ko,$a,$o,Bn,Lo,q,ca,Po,Ro,jo,Io,mo,pa,Fs,$r,jr,go,ho,Dn,Go,Cr,Wo,ua,Fn,fa,Ns,ma,Os,ga,ct,ja,no,Fr,_s;for(let ha=0;ha<j.length;ha++){let Ye=j[ha].payloadType,k=j[ha].payload;if(!Ze&&we!=="flow"&&typeof k.stepType=="string"&&(we="flow"),Ye==="reasoning_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V),Ne($,V,"reasoning");continue}let X=(P=Se(k,!0))!=null?P:`reason-${l()}`,ge=We(X);ge.reasoning=(ee=ge.reasoning)!=null?ee:{id:X,status:"streaming",chunks:[]},ge.reasoning.startedAt=(Ie=ge.reasoning.startedAt)!=null?Ie:K((Ae=k.startedAt)!=null?Ae:k.timestamp),ge.reasoning.completedAt=void 0,ge.reasoning.durationMs=void 0,(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),ge.streaming=!0,ge.reasoning.status="streaming",u(ge)}else if(Ye==="reasoning_delta"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let De=y.get($),ft=(Ge=(He=(Ee=k.reasoningText)!=null?Ee:k.text)!=null?He:k.delta)!=null?Ge:"";ft&&k.hidden!==!0&&De.reasoning&&(De.reasoning.chunks.push(String(ft)),u(De));continue}let V=(Lt=(st=Se(k,!1))!=null?st:Se(k,!0))!=null?Lt:`reason-${l()}`,X=We(V);X.reasoning=(xt=X.reasoning)!=null?xt:{id:V,status:"streaming",chunks:[]},X.reasoning.startedAt=(Y=X.reasoning.startedAt)!=null?Y:K((F=k.startedAt)!=null?F:k.timestamp);let ge=(Je=(it=(Ce=k.reasoningText)!=null?Ce:k.text)!=null?it:k.delta)!=null?Je:"";if(ge&&k.hidden!==!0){let De=typeof k.sequenceIndex=="number"?k.sequenceIndex:void 0;if(De!==void 0){let ft=rt(V,De,String(ge));X.reasoning.chunks=[ft]}else X.reasoning.chunks.push(String(ge))}if(X.reasoning.status=k.done?"complete":"streaming",k.done){X.reasoning.completedAt=K((qt=k.completedAt)!=null?qt:k.timestamp);let De=(yr=X.reasoning.startedAt)!=null?yr:Date.now();X.reasoning.durationMs=Math.max(0,((yt=X.reasoning.completedAt)!=null?yt:Date.now())-De)}X.streaming=X.reasoning.status!=="complete",u(X)}else if(Ye==="reasoning_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)&&y.has($)){let ft=y.get($);if(ft.reasoning){let ot=typeof k.text=="string"?k.text:"";ot&&ft.reasoning.chunks.length===0&&ft.reasoning.chunks.push(ot),ft.reasoning.status="complete",ft.streaming=!1,u(ft)}T.delete($),y.delete($);continue}let V=(Pt=(bt=Se(k,!1))!=null?bt:Se(k,!0))!=null?Pt:`reason-${l()}`,X=typeof k.text=="string"?k.text:"";!v.get(V)&&(X||k.scope==="loop")&&We(V);let ge=v.get(V);if(ge!=null&&ge.reasoning){(k.scope==="loop"||k.scope==="turn")&&(ge.reasoning.scope=k.scope),X&&ge.reasoning.chunks.length===0&&ge.reasoning.chunks.push(X),ge.reasoning.status="complete",ge.reasoning.completedAt=K((wt=k.completedAt)!=null?wt:k.timestamp);let ft=(pr=ge.reasoning.startedAt)!=null?pr:Date.now();ge.reasoning.durationMs=Math.max(0,((Ot=ge.reasoning.completedAt)!=null?Ot:Date.now())-ft),ge.streaming=!1,u(ge)}let De=D(k);De&&W.byStep.delete(De)}else if(Ye==="tool_start"){m&&(m.streaming=!1,u(m),m=null),typeof k.iteration=="number"&&(ye=k.iteration);let $=(Tr=(_r=typeof k.toolCallId=="string"?k.toolCallId:void 0)!=null?_r:_e(k,!0))!=null?Tr:`tool-${l()}`,V=(Er=k.toolName)!=null?Er:k.name;if(Ve(V)){ve.add($);continue}de(O(k),$);let X=G($),ge=(wr=X.toolCall)!=null?wr:{id:$,status:"pending"};ge.name=V!=null?V:ge.name,ge.status="running",k.parameters!==void 0?ge.args=k.parameters:k.args!==void 0&&(ge.args=k.args),ge.startedAt=(uo=ge.startedAt)!=null?uo:K((kr=k.startedAt)!=null?kr:k.timestamp),ge.completedAt=void 0,ge.durationMs=void 0,X.toolCall=ge,X.streaming=!0,k.executionId&&(X.agentMetadata={executionId:k.executionId,iteration:k.iteration}),u(X)}else if(Ye==="tool_output_delta"){let $=(Ao=(Ct=_e(k,!1))!=null?Ct:_e(k,!0))!=null?Ao:`tool-${l()}`;if(ve.has($))continue;let V=G($),X=(Mo=V.toolCall)!=null?Mo:{id:$,status:"running"};X.startedAt=(fo=X.startedAt)!=null?fo:K((Uo=k.startedAt)!=null?Uo:k.timestamp);let ge=(To=(Rn=(pt=k.text)!=null?pt:k.delta)!=null?Rn:k.message)!=null?To:"";ge&&(X.chunks=(In=X.chunks)!=null?In:[],X.chunks.push(String(ge))),X.status="running",V.toolCall=X,V.streaming=!0;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(nn=V.agentMetadata)!=null?nn:{executionId:(Br=De==null?void 0:De.executionId)!=null?Br:k.executionId,iteration:(da=De==null?void 0:De.iteration)!=null?da:k.iteration}),u(V)}else if(Ye==="tool_complete"){let $=(an=(qo=_e(k,!1))!=null?qo:_e(k,!0))!=null?an:`tool-${l()}`;if(ve.has($)){ve.delete($);continue}let V=G($),X=(sn=V.toolCall)!=null?sn:{id:$,status:"running"};X.status="complete",k.result!==void 0&&(X.result=k.result),typeof k.duration=="number"&&(X.duration=k.duration),X.completedAt=K((Wn=k.completedAt)!=null?Wn:k.timestamp);let ge=(Hn=k.duration)!=null?Hn:k.executionTime;if(typeof ge=="number")X.durationMs=ge;else{let ot=(ln=X.startedAt)!=null?ln:Date.now();X.durationMs=Math.max(0,((ht=X.completedAt)!=null?ht:Date.now())-ot)}V.toolCall=X,V.streaming=!1;let De=k.agentContext;(De||k.executionId)&&(V.agentMetadata=(Lr=V.agentMetadata)!=null?Lr:{executionId:(Ur=De==null?void 0:De.executionId)!=null?Ur:k.executionId,iteration:(qr=De==null?void 0:De.iteration)!=null?qr:k.iteration}),u(V);let ft=O(k);ft&&H.byCall.delete(ft)}else if(Ye==="await"&&k.toolName){let $=typeof k.toolCallId=="string"&&k.toolCallId.length>0?k.toolCallId:void 0,V=(St=$!=null?$:k.toolId)!=null?St:`local-${l()}`,X=G(V),ge=k.toolName,De=k.origin==="webmcp"&&!yn(ge)?`webmcp:${ge}`:ge,ft=yn(De),ot=(to=X.toolCall)!=null?to:{id:V,status:"pending"};ot.name=De,ot.args=k.parameters,ot.status=ft?"running":"complete",ot.chunks=(ro=ot.chunks)!=null?ro:[],ot.startedAt=(Vo=ot.startedAt)!=null?Vo:K((dn=(Vr=k.startedAt)!=null?Vr:k.timestamp)!=null?dn:k.awaitedAt),ft?(ot.completedAt=void 0,ot.duration=void 0,ot.durationMs=void 0):ot.completedAt=(cn=ot.completedAt)!=null?cn:ot.startedAt,X.toolCall=ot,X.streaming=!1,X.agentMetadata={...X.agentMetadata,executionId:(Rt=k.executionId)!=null?Rt:(zr=X.agentMetadata)==null?void 0:zr.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},u(X)}else if(Ye==="text_start"){let $=typeof k.id=="string"?k.id:null,V=typeof k.parentToolCallId=="string"&&k.parentToolCallId?k.parentToolCallId:null;if($&&V){T.set($,V);continue}let X=m;X&&(we==="flow"?(at(X),Ut=X):(X.streaming=!1,u(X)),m=null),E=typeof k.id=="string"?k.id:E,A=""}else if(Ye==="text_delta"){let $=typeof k.id=="string"?k.id:null,V=$?T.get($):void 0;if($&&V){let ge=typeof k.delta=="string"?k.delta:"",De=((Pr=S.get($))!=null?Pr:"")+ge;if(S.set($,De),De.trim()==="")continue;let ft=Ne($,V);ft.agentMetadata={...ft.agentMetadata,executionId:k.executionId,parentToolId:V},jt(ft,De,ge,void 0);continue}if(E=typeof k.id=="string"?k.id:E,we==="flow"){let ge=typeof k.delta=="string"?k.delta:"";if(A+=ge,A.trim()==="")continue;let De=ce();De.agentMetadata={executionId:k.executionId,iteration:k.iteration},jt(De,A,ge,void 0),x=De;continue}let X=ce();X.content+=(oo=k.delta)!=null?oo:"",X.agentMetadata={executionId:k.executionId,iteration:k.iteration,turnId:Nt!=null?Nt:void 0,agentName:re==null?void 0:re.agentName},x=X,u(X)}else if(Ye==="text_complete"){let $=typeof k.id=="string"?k.id:null;if($&&T.has($)){let X=y.get($);X&&at(X),T.delete($),S.delete($),y.delete($);continue}let V=m;V&&(we==="flow"?(at(V),Ut=V):(((pn=V.content)!=null?pn:"")===""&&typeof k.text=="string"&&(V.content=k.text),V.streaming=!1,u(V)),m=null),E=null,A=""}else if(Ye==="step_complete"){let $=k.stepType,V=k.executionType;if($==="tool"||V==="context")continue;if(k.success===!1){let X=k.error,ge=typeof X=="string"&&X!==""?X:X!=null&&typeof X=="object"&&"message"in X?String((zo=X.message)!=null?zo:"Step failed"):"Step failed";r({type:"error",error:new Error(ge)});let De=m;De&&De.streaming&&(De.streaming=!1,u(De)),r({type:"status",status:"idle"});continue}{let X=Ut;Ut=null;let ge=k.stopReason,De=(un=k.result)==null?void 0:un.response;if(X)ge&&(X.stopReason=ge),De!=null?vt(X,De):X.streaming!==!1&&(Q.delete(X.id),le.delete(X.id),X.streaming=!1,u(X));else{let ft=De!=null&&De!=="";if(ft||ge){let ot=ce();ge&&(ot.stopReason=ge),ft?at(ot,De):(ot.streaming=!1,u(ot))}}continue}}else if(Ye==="execution_start")we=k.kind==="flow"?"flow":"agent",Ze=!0,we==="agent"&&(re={executionId:k.executionId,agentId:(he=k.agentId)!=null?he:"virtual",agentName:(Dr=k.agentName)!=null?Dr:"",status:"running",currentIteration:0,maxTurns:(Eo=k.maxTurns)!=null?Eo:1,startedAt:K(k.startedAt)});else if(Ye==="turn_start"){let $=typeof k.iteration=="number"?k.iteration:ye;if($!==ye){if(re&&(re.currentIteration=$),xr==="separate"&&$>1){let V=m;V&&(V.streaming=!1,u(V),Oe.set($-1,V),m=null)}ye=$}Nt=typeof k.id=="string"?k.id:null,x=null}else if(Ye==="tool_input_delta"){let $=(ut=k.toolCallId)!=null?ut:H.lastId;if($){let V=M.get($);V!=null&&V.toolCall&&(V.toolCall.chunks=(ar=V.toolCall.chunks)!=null?ar:[],V.toolCall.chunks.push((sr=k.delta)!=null?sr:""),u(V))}}else{if(Ye==="tool_input_complete")continue;if(Ye==="turn_complete"){let $=k.stopReason,V=m!=null?m:x;if($&&V!==null){let X=k.id;(!X||((ko=V.agentMetadata)==null?void 0:ko.turnId)===X)&&(V.stopReason=$,u(V))}Nt===k.id&&(Nt=null)}else if(Ye==="media_start"){let $=String(k.id);ze.set($,{mediaType:typeof k.mediaType=="string"?k.mediaType:void 0,role:typeof k.role=="string"?k.role:void 0,toolCallId:k.toolCallId,parts:[]})}else if(Ye==="media_delta"){let $=ze.get(String(k.id));$&&typeof k.delta=="string"&&$.parts.push(k.delta)}else if(Ye==="media_complete"){let $=String(k.id),V=ze.get($);ze.delete($);let X=($o=($a=typeof k.mediaType=="string"?k.mediaType:void 0)!=null?$a:V==null?void 0:V.mediaType)!=null?$o:"application/octet-stream",ge=typeof k.data=="string"?k.data:void 0,De=typeof k.url=="string"?k.url:V&&V.parts.length>0?V.parts.join(""):void 0,ft=null;if(ge)ft={type:"media",data:ge,mediaType:X};else if(De){let ur=X.toLowerCase();ft={type:ur==="image"||ur.startsWith("image/")?"image-url":"file-url",url:De,mediaType:X}}let ot=(Bn=k.toolCallId)!=null?Bn:V==null?void 0:V.toolCallId,Ga=ft?[ft]:[],Nr=[];for(let ur of Ga){if(!ur||typeof ur!="object")continue;let fr=ur,Nn=typeof fr.type=="string"?fr.type:void 0,Ko=typeof fr.mediaType=="string"?fr.mediaType.toLowerCase():"",Rr=null,br="";if(Nn==="media"){let Gr=typeof fr.data=="string"?fr.data:void 0;if(!Gr)continue;br=Ko.length>0?Ko:"application/octet-stream",Rr=`data:${br};base64,${Gr}`}else if(Nn==="image-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else if(Nn==="file-url"){let Gr=typeof fr.url=="string"?fr.url:void 0;if(!Gr)continue;br=Ko,Rr=Gr}else continue;if(Rr)if(Nn==="image-url"||br.startsWith("image/"))Nr.push({type:"image",image:Rr,...br.includes("/")?{mimeType:br}:{}});else if(br.startsWith("audio/"))Nr.push({type:"audio",audio:Rr,mimeType:br});else if(br.startsWith("video/"))Nr.push({type:"video",video:Rr,mimeType:br});else{let Gr=br||"application/octet-stream";Nr.push({type:"file",data:Rr,mimeType:Gr,filename:cb(Gr)})}}if(Nr.length>0){let ur=l(),fr=ot,Ko={id:`agent-media-${typeof fr=="string"&&fr.length>0?`${fr}-${ur}`:String(ur)}`,role:"assistant",content:"",contentParts:Nr,createdAt:new Date().toISOString(),streaming:!1,sequence:ur,agentMetadata:{executionId:k.executionId,iteration:typeof k.iteration=="number"?k.iteration:ye}};u(Ko);let Rr=m;Rr&&(Rr.streaming=!1,u(Rr)),m=null,b.current=null}}else if(Ye==="execution_complete"){let $=(Lo=k.kind)!=null?Lo:we;$==="agent"&&re&&(re.status=k.success?"complete":"error",re.completedAt=K(k.completedAt),re.stopReason=k.stopReason);let V=m;V&&($==="flow"&&V.streaming!==!1?at(V):(V.streaming=!1,u(V)),m=null),E=null,A="",Ut=null,r({type:"status",status:"idle"})}else if(Ye==="execution_error"){let $=typeof k.error=="string"?k.error:(ca=(q=k.error)==null?void 0:q.message)!=null?ca:"Execution error";r({type:"error",error:new Error($)})}else if(Ye!=="ping"){if(Ye==="approval_start"){let $=(Po=k.approvalId)!=null?Po:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ro=re==null?void 0:re.agentId)!=null?Ro:"virtual",executionId:(Io=(jo=k.executionId)!=null?jo:re==null?void 0:re.executionId)!=null?Io:"",toolName:(mo=k.toolName)!=null?mo:"",toolType:k.toolType,description:(Fs=k.description)!=null?Fs:`Execute ${(pa=k.toolName)!=null?pa:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="step_await"&&k.awaitReason==="approval_required"){let $=($r=k.approvalId)!=null?$r:`approval-${l()}`,V={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(jr=re==null?void 0:re.agentId)!=null?jr:"virtual",executionId:(ho=(go=k.executionId)!=null?go:re==null?void 0:re.executionId)!=null?ho:"",toolName:(Dn=k.toolName)!=null?Dn:"",toolType:k.toolType,description:(Cr=k.description)!=null?Cr:`Execute ${(Go=k.toolName)!=null?Go:"tool"}`,...typeof k.reason=="string"&&k.reason?{reason:k.reason}:{},parameters:k.parameters}};u(V)}else if(Ye==="approval_complete"){let $=k.approvalId;if($){let X={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(Wo=k.decision)!=null?Wo:"approved",agentId:(ua=re==null?void 0:re.agentId)!=null?ua:"virtual",executionId:(fa=(Fn=k.executionId)!=null?Fn:re==null?void 0:re.executionId)!=null?fa:"",toolName:(Ns=k.toolName)!=null?Ns:"",description:(ma=k.description)!=null?ma:"",resolvedAt:Date.now()}};u(X)}}else if(Ye==="artifact_start"||Ye==="artifact_delta"||Ye==="artifact_update"||Ye==="artifact_complete"){if(Ye==="artifact_start"){let $=k.artifactType,V=String(k.id),X=typeof k.title=="string"?k.title:void 0;if(r({type:"artifact_start",id:V,artifactType:$,title:X,component:typeof k.component=="string"?k.component:void 0}),pe.set(V,{markdown:"",title:X}),!ie.has(V)){ie.add(V);let ge={id:`artifact-ref-${V}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:V,title:X,artifactType:$,status:"streaming"}})};se.set(V,ge),u(ge)}}else if(Ye==="artifact_delta"){let $=String(k.id),V=typeof k.delta=="string"?k.delta:String((Os=k.delta)!=null?Os:"");r({type:"artifact_delta",id:$,artDelta:V});let X=pe.get($);X&&(X.markdown+=V)}else if(Ye==="artifact_update"){let $=k.props&&typeof k.props=="object"&&!Array.isArray(k.props)?k.props:{};r({type:"artifact_update",id:String(k.id),props:$,component:typeof k.component=="string"?k.component:void 0})}else if(Ye==="artifact_complete"){let $=String(k.id);r({type:"artifact_complete",id:$});let V=se.get($);if(V){V.streaming=!1;try{let X=JSON.parse((ga=V.rawContent)!=null?ga:"{}");if(X.props){X.props.status="complete";let ge=pe.get($);ge!=null&&ge.markdown&&(X.props.markdown=ge.markdown)}V.rawContent=JSON.stringify(X)}catch{}pe.delete($),u(V),se.delete($)}}}else if(Ye==="transcript_insert"){let $=k.message;if(!$||typeof $!="object")continue;let V=String((ct=$.id)!=null?ct:`msg-${l()}`),X=$.role,De={id:V,role:X==="user"?"user":X==="system"?"system":"assistant",content:typeof $.content=="string"?$.content:"",rawContent:typeof $.rawContent=="string"?$.rawContent:void 0,createdAt:typeof $.createdAt=="string"?$.createdAt:new Date().toISOString(),streaming:$.streaming===!0,...typeof $.variant=="string"?{variant:$.variant}:{},sequence:l()};if(u(De),De.rawContent)try{let ft=JSON.parse(De.rawContent),ot=(ja=ft==null?void 0:ft.props)==null?void 0:ja.artifactId;typeof ot=="string"&&ie.add(ot)}catch{}m=null,b.current=null,Q.delete(V),le.delete(V)}else if(Ye==="error"){if(k.recoverable===!1&&k.error!=null&&k.error!==""){let $=typeof k.error=="string"?k.error:((no=k.error)==null?void 0:no.message)!=null?String(k.error.message):"Execution error";r({type:"error",error:new Error($)});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}else if(Ye==="step_error"||Ye==="dispatch_error"||Ye==="flow_error"){let $=null;if(k.error instanceof Error)$=k.error;else if(Ye==="dispatch_error"){let V=(Fr=k.message)!=null?Fr:k.error;V!=null&&V!==""&&($=new Error(String(V)))}else{let V=k.error;typeof V=="string"&&V!==""?$=new Error(V):V!=null&&typeof V=="object"&&"message"in V&&($=new Error(String((_s=V.message)!=null?_s:V)))}if($){r({type:"error",error:$});let V=m;V&&V.streaming&&(V.streaming=!1,u(V)),r({type:"status",status:"idle"})}}}}}j.length=0};;){let{done:P,value:ee}=await n.read();if(P)break;s+=a.decode(ee,{stream:!0});let Ae=s.split(`
13
13
 
14
14
  `);s=(Qt=Ae.pop())!=null?Qt:"";for(let Ie of Ae){let Ee=Ie.split(`
15
15
  `),He="message",Ge="";for(let xt of Ee)xt.startsWith("event:")?He=xt.replace("event:","").trim():xt.startsWith("data:")&&(Ge+=xt.replace("data:","").trim());if(!Ge)continue;let st;try{st=JSON.parse(Ge)}catch(xt){r({type:"error",error:xt instanceof Error?xt:new Error("Failed to parse chat stream payload")});continue}let Lt=He!=="message"?He:(_o=st.type)!=null?_o:"message";if((So=this.onSSEEvent)==null||So.call(this,Lt,st),this.parseSSEEvent){b.current=m;let xt=await this.handleCustomSSEEvent(st,r,b,u,l,L);if(b.current&&b.current!==m&&(m=b.current),xt)continue}j.push({payloadType:Lt,payload:st}),$e()}}$e()}};function _g(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Pa(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Qn(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function Ug(e){return typeof e=="string"?[{type:"text",text:e}]:e}function qg(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Vg(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function zg(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function gs(e){return{type:"text",text:e}}function $g(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 jg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;t({type:"image",image:n,mimeType:e.type,alt:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Gg(e,t=["image/png","image/jpeg","image/gif","image/webp"],r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Kg=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],fb=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],en=[...Kg,...fb];function mb(e){return Kg.includes(e)||e.startsWith("image/")}function mi(e){return mb(e.type)}async function Xg(e){return new Promise((t,r)=>{let o=new FileReader;o.onload=()=>{let n=o.result;mi(e)?t({type:"image",image:n,mimeType:e.type,alt:e.name}):t({type:"file",data:n,mimeType:e.type,filename:e.name})},o.onerror=()=>r(new Error("Failed to read file")),o.readAsDataURL(e)})}function Jg(e,t=en,r=10*1024*1024){return t.includes(e.type)?e.size>r?{valid:!1,error:`File too large. Maximum size: ${Math.round(r/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function gb(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Qg(e,t){let r=gb(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||r||"FILE"}var gi=class{constructor(t=24e3,r={}){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.startedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.started=!1;this.userPaused=!1;this.pendingBuffers=[];this.pendingSamples=0;this.remainder=null;var n;this.sampleRate=t;let o=Math.max(0,(n=r.prebufferMs)!=null?n:0);this.waterlineSamples=Math.round(t*o/1e3),this.buffering=this.waterlineSamples>0}ensureContext(){if(!this.ctx){let r=typeof window!="undefined"?window:void 0;if(!r)throw new Error("AudioPlaybackManager requires a browser environment");let o=r.AudioContext||r.webkitAudioContext;this.ctx=new o({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&!this.userPaused&&t.resume(),t}enqueue(t){if(t.length===0)return;let r=t;if(this.remainder){let n=new Uint8Array(this.remainder.length+t.length);n.set(this.remainder),n.set(t,this.remainder.length),r=n,this.remainder=null}if(r.length%2!==0&&(this.remainder=new Uint8Array([r[r.length-1]]),r=r.subarray(0,r.length-1)),r.length===0)return;let o=this.pcmToFloat32(r);o.length!==0&&(this.buffering?(this.pendingBuffers.push(o),this.pendingSamples+=o.length,this.pendingSamples>=this.waterlineSamples&&this.releaseBuffer()):this.scheduleSamples(o))}markStreamEnd(){this.pendingBuffers.length>0&&this.releaseBuffer(),this.streamEnded=!0,this.checkFinished()}flush(){for(let t of this.activeSources)try{t.stop(),t.disconnect()}catch{}this.activeSources=[],this.pendingCount=0,this.nextStartTime=0,this.playing=!1,this.streamEnded=!1,this.finishedCallbacks=[],this.startedCallbacks=[],this.remainder=null,this.pendingBuffers=[],this.pendingSamples=0,this.buffering=this.waterlineSamples>0,this.started=!1}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}onStarted(t){this.startedCallbacks.push(t)}pause(){this.userPaused=!0,this.ctx&&this.ctx.state==="running"&&this.ctx.suspend()}resume(){this.userPaused=!1,this.ctx&&this.ctx.state==="suspended"&&this.ctx.resume()}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}releaseBuffer(){this.buffering=!1;let t=this.pendingBuffers;this.pendingBuffers=[],this.pendingSamples=0;for(let r of t)this.scheduleSamples(r)}scheduleSamples(t){if(t.length===0)return;let r=this.ensureContext(),o=r.createBuffer(1,t.length,this.sampleRate);o.getChannelData(0).set(t);let n=r.createBufferSource();n.buffer=o,n.connect(r.destination);let a=r.currentTime;if(this.nextStartTime===0?this.nextStartTime=a:this.nextStartTime<a&&(this.nextStartTime=a,this.waterlineSamples>0&&(this.buffering=!0)),n.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(n),this.pendingCount++,this.playing=!0,!this.started){this.started=!0;let s=this.startedCallbacks.slice();this.startedCallbacks=[];for(let i of s)i()}n.onended=()=>{let s=this.activeSources.indexOf(n);s!==-1&&this.activeSources.splice(s,1),this.pendingCount--,this.checkFinished()}}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.pendingBuffers.length===0){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let r of t)r()}}pcmToFloat32(t){let r=Math.floor(t.length/2),o=new Float32Array(r),n=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let a=0;a<r;a++){let s=n.getInt16(a*2,!0);o[a]=s/32768}return o}};var Yg=16e3,hb=24e3,xb=4096,yb=1380533830;function bb(e){return e.byteLength>=44&&new DataView(e).getUint32(0,!1)===yb?new Uint8Array(e,44):new Uint8Array(e)}function vb(e){var o;let t=e.replace(/\/+$/,"");return/^wss?:\/\//i.test(t)?t:/^https?:\/\//i.test(t)?t.replace(/^http/i,"ws"):`${typeof window!="undefined"&&((o=window.location)==null?void 0:o.protocol)==="https:"?"wss:":"ws:"}//${t}`}var hs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.captureContext=null;this.mediaStream=null;this.sourceNode=null;this.processor=null;this.playback=null;this.callLive=!1;this.isSpeaking=!1;this.callGeneration=0;this.intentionalClose=!1;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.transcriptCallbacks=[];this.metricsCallbacks=[]}async connect(){}async startListening(){var a,s,i,c;if(this.callLive)return;let t=(a=this.config)==null?void 0:a.agentId,r=(s=this.config)==null?void 0:s.clientToken,o=(i=this.config)==null?void 0:i.host;if(!t)throw new Error("Runtype voice requires an agentId");if(!r)throw new Error("Runtype voice requires a clientToken");if(!o)throw new Error("Runtype voice requires a host (or widget apiUrl)");let n=++this.callGeneration;this.intentionalClose=!1,this.callLive=!0;try{let l=await navigator.mediaDevices.getUserMedia({audio:{sampleRate:Yg,channelCount:1,echoCancellation:!0}});if(n!==this.callGeneration){l.getTracks().forEach(b=>b.stop());return}this.mediaStream=l;let p=window.AudioContext||window.webkitAudioContext,f=new p({sampleRate:Yg});f.state==="suspended"&&await f.resume().catch(()=>{}),this.captureContext=f;let u=(c=this.config)!=null&&c.createPlaybackEngine?await this.config.createPlaybackEngine():new gi(hb);if(n!==this.callGeneration){u.destroy(),l.getTracks().forEach(b=>b.stop()),f.close().catch(()=>{});return}this.playback=u,u.onFinished(()=>{n===this.callGeneration&&(this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening"))});let m=`${vb(o)}/ws/agents/${encodeURIComponent(t)}/voice`,x=new WebSocket(m,["runtype.bearer",r]);x.binaryType="arraybuffer",this.ws=x,x.onopen=()=>{n===this.callGeneration&&(this.emitStatus("listening"),this.startCapture(f,l,x,n))},x.onmessage=b=>this.handleMessage(b,n),x.onerror=()=>{n===this.callGeneration&&(this.emitError(new Error("Voice connection failed")),this.emitStatus("error"),this.cleanup())},x.onclose=b=>{if(this.intentionalClose){this.intentionalClose=!1;return}if(n===this.callGeneration){if(b.code!==1e3){let L=b.code?` (code ${b.code})`:"";this.emitError(new Error(`Voice connection closed${L}`)),this.emitStatus("error")}else this.emitStatus("idle");this.cleanup()}}}catch(l){throw this.cleanup(),this.emitError(l),this.emitStatus("error"),l}}async stopListening(){this.cleanup(),this.emitStatus("idle")}async disconnect(){this.cleanup(),this.emitStatus("disconnected"),this.resultCallbacks=[],this.errorCallbacks=[],this.statusCallbacks=[],this.transcriptCallbacks=[],this.metricsCallbacks=[]}stopPlayback(){this.playback&&this.playback.flush(),this.isSpeaking=!1,this.ws&&this.ws.readyState===WebSocket.OPEN&&this.emitStatus("listening")}getInterruptionMode(){return"barge-in"}isBargeInActive(){return this.callLive}async deactivateBargeIn(){this.cleanup(),this.emitStatus("idle")}startCapture(t,r,o,n){let a=t.createMediaStreamSource(r);this.sourceNode=a;let s=t.createScriptProcessor(xb,1,1);this.processor=s,s.onaudioprocess=i=>{if(n!==this.callGeneration||o.readyState!==WebSocket.OPEN)return;let c=i.inputBuffer.getChannelData(0),l=new Int16Array(c.length);for(let p=0;p<c.length;p++){let f=Math.max(-1,Math.min(1,c[p]));l[p]=f<0?f*32768:f*32767}o.send(l.buffer)},a.connect(s),s.connect(t.destination)}handleMessage(t,r){var n,a;if(r!==this.callGeneration)return;if(t.data instanceof ArrayBuffer){this.handleAudioFrame(t.data,r);return}let o;try{o=JSON.parse(t.data)}catch{return}switch(o.type){case"transcript_interim":this.emitStatus("listening"),this.emitTranscript("user",(n=o.text)!=null?n:"",!1);break;case"transcript_final":{let s=o.role==="assistant"?"assistant":"user";this.emitStatus(s==="user"?"processing":"speaking"),this.emitTranscript(s,(a=o.text)!=null?a:"",!0);break}case"audio_end":this.playback?this.playback.markStreamEnd():(this.isSpeaking=!1,this.emitStatus("listening"));break;case"metrics":this.emitMetrics({llmMs:o.llm_ms,ttsMs:o.tts_ms,firstAudioMs:o.first_audio_ms,totalMs:o.total_ms});break;case"error":this.emitError(new Error(o.error||"Voice error")),this.emitStatus("error");break}}handleAudioFrame(t,r){if(r!==this.callGeneration||!this.playback)return;let o=bb(t);o.length!==0&&(this.isSpeaking||(this.isSpeaking=!0,this.emitStatus("speaking")),this.playback.enqueue(o))}cleanup(){if(this.callGeneration+=1,this.callLive=!1,this.isSpeaking=!1,this.processor&&(this.processor.onaudioprocess=null,this.processor.disconnect(),this.processor=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.captureContext&&(this.captureContext.close().catch(()=>{}),this.captureContext=null),this.playback&&(this.playback.destroy(),this.playback=null),this.ws){this.intentionalClose=!0;try{this.ws.close(1e3,"client ended call")}catch{}this.ws=null}}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onTranscript(t){this.transcriptCallbacks.push(t)}onMetrics(t){this.metricsCallbacks.push(t)}emitStatus(t){this.statusCallbacks.forEach(r=>r(t))}emitError(t){this.errorCallbacks.forEach(r=>r(t))}emitTranscript(t,r,o){this.transcriptCallbacks.forEach(n=>n(t,r,o))}emitMetrics(t){this.metricsCallbacks.forEach(r=>r(t))}};var Yn=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,r;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let o=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!o)throw new Error("Browser speech recognition not supported");this.recognition=new o,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((r=this.config)==null?void 0:r.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=n=>{var i;let a=Array.from(n.results).map(c=>c[0]).map(c=>c.transcript).join(""),s=n.results[n.results.length-1].isFinal;this.resultCallbacks.forEach(c=>c({text:a,confidence:s?.8:.5,provider:"browser"})),s&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=n=>{this.errorCallbacks.forEach(a=>a(new Error(n.error))),this.statusCallbacks.forEach(a=>a("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(n=>n("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(n=>n("idle"))},this.recognition.start()}catch(o){throw this.errorCallbacks.forEach(n=>n(o)),this.statusCallbacks.forEach(n=>n("error")),o}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function An(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new hs(e.runtype);case"browser":if(!Yn.isSupported())throw new Error("Browser speech recognition not supported");return new Yn(e.browser||{});case"custom":{let t=e.custom;if(!t)throw new Error("Custom voice provider requires a `custom` provider instance or factory");let r=typeof t=="function"?t():t;if(!r||typeof r.startListening!="function")throw new Error("Custom voice provider `custom` must be a VoiceProvider (or a factory returning one)");return r}default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function hi(e){if((e==null?void 0:e.type)==="custom"&&e.custom)return An({type:"custom",custom:e.custom});if((e==null?void 0:e.type)==="runtype"&&e.runtype)return An({type:"runtype",runtype:e.runtype});if(Yn.isSupported())return An({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function xs(e){try{return hi(e),!0}catch{return!1}}function Ra(e){var r;let t=["Microsoft Jenny Online (Natural) - English (United States)","Microsoft Aria Online (Natural) - English (United States)","Microsoft Guy Online (Natural) - English (United States)","Google US English","Google UK English Female","Ava (Premium)","Evan (Enhanced)","Samantha (Enhanced)","Samantha","Daniel","Karen","Microsoft David Desktop - English (United States)","Microsoft Zira Desktop - English (United States)"];for(let o of t){let n=e.find(a=>a.name===o);if(n)return n}return(r=e.find(o=>o.lang.startsWith("en")))!=null?r:e[0]}var Mn=class e{constructor(t={}){this.options=t;this.id="browser";this.supportsPause=!0}static isSupported(){return typeof window!="undefined"&&"speechSynthesis"in window}speak(t,r){var s;if(!e.isSupported()){(s=r.onError)==null||s.call(r,new Error("Web Speech API is unavailable"));return}let o=window.speechSynthesis;o.cancel();let n=new SpeechSynthesisUtterance(t.text),a=o.getVoices();if(t.voice){let i=a.find(c=>c.name===t.voice);i&&(n.voice=i)}else a.length>0&&(n.voice=this.options.pickVoice?this.options.pickVoice(a):Ra(a));t.rate!==void 0&&(n.rate=t.rate),t.pitch!==void 0&&(n.pitch=t.pitch),n.onend=()=>{var i;return(i=r.onEnd)==null?void 0:i.call(r)},n.onerror=i=>{var l,p;let c=i.error;c==="canceled"||c==="interrupted"?(l=r.onEnd)==null||l.call(r):(p=r.onError)==null||p.call(r,new Error(c||"Speech synthesis failed"))},setTimeout(()=>{var i;o.speak(n),(i=r.onStart)==null||i.call(r)},50)}pause(){e.isSupported()&&window.speechSynthesis.pause()}resume(){e.isSupported()&&window.speechSynthesis.resume()}stop(){e.isSupported()&&window.speechSynthesis.cancel()}};var Zn=class{constructor(t){this.resolveEngine=t;this.engine=null;this.activeId=null;this.state="idle";this.listeners=new Set;this.generation=0}get supportsPause(){var t,r;return(r=(t=this.engine)==null?void 0:t.supportsPause)!=null?r:!0}stateFor(t){return this.activeId===t?this.state:"idle"}activeMessageId(){return this.activeId}onChange(t){return this.listeners.add(t),()=>this.listeners.delete(t)}toggle(t,r){var o,n;if(this.activeId===t){if(this.state==="playing"){(o=this.engine)!=null&&o.supportsPause?(this.engine.pause(),this.set(t,"paused")):this.stop();return}if(this.state==="paused"){(n=this.engine)==null||n.resume(),this.set(t,"playing");return}if(this.state==="loading"){this.stop();return}}this.play(t,r)}async play(t,r){var n;let o=++this.generation;(n=this.engine)==null||n.stop(),this.set(t,"loading");try{if(!this.engine){let a=await this.resolveEngine();if(o!==this.generation)return;if(!a){this.set(null,"idle");return}this.engine=a}this.engine.speak(r,{onStart:()=>{o===this.generation&&this.set(t,"playing")},onEnd:()=>{o===this.generation&&this.set(null,"idle")},onError:()=>{o===this.generation&&this.set(null,"idle")}})}catch{o===this.generation&&this.set(null,"idle")}}stop(){var t;this.generation++,(t=this.engine)==null||t.stop(),this.set(null,"idle")}destroy(){var t,r;this.stop(),(r=(t=this.engine)==null?void 0:t.destroy)==null||r.call(t),this.engine=null,this.listeners.clear()}set(t,r){this.activeId=r==="idle"?null:t,this.state=r;for(let o of this.listeners)o(this.activeId,this.state)}};function Ul(e){if(!e)return"";let t=wb(e);return Zg(t!==null?t:e)}function wb(e){let t=e.trim(),r=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i);if(r&&(t=r[1].trim()),!t.startsWith("{"))return null;try{let o=JSON.parse(t);if(o&&typeof o=="object"&&typeof o.text=="string")return o.text}catch{}return null}function Zg(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,`
@@ -17,7 +17,7 @@ ${e.description}`:"");return window.confirm(r)},Ly=e=>{if(e==null)return"";try{l
17
17
  `),t.trim()}var ql=null,eh=e=>{ql=e},Vl=()=>ql?ql():import("./runtype-tts-entry");var Cb=["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 Cb.some(r=>e[r]!==t[r])}function th(e,t){let r=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(r);let o="Sorry: I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return r.message?`${o}
18
18
 
19
19
  _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]}),rh=(e,t="WebMCP tool execution failed.")=>e instanceof Error&&e.message?e.message:typeof e=="string"&&e?e:t,oh=e=>yn(e)||e===wo,Ia=class{constructor(t={},r){this.config=t;this.callbacks=r;this.status="idle";this.streaming=!1;this.abortController=null;this.sequenceCounter=Date.now();this.clientSession=null;this.agentExecution=null;this.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 Zn(()=>this.createSpeechEngine());this.handleEvent=t=>{var r,o,n,a,s,i,c,l,p,f;if(t.type==="message"){this.upsertMessage(t.message);let u=t.message.toolCall,m=!!(u!=null&&u.name)&&(yn(u.name)||u.name===wo&&((o=(r=this.config.features)==null?void 0:r.suggestReplies)==null?void 0:o.enabled)!==!1);((n=t.message.agentMetadata)==null?void 0:n.awaitingLocalTool)===!0&&m&&this.enqueueWebMcpAwait(t.message),(a=t.message.agentMetadata)!=null&&a.executionId&&(this.agentExecution?t.message.agentMetadata.iteration!==void 0&&(this.agentExecution.currentIteration=t.message.agentMetadata.iteration):this.agentExecution={executionId:t.message.agentMetadata.executionId,agentId:"",agentName:(s=t.message.agentMetadata.agentName)!=null?s:"",status:"running",currentIteration:(i=t.message.agentMetadata.iteration)!=null?i:0,maxTurns:0})}else if(t.type==="status"){if(this.setStatus(t.status),t.status==="connecting")this.setStreaming(!0);else if(t.status==="idle"||t.status==="error"){this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null);let u=this.webMcpAwaitBatches.size>0||this.webMcpResolveControllers.size>0;((c=this.agentExecution)==null?void 0:c.status)==="running"&&(t.status==="error"?this.agentExecution.status="error":u||(this.agentExecution.status="complete")),this.scheduleWebMcpBatchFlush()}}else t.type==="error"?(this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),((l=this.agentExecution)==null?void 0:l.status)==="running"&&(this.agentExecution.status="error"),(f=(p=this.callbacks).onError)==null||f.call(p,t.error)):(t.type==="artifact_start"||t.type==="artifact_delta"||t.type==="artifact_update"||t.type==="artifact_complete")&&this.applyArtifactStreamEvent(t)};var o,n;this.messages=[...(o=t.initialMessages)!=null?o:[]].map(a=>{var s;return{...a,sequence:(s=a.sequence)!=null?s:this.nextSequence()}}),this.messages=this.sortMessages(this.messages),this.client=new Jn(t),this.wireDefaultWebMcpConfirm();for(let a of(n=t.initialArtifacts)!=null?n:[])this.artifacts.set(a.id,{...a,status:"complete"});t.initialSelectedArtifactId!=null&&(this.selectedArtifactId=t.initialSelectedArtifactId),this.messages.length&&this.callbacks.onMessagesChanged([...this.messages]),this.artifacts.size>0&&this.emitArtifactsState(),this.callbacks.onStatusChanged(this.status),this.prefetchRuntypeTts()}prefetchRuntypeTts(){var n,a,s,i,c,l;let t=this.config.textToSpeech;if((t==null?void 0:t.provider)!=="runtype"||t.createEngine)return;let r=(n=t.host)!=null?n:this.config.apiUrl,o=(l=(c=t.agentId)!=null?c:(i=(s=(a=this.config.voiceRecognition)==null?void 0:a.provider)==null?void 0:s.runtype)==null?void 0:i.agentId)!=null?l:this.config.agentId;!r||!o||!this.config.clientToken||Vl().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 xs((t=this.config.voiceRecognition)==null?void 0:t.provider)}isVoiceActive(){return this.voiceActive}getVoiceStatus(){return this.voiceStatus}getVoiceInterruptionMode(){var t;return(t=this.voiceProvider)!=null&&t.getInterruptionMode?this.voiceProvider.getInterruptionMode():"none"}stopVoicePlayback(){var t;(t=this.voiceProvider)!=null&&t.stopPlayback&&this.voiceProvider.stopPlayback()}isBargeInActive(){var t,r,o;return(o=(r=(t=this.voiceProvider)==null?void 0:t.isBargeInActive)==null?void 0:r.call(t))!=null?o:!1}async deactivateBargeIn(){var t;(t=this.voiceProvider)!=null&&t.deactivateBargeIn&&await this.voiceProvider.deactivateBargeIn()}createSpeechEngine(){var o,n,a,s,i,c;let t=this.config.textToSpeech;if(t!=null&&t.createEngine)return t.createEngine();let r=Mn.isSupported()?new Mn({pickVoice:t==null?void 0:t.pickVoice}):null;if((t==null?void 0:t.provider)==="runtype"){let l=(o=t.host)!=null?o:this.config.apiUrl,p=(c=(i=t.agentId)!=null?i:(s=(a=(n=this.config.voiceRecognition)==null?void 0:n.provider)==null?void 0:a.runtype)==null?void 0:s.agentId)!=null?c:this.config.agentId,f=this.config.clientToken,u=t.browserFallback!==!1;if(l&&p&&f)return Vl().then(({RuntypeSpeechEngine:m,FallbackSpeechEngine:x})=>{let b=new m({host:l,agentId:p,clientToken:f,voice:t.voice,prebufferMs:t.prebufferMs,createPlaybackEngine:t.createPlaybackEngine});return u&&r?new x(b,r,{onFallback:L=>console.warn(`[persona] Runtype read-aloud failed; using browser voice. ${L.message}`)}):b});if(u&&r)return f&&console.warn("[persona] textToSpeech.provider 'runtype' is missing an agentId; using the browser voice. Set textToSpeech.agentId (or voiceRecognition.provider.runtype.agentId)."),r}return r}setupVoice(t){var r,o;try{let n=t||this.getVoiceConfigFromConfig();if(!n)throw new Error("Voice configuration not provided");this.voiceProvider=An(n);let s=(o=((r=this.config.voiceRecognition)!=null?r:{}).processingErrorText)!=null?o:"Voice processing failed. Please try again.";this.voiceProvider.onResult(i=>{i.provider!=="runtype"&&i.text&&i.text.trim()&&this.sendMessage(i.text,{viaVoice:!0})}),this.voiceProvider.onTranscript&&this.voiceProvider.onTranscript((i,c,l)=>{if(i==="user"){if(this.pendingVoiceUserMessageId)this.upsertMessage({id:this.pendingVoiceUserMessageId,role:"user",content:c,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!l});else{let p=this.injectMessage({role:"user",content:c,streaming:!1,voiceProcessing:!l});this.pendingVoiceUserMessageId=p.id}if(l){this.pendingVoiceUserMessageId=null;let p=this.injectMessage({role:"assistant",content:"",streaming:!0,voiceProcessing:!0});this.pendingVoiceAssistantMessageId=p.id,this.setStreaming(!0)}}else{if(this.pendingVoiceAssistantMessageId)this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:c,createdAt:new Date().toISOString(),streaming:!l,voiceProcessing:!l});else{let p=this.injectMessage({role:"assistant",content:c,streaming:!l,voiceProcessing:!l});this.pendingVoiceAssistantMessageId=p.id}l&&(this.pendingVoiceAssistantMessageId&&this.ttsSpokenMessageIds.add(this.pendingVoiceAssistantMessageId),this.setStreaming(!1),this.pendingVoiceAssistantMessageId=null)}}),this.voiceProvider.onMetrics&&this.voiceProvider.onMetrics(i=>{var c,l;(l=(c=this.config.voiceRecognition)==null?void 0:c.onMetrics)==null||l.call(c,i)}),this.voiceProvider.onError(i=>{console.error("Voice error:",i),this.pendingVoiceAssistantMessageId&&(this.upsertMessage({id:this.pendingVoiceAssistantMessageId,role:"assistant",content:s,createdAt:new Date().toISOString(),streaming:!1,voiceProcessing:!1}),this.setStreaming(!1),this.pendingVoiceUserMessageId=null,this.pendingVoiceAssistantMessageId=null)}),this.voiceProvider.onStatusChange(i=>{var c,l;this.voiceStatus=i,this.voiceActive=i==="listening",(l=(c=this.callbacks).onVoiceStatusChanged)==null||l.call(c,i)}),this.voiceProvider.connect()}catch(n){console.error("Failed to setup voice:",n)}}async toggleVoice(){if(!this.voiceProvider){console.error("Voice not configured");return}if(this.voiceActive)await this.voiceProvider.stopListening();else{this.stopSpeaking();try{await this.voiceProvider.startListening()}catch(t){console.error("Failed to start voice:",t)}}}cleanupVoice(){this.voiceProvider&&(this.voiceProvider.disconnect(),this.voiceProvider=null),this.voiceActive=!1,this.voiceStatus="disconnected"}getVoiceConfigFromConfig(){var r,o,n,a,s,i,c,l,p,f,u,m;if(!((r=this.config.voiceRecognition)!=null&&r.provider))return;let t=this.config.voiceRecognition.provider;switch(t.type){case"runtype":return{type:"runtype",runtype:{agentId:(a=(n=(o=t.runtype)==null?void 0:o.agentId)!=null?n:this.config.agentId)!=null?a:"",clientToken:(i=(s=t.runtype)==null?void 0:s.clientToken)!=null?i:this.config.clientToken,host:(l=(c=t.runtype)==null?void 0:c.host)!=null?l:this.config.apiUrl,voiceId:(p=t.runtype)==null?void 0:p.voiceId,createPlaybackEngine:(f=t.runtype)==null?void 0:f.createPlaybackEngine}};case"browser":return{type:"browser",browser:{language:((u=t.browser)==null?void 0:u.language)||"en-US",continuous:(m=t.browser)==null?void 0:m.continuous}};case"custom":return{type:"custom",custom:t.custom};default:return}}async initClientSession(){var t,r;if(!this.isClientTokenMode())return null;try{let o=await this.client.initSession();return this.setClientSession(o),o}catch(o){return(r=(t=this.callbacks).onError)==null||r.call(t,o instanceof Error?o:new Error(String(o))),null}}setClientSession(t){if(this.clientSession=t,t.config.welcomeMessage&&this.messages.length===0){let r={id:`welcome-${Date.now()}`,role:"assistant",content:t.config.welcomeMessage,createdAt:new Date().toISOString(),sequence:this.nextSequence()};this.appendMessage(r)}}getClientSession(){var t;return(t=this.clientSession)!=null?t:this.client.getClientSession()}isSessionValid(){let t=this.getClientSession();return t?new Date<t.expiresAt:!1}clearClientSession(){this.clientSession=null,this.client.clearClientSession()}getClient(){return this.client}async submitMessageFeedback(t,r){return this.client.submitMessageFeedback(t,r)}async submitCSATFeedback(t,r){return this.client.submitCSATFeedback(t,r)}async submitNPSFeedback(t,r){return this.client.submitNPSFeedback(t,r)}updateConfig(t){let r={...this.config,...t};if(!Sb(this.config,r)){this.config=r,this.client.updateConfig(r);return}this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear();let o=this.client.getSSEEventCallback();this.config=r,this.client=new Jn(this.config),this.wireDefaultWebMcpConfirm(),o&&this.client.setSSEEventCallback(o)}getMessages(){return[...this.messages]}getStatus(){return this.status}isStreaming(){return this.streaming}injectTestEvent(t){this.handleEvent(t)}injectMessage(t){let{role:r,content:o,llmContent:n,contentParts:a,id:s,createdAt:i,sequence:c,streaming:l=!1,voiceProcessing:p,rawContent:f}=t,m={id:s!=null?s:r==="user"?Pa():r==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:r,content:o,createdAt:i!=null?i:new Date().toISOString(),sequence:c!=null?c:this.nextSequence(),streaming:l,...n!==void 0&&{llmContent:n},...a!==void 0&&{contentParts:a},...p!==void 0&&{voiceProcessing:p},...f!==void 0&&{rawContent:f}};return this.upsertMessage(m),m}injectAssistantMessage(t){return this.injectMessage({...t,role:"assistant"})}injectUserMessage(t){return this.injectMessage({...t,role:"user"})}injectSystemMessage(t){return this.injectMessage({...t,role:"system"})}injectMessageBatch(t){let r=[];for(let o of t){let{role:n,content:a,llmContent:s,contentParts:i,id:c,createdAt:l,sequence:p,streaming:f=!1,voiceProcessing:u,rawContent:m}=o,b={id:c!=null?c:n==="user"?Pa():n==="assistant"?Qn():`system-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:n,content:a,createdAt:l!=null?l:new Date().toISOString(),sequence:p!=null?p:this.nextSequence(),streaming:f,...s!==void 0&&{llmContent:s},...i!==void 0&&{contentParts:i},...u!==void 0&&{voiceProcessing:u},...m!==void 0&&{rawContent:m}};r.push(b)}return this.messages=this.sortMessages([...this.messages,...r]),this.callbacks.onMessagesChanged([...this.messages]),r}injectComponentDirective(t){let{component:r,props:o={},text:n="",llmContent:a,id:s,createdAt:i,sequence:c}=t,l={text:n,component:r,props:o};return this.injectMessage({role:"assistant",content:n,rawContent:JSON.stringify(l),...a!==void 0&&{llmContent:a},...s!==void 0&&{id:s},...i!==void 0&&{createdAt:i},...c!==void 0&&{sequence:c}})}async sendMessage(t,r){var l,p,f,u,m;let o=t.trim();if(!o&&(!(r!=null&&r.contentParts)||r.contentParts.length===0))return;this.stopSpeaking(),(l=this.abortController)==null||l.abort(),this.abortWebMcpResolves();let n=Pa(),a=Qn(),s={id:n,role:"user",content:o||fi,createdAt:new Date().toISOString(),sequence:this.nextSequence(),viaVoice:(r==null?void 0:r.viaVoice)||!1,...(r==null?void 0:r.contentParts)&&r.contentParts.length>0&&{contentParts:r.contentParts}};this.appendMessage(s),this.setStreaming(!0);let i=new AbortController;this.abortController=i;let c=[...this.messages];try{await this.client.dispatch({messages:c,signal:i.signal,assistantMessageId:a},this.handleEvent)}catch(x){let b=x instanceof Error&&(x.name==="AbortError"||x.message.includes("aborted")||x.message.includes("abort"));if(!b){let L=th(x,this.config.errorMessage);if(L){let E={id:a,role:"assistant",createdAt:new Date().toISOString(),content:L,sequence:this.nextSequence()};this.appendMessage(E)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,b||(x instanceof Error?(f=(p=this.callbacks).onError)==null||f.call(p,x):(m=(u=this.callbacks).onError)==null||m.call(u,new Error(String(x))))}}async continueConversation(){var n,a,s,i,c;if(this.streaming)return;(n=this.abortController)==null||n.abort();let t=Qn();this.setStreaming(!0);let r=new AbortController;this.abortController=r;let o=[...this.messages];try{await this.client.dispatch({messages:o,signal:r.signal,assistantMessageId:t},this.handleEvent)}catch(l){let p=l instanceof Error&&(l.name==="AbortError"||l.message.includes("aborted")||l.message.includes("abort"));if(!p){let f=th(l,this.config.errorMessage);if(f){let u={id:t,role:"assistant",createdAt:new Date().toISOString(),content:f,sequence:this.nextSequence()};this.appendMessage(u)}}this.setStatus("idle"),this.setStreaming(!1),this.abortController=null,p||(l instanceof Error?(s=(a=this.callbacks).onError)==null||s.call(a,l):(c=(i=this.callbacks).onError)==null||c.call(i,new Error(String(l))))}}async connectStream(t,r){var n,a,s;if(this.streaming&&!(r!=null&&r.allowReentry))return;r!=null&&r.allowReentry||(n=this.abortController)==null||n.abort();let o=!1;for(let i of this.messages)i.streaming&&(i.streaming=!1,o=!0);o&&this.callbacks.onMessagesChanged([...this.messages]),this.setStreaming(!0);try{await this.client.processStream(t,this.handleEvent,r==null?void 0:r.assistantMessageId)}catch(i){this.setStatus("error"),this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null),(s=(a=this.callbacks).onError)==null||s.call(a,i instanceof Error?i:new Error(String(i)))}}wireDefaultWebMcpConfirm(){let t=this.config.webmcp;(t==null?void 0:t.enabled)===!0&&!t.onConfirm&&this.client.setWebMcpConfirmHandler(r=>this.requestWebMcpApproval(r))}requestWebMcpApproval(t){var n,a,s;try{if(((a=(n=this.config.webmcp)==null?void 0:n.autoApprove)==null?void 0:a.call(n,t))===!0)return Promise.resolve(!0)}catch{}let r={id:`webmcp-${++this.webMcpApprovalSeq}`,status:"pending",agentId:"",executionId:"",toolName:t.toolName,toolType:"webmcp",description:(s=t.description)!=null?s:`Allow the assistant to run ${t.toolName}?`,parameters:t.args},o=`approval-${r.id}`;return this.upsertMessage({id:o,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",approval:r}),new Promise(i=>{this.webMcpApprovalResolvers.set(o,i)})}resolveWebMcpApproval(t,r){let o=this.webMcpApprovalResolvers.get(t);if(!o)return;this.webMcpApprovalResolvers.delete(t);let n=this.messages.find(a=>a.id===t);n!=null&&n.approval&&this.upsertMessage({...n,approval:{...n.approval,status:r,resolvedAt:Date.now()}}),o(r==="approved")}async resolveApproval(t,r,o){var p,f,u,m,x;let n=`approval-${t.id}`,a={...t,status:r,resolvedAt:Date.now()},s=this.messages.find(b=>b.id===n),i={id:n,role:"assistant",content:"",createdAt:(p=s==null?void 0:s.createdAt)!=null?p:new Date().toISOString(),...(s==null?void 0:s.sequence)!==void 0?{sequence:s.sequence}:{},streaming:!1,variant:"approval",approval:a};this.upsertMessage(i),(f=this.abortController)==null||f.abort(),this.abortController=new AbortController,this.setStreaming(!0);let c=this.config.approval,l=c&&typeof c=="object"?c.onDecision:void 0;try{let b;if(l?b=await l({approvalId:t.id,executionId:t.executionId,agentId:t.agentId,toolName:t.toolName},r,o):b=await this.client.resolveApproval({agentId:t.agentId,executionId:t.executionId,approvalId:t.id},r),b){let L=null;if(b instanceof Response){if(!b.ok){let E=await b.json().catch(()=>null);throw new Error((u=E==null?void 0:E.error)!=null?u:`Approval request failed: ${b.status}`)}L=b.body}else b instanceof ReadableStream&&(L=b);L?await this.connectStream(L,{allowReentry:!0}):(r==="denied"&&this.appendMessage({id:`denial-${t.id}`,role:"assistant",content:"Tool execution was denied by user.",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.setStreaming(!1),this.abortController=null)}else this.setStreaming(!1),this.abortController=null}catch(b){let L=b instanceof Error&&(b.name==="AbortError"||b.message.includes("aborted")||b.message.includes("abort"));this.setStreaming(!1),this.abortController=null,L||(x=(m=this.callbacks).onError)==null||x.call(m,b instanceof Error?b:new Error(String(b)))}}persistAskUserQuestionProgress(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,askUserQuestionAnswers:r.answers,askUserQuestionIndex:r.currentIndex}})}markAskUserQuestionResolved(t,r){let o=this.messages.find(n=>n.id===t.id);o&&this.upsertMessage({...o,agentMetadata:{...o.agentMetadata,awaitingLocalTool:!1,askUserQuestionAnswered:!0,...r?{askUserQuestionAnswers:r}:{}}})}async resolveAskUserQuestion(t,r){var p,f,u,m,x,b,L,E,A,T,y,S;let o=this.messages.find(v=>v.id===t.id);if(((p=o==null?void 0:o.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0)return;let n=(f=t.agentMetadata)==null?void 0:f.executionId,a=(u=t.toolCall)==null?void 0:u.name;if(!n||!a){(x=(m=this.callbacks).onError)==null||x.call(m,new Error("resolveAskUserQuestion: message is missing executionId or toolCall.name"));return}let s=typeof r=="string"?void 0:r;if(s===void 0&&typeof r=="string"){let v=(b=t.toolCall)==null?void 0:b.args,M=Array.isArray(v==null?void 0:v.questions)?v.questions:[];if(M.length===1){let W=typeof((L=M[0])==null?void 0:L.question)=="string"?M[0].question:"";W&&(s={[W]:r})}}this.markAskUserQuestionResolved(t,s),(E=this.abortController)==null||E.abort(),this.abortController=new AbortController,this.setStreaming(!0);let i=t.toolCall.id,c=(A=t.toolCall)==null?void 0:A.args,l=Array.isArray(c==null?void 0:c.questions)?c.questions:[];if(l.length===0){let v=typeof r=="string"?r:Object.entries(r).map(([M,W])=>`${M}: ${Array.isArray(W)?W.join(", "):W}`).join(" | ");this.appendMessage({id:`ask-user-answer-${i}`,role:"user",content:v,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})}else{let v=s!=null?s:{};l.forEach((M,W)=>{let H=typeof(M==null?void 0:M.question)=="string"?M.question:"";if(!H)return;let I=v[H],D=Array.isArray(I)?I.join(", "):typeof I=="string"?I:"";this.appendMessage({id:`ask-user-q-${i}-${W}`,role:"assistant",content:H,createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()}),this.appendMessage({id:`ask-user-a-${i}-${W}`,role:"user",content:D||"*Skipped*",createdAt:new Date().toISOString(),streaming:!1,sequence:this.nextSequence()})})}try{let v=await this.client.resumeFlow(n,{[a]:r});if(!v.ok){let M=await v.json().catch(()=>null);throw new Error((T=M==null?void 0:M.error)!=null?T:`Resume failed: ${v.status}`)}v.body?await this.connectStream(v.body,{allowReentry:!0}):(this.setStreaming(!1),this.abortController=null)}catch(v){let M=v instanceof Error&&(v.name==="AbortError"||v.message.includes("aborted")||v.message.includes("abort"));this.setStreaming(!1),this.abortController=null,M||(S=(y=this.callbacks).onError)==null||S.call(y,v instanceof Error?v:new Error(String(v)))}}enqueueWebMcpAwait(t){var a,s;let r=(a=t.agentMetadata)==null?void 0:a.executionId,o=(s=t.toolCall)==null?void 0:s.id;if(!r||!o){let i=this.webMcpEpoch;queueMicrotask(()=>{i===this.webMcpEpoch&&this.resolveWebMcpToolCall(t)});return}let n=this.webMcpAwaitBatches.get(r);n||(n={snapshots:[],seen:new Set},this.webMcpAwaitBatches.set(r,n)),!n.seen.has(o)&&(n.seen.add(o),n.snapshots.push(t))}scheduleWebMcpBatchFlush(){if(this.webMcpAwaitBatches.size===0)return;let t=this.webMcpEpoch;queueMicrotask(()=>{if(t===this.webMcpEpoch)for(let r of[...this.webMcpAwaitBatches.keys()])this.flushWebMcpAwaitBatch(r)})}flushWebMcpAwaitBatch(t){let r=this.webMcpAwaitBatches.get(t);if(!r)return;this.webMcpAwaitBatches.delete(t);let{snapshots:o}=r;o.length===1?this.resolveWebMcpToolCall(o[0]):o.length>1&&this.resolveWebMcpToolCallBatch(t,o)}resolveWebMcpToolStartedAt(t){var n,a;let r=this.messages.find(s=>s.id===t.id),o=[(n=r==null?void 0:r.toolCall)==null?void 0:n.startedAt,(a=t.toolCall)==null?void 0:a.startedAt];for(let s of o)if(typeof s=="number"&&Number.isFinite(s))return s;return Date.now()}isSuggestRepliesAlreadyResolved(t){var o,n;if(((o=t.toolCall)==null?void 0:o.name)!==wo)return!1;let r=this.messages.find(a=>a.id===t.id);return((n=(r!=null?r:t).agentMetadata)==null?void 0:n.suggestRepliesResolved)===!0}markWebMcpToolRunning(t){let r=this.resolveWebMcpToolStartedAt(t);return this.upsertMessage({...t,streaming:!0,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1},toolCall:t.toolCall?{...t.toolCall,status:"running",startedAt:r,completedAt:void 0,duration:void 0,durationMs:void 0}:t.toolCall}),r}markWebMcpToolComplete(t,r,o,n=Date.now(),a){this.messages.some(s=>s.id===t.id)&&this.upsertMessage({...t,streaming:!1,agentMetadata:{...t.agentMetadata,awaitingLocalTool:!1,...a},toolCall:t.toolCall?{...t.toolCall,status:"complete",result:r,startedAt:o,completedAt:n,duration:void 0,durationMs:Math.max(0,n-o)}:t.toolCall})}async resolveWebMcpToolCallBatch(t,r){var c,l,p,f;let o=[],n=[],a=new AbortController;this.webMcpResolveControllers.add(a),this.setStreaming(!0);let s=await Promise.all(r.map(async u=>{var S,v,M,W,H,I,D;let m=(S=u.toolCall)==null?void 0:S.name,x=(v=u.toolCall)==null?void 0:v.id;if(!m||!x)return null;let b=`${t}:${x}`;if(this.webMcpInflightKeys.has(b)||this.webMcpResolvedKeys.has(b)||this.isSuggestRepliesAlreadyResolved(u))return null;this.webMcpInflightKeys.add(b),o.push(b);let L=this.markWebMcpToolRunning(u),E=(W=(M=u.agentMetadata)==null?void 0:M.webMcpToolCallId)!=null?W:m;if(m===wo)return{dedupeKey:b,resumeKey:E,output:Bl(),toolMessage:u,startedAt:L,completedAt:Date.now()};let A=new AbortController;this.webMcpResolveControllers.add(A),n.push(A);let T=this.client.executeWebMcpToolCall(m,(H=u.toolCall)==null?void 0:H.args,A.signal),y;if(!T)y={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]};else try{y=await T}catch(O){let J=O instanceof Error&&(O.name==="AbortError"||O.message.includes("aborted")||O.message.includes("abort"));return J||(D=(I=this.callbacks).onError)==null||D.call(I,O instanceof Error?O:new Error(String(O))),this.markWebMcpToolComplete(u,ys(J?"Aborted by cancel()":rh(O)),L),this.webMcpInflightKeys.delete(b),null}return A.signal.aborted?(this.markWebMcpToolComplete(u,ys("Aborted by cancel()"),L),this.webMcpInflightKeys.delete(b),null):{dedupeKey:b,resumeKey:E,output:y,toolMessage:u,startedAt:L,completedAt:Date.now()}})),i=[];try{if(i=s.filter(x=>x!==null),i.length===0)return;let u={};for(let x of i)u[x.resumeKey]=x.output;let m=await this.client.resumeFlow(t,u,{signal:a.signal});if(!m.ok){let x=await m.json().catch(()=>null);throw new Error((c=x==null?void 0:x.error)!=null?c:`Resume failed: ${m.status}`)}for(let x of i)this.webMcpResolvedKeys.add(x.dedupeKey),this.markWebMcpToolComplete(x.toolMessage,x.output,x.startedAt,x.completedAt,((l=x.toolMessage.toolCall)==null?void 0:l.name)===wo?{suggestRepliesResolved:!0}:void 0);m.body&&await this.connectStream(m.body,{allowReentry:!0})}catch(u){if(!(u instanceof Error&&(u.name==="AbortError"||u.message.includes("aborted")||u.message.includes("abort"))))(f=(p=this.callbacks).onError)==null||f.call(p,u instanceof Error?u:new Error(String(u)));else for(let x of i)this.markWebMcpToolComplete(x.toolMessage,ys("Aborted by cancel()"),x.startedAt)}finally{for(let u of o)this.webMcpInflightKeys.delete(u);for(let u of n)this.webMcpResolveControllers.delete(u);this.webMcpResolveControllers.delete(a),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resolveWebMcpToolCall(t){var x,b,L,E,A,T,y,S,v,M,W,H;let r=(x=t.agentMetadata)==null?void 0:x.executionId,o=(b=t.toolCall)==null?void 0:b.name,n=(L=t.toolCall)==null?void 0:L.id;if(!r){(A=(E=this.callbacks).onError)==null||A.call(E,new Error("WebMCP step_await missing executionId: dispatch left paused."));return}if(!o)return;if(!n){let I=`${r}:__no_tool_id__:${o}`;if(this.webMcpInflightKeys.has(I)||this.webMcpResolvedKeys.has(I))return;this.webMcpInflightKeys.add(I);try{await this.resumeWithToolOutput(r,o,{isError:!0,content:[{type:"text",text:"WebMCP step_await missing toolCall.id: cannot execute the page tool."}]}),this.webMcpResolvedKeys.add(I)}catch(D){(y=(T=this.callbacks).onError)==null||y.call(T,D instanceof Error?D:new Error(String(D)))}finally{this.webMcpInflightKeys.delete(I)}return}let a=`${r}:${n}`;if(this.webMcpInflightKeys.has(a)||this.webMcpResolvedKeys.has(a)||this.isSuggestRepliesAlreadyResolved(t))return;this.webMcpInflightKeys.add(a);let s=this.markWebMcpToolRunning(t),i=new AbortController;this.webMcpResolveControllers.add(i);let{signal:c}=i;this.setStreaming(!0);let l=o===wo,p=(S=t.toolCall)==null?void 0:S.args,f=l?null:this.client.executeWebMcpToolCall(o,p,c),u="execute",m=s;try{let I;if(l?I=Bl():f?I=await f:I={isError:!0,content:[{type:"text",text:"WebMCP not enabled on this widget."}]},m=Date.now(),c.aborted){this.markWebMcpToolComplete(t,ys("Aborted by cancel()"),s);return}let D=(M=(v=t.agentMetadata)==null?void 0:v.webMcpToolCallId)!=null?M:o;u="resume",await this.resumeWithToolOutput(r,D,I,{onHttpOk:()=>{this.webMcpResolvedKeys.add(a),this.markWebMcpToolComplete(t,I,s,m,l?{suggestRepliesResolved:!0}:void 0)},signal:c})}catch(I){let D=I instanceof Error&&(I.name==="AbortError"||I.message.includes("aborted")||I.message.includes("abort"));(u==="execute"||D||c.aborted)&&this.markWebMcpToolComplete(t,ys(D||c.aborted?"Aborted by cancel()":rh(I)),s),D||(H=(W=this.callbacks).onError)==null||H.call(W,I instanceof Error?I:new Error(String(I)))}finally{this.webMcpInflightKeys.delete(a),this.webMcpResolveControllers.delete(i),this.webMcpResolveControllers.size===0&&!this.abortController&&this.setStreaming(!1)}}async resumeWithToolOutput(t,r,o,n){var s,i;let a=await this.client.resumeFlow(t,{[r]:o},{signal:n==null?void 0:n.signal});if(!a.ok){let c=await a.json().catch(()=>null);throw new Error((s=c==null?void 0:c.error)!=null?s:`Resume failed: ${a.status}`)}(i=n==null?void 0:n.onHttpOk)==null||i.call(n),a.body?await this.connectStream(a.body,{allowReentry:!0}):this.webMcpResolveControllers.size===0&&(this.setStreaming(!1),this.abortController=null)}abortWebMcpResolves(){for(let t of this.webMcpResolveControllers)t.abort();this.webMcpResolveControllers.clear();for(let t of[...this.webMcpApprovalResolvers.keys()])this.resolveWebMcpApproval(t,"denied");this.webMcpAwaitBatches.clear(),this.webMcpEpoch++}cancel(){var t;(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.stopSpeaking(),this.stopVoicePlayback(),this.setStreaming(!1),this.setStatus("idle")}clearMessages(){var t;this.stopSpeaking(),(t=this.abortController)==null||t.abort(),this.abortController=null,this.abortWebMcpResolves(),this.messages=[],this.agentExecution=null,this.clearArtifactState(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.client.resetClientToolsFingerprint(),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}getArtifacts(){return[...this.artifacts.values()]}getArtifactById(t){return this.artifacts.get(t)}getSelectedArtifactId(){return this.selectedArtifactId}selectArtifact(t){this.selectedArtifactId=t,this.emitArtifactsState()}clearArtifacts(){this.clearArtifactState()}upsertArtifact(t){var n;let r=t.id||`art_${Date.now().toString(36)}_${Math.random().toString(36).slice(2,9)}`;if(t.artifactType==="markdown"){let a={id:r,artifactType:"markdown",title:t.title,status:"complete",markdown:t.content};return this.artifacts.set(r,a),this.selectedArtifactId=r,this.emitArtifactsState(),a}let o={id:r,artifactType:"component",title:t.title,status:"complete",component:t.component,props:(n=t.props)!=null?n:{}};return this.artifacts.set(r,o),this.selectedArtifactId=r,this.emitArtifactsState(),o}clearArtifactState(){this.artifacts.size===0&&this.selectedArtifactId===null||(this.artifacts.clear(),this.selectedArtifactId=null,this.emitArtifactsState())}emitArtifactsState(){var t,r;(r=(t=this.callbacks).onArtifactsState)==null||r.call(t,{artifacts:[...this.artifacts.values()],selectedId:this.selectedArtifactId})}applyArtifactStreamEvent(t){var r,o;switch(t.type){case"artifact_start":{t.artifactType==="markdown"?this.artifacts.set(t.id,{id:t.id,artifactType:"markdown",title:t.title,status:"streaming",markdown:""}):this.artifacts.set(t.id,{id:t.id,artifactType:"component",title:t.title,status:"streaming",component:(r=t.component)!=null?r:"",props:{}}),this.selectedArtifactId=t.id;break}case"artifact_delta":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="markdown"&&(n.markdown=((o=n.markdown)!=null?o:"")+t.artDelta);break}case"artifact_update":{let n=this.artifacts.get(t.id);(n==null?void 0:n.artifactType)==="component"&&(n.props={...n.props,...t.props},t.component&&(n.component=t.component));break}case"artifact_complete":{let n=this.artifacts.get(t.id);n&&(n.status="complete");break}default:return}this.emitArtifactsState()}hydrateMessages(t){var r;(r=this.abortController)==null||r.abort(),this.abortController=null,this.abortWebMcpResolves(),this.webMcpInflightKeys.clear(),this.webMcpResolvedKeys.clear(),this.messages=this.sortMessages(t.map(o=>{var n;return{...o,streaming:!1,sequence:(n=o.sequence)!=null?n:this.nextSequence()}})),this.setStreaming(!1),this.setStatus("idle"),this.callbacks.onMessagesChanged([...this.messages])}hydrateArtifacts(t,r=null){this.artifacts.clear();for(let o of t)this.artifacts.set(o.id,{...o,status:"complete"});this.selectedArtifactId=r,this.emitArtifactsState()}setStatus(t){this.status!==t&&(this.status=t,this.callbacks.onStatusChanged(t))}setStreaming(t){if(this.streaming===t)return;let r=this.streaming;this.streaming=t,this.callbacks.onStreamingChanged(t),r&&!t&&this.speakLatestAssistantMessage()}speakLatestAssistantMessage(){let t=this.config.textToSpeech;if(!(t!=null&&t.enabled)||!(!t.provider||t.provider==="browser"||t.provider==="runtype"&&t.browserFallback))return;let o=[...this.messages].reverse().find(a=>a.role==="assistant"&&a.content&&!a.voiceProcessing);if(!o)return;if(this.ttsSpokenMessageIds.has(o.id)){this.ttsSpokenMessageIds.delete(o.id);return}let n=Ul(o.content);n.trim()&&this.readAloud.play(o.id,{text:n,voice:t.voice,rate:t.rate,pitch:t.pitch})}static pickBestVoice(t){return Ra(t)}toggleReadAloud(t){let r=this.messages.find(a=>a.id===t);if(!r||r.role!=="assistant")return;let o=Ul(r.content||"");if(!o.trim())return;let n=this.config.textToSpeech;this.readAloud.toggle(t,{text:o,voice:n==null?void 0:n.voice,rate:n==null?void 0:n.rate,pitch:n==null?void 0:n.pitch})}getReadAloudState(t){return this.readAloud.stateFor(t)}onReadAloudChange(t){return this.readAloud.onChange(t)}stopSpeaking(){this.readAloud.stop(),typeof window!="undefined"&&"speechSynthesis"in window&&window.speechSynthesis.cancel()}appendMessage(t){let r=this.ensureSequence(t);this.messages=this.sortMessages([...this.messages,r]),this.callbacks.onMessagesChanged([...this.messages])}upsertMessage(t){let r=this.ensureSequence(t),o=this.messages.findIndex(n=>n.id===r.id);if(o===-1){this.appendMessage(r);return}this.messages=this.messages.map((n,a)=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,W;if(a!==o)return n;let s={...n,...r};if(((p=n.agentMetadata)==null?void 0:p.askUserQuestionAnswered)===!0&&r.agentMetadata&&(s.agentMetadata={...r.agentMetadata,askUserQuestionAnswered:!0,...n.agentMetadata.askUserQuestionAnswers?{askUserQuestionAnswers:n.agentMetadata.askUserQuestionAnswers}:{},awaitingLocalTool:!1}),((f=n.agentMetadata)==null?void 0:f.suggestRepliesResolved)===!0&&r.agentMetadata&&(s.agentMetadata={...(u=s.agentMetadata)!=null?u:r.agentMetadata,suggestRepliesResolved:!0,awaitingLocalTool:!1}),n.approval&&r.approval&&n.approval.id===r.approval.id){let H=n.approval,I=r.approval;s.approval={...H,...I,executionId:I.executionId||H.executionId,toolName:I.toolName||H.toolName,description:I.description||H.description,toolType:(m=I.toolType)!=null?m:H.toolType,reason:(x=I.reason)!=null?x:H.reason,parameters:(b=I.parameters)!=null?b:H.parameters}}let i=(L=r.toolCall)==null?void 0:L.name,c=(E=r.agentMetadata)==null?void 0:E.executionId,l=(A=r.toolCall)==null?void 0:A.id;if(i&&oh(i)&&c&&l&&((T=r.agentMetadata)==null?void 0:T.awaitingLocalTool)===!0){let H=`${c}:${l}`,I=this.webMcpInflightKeys.has(H),D=this.webMcpResolvedKeys.has(H),O=(y=n.toolCall)==null?void 0:y.name,J=((S=n.agentMetadata)==null?void 0:S.executionId)===c&&((v=n.toolCall)==null?void 0:v.id)===l&&O!==void 0&&oh(O)&&((M=n.toolCall)==null?void 0:M.status)==="complete";(I||D||J)&&(s.agentMetadata={...(W=s.agentMetadata)!=null?W:{},awaitingLocalTool:!1},s.toolCall=n.toolCall,s.streaming=n.streaming)}return s}),this.messages=this.sortMessages(this.messages),this.callbacks.onMessagesChanged([...this.messages])}ensureSequence(t){return t.sequence!==void 0?{...t}:{...t,sequence:this.nextSequence()}}nextSequence(){return this.sequenceCounter++}sortMessages(t){return[...t].sort((r,o)=>{var c,l;let n=new Date(r.createdAt).getTime(),a=new Date(o.createdAt).getTime();if(!Number.isNaN(n)&&!Number.isNaN(a)&&n!==a)return n-a;let s=(c=r.sequence)!=null?c:0,i=(l=o.sequence)!=null?l:0;return s!==i?s-i:r.id.localeCompare(o.id)})}};var zl=[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2"}]];var $l=[["path",{d:"M12 5v14"}],["path",{d:"m19 12-7 7-7-7"}]];var jl=[["path",{d:"m12 19-7-7 7-7"}],["path",{d:"M19 12H5"}]];var Gl=[["path",{d:"M5 12h14"}],["path",{d:"m12 5 7 7-7 7"}]];var Kl=[["path",{d:"M7 7h10v10"}],["path",{d:"M7 17 17 7"}]];var Xl=[["path",{d:"m5 12 7-7 7 7"}],["path",{d:"M12 19V5"}]];var Jl=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8"}]];var Ql=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M4.929 4.929 19.07 19.071"}]];var Yl=[["path",{d:"M10.268 21a2 2 0 0 0 3.464 0"}],["path",{d:"M3.262 15.326A1 1 0 0 0 4 17h16a1 1 0 0 0 .74-1.673C19.41 13.956 18 12.499 18 8A6 6 0 0 0 6 8c0 4.499-1.411 5.956-2.738 7.326"}]];var Zl=[["path",{d:"M17 3a2 2 0 0 1 2 2v15a1 1 0 0 1-1.496.868l-4.512-2.578a2 2 0 0 0-1.984 0l-4.512 2.578A1 1 0 0 1 5 20V5a2 2 0 0 1 2-2z"}]];var ed=[["path",{d:"M12 8V4H8"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2"}],["path",{d:"M2 14h2"}],["path",{d:"M20 14h2"}],["path",{d:"M15 13v2"}],["path",{d:"M9 13v2"}]];var td=[["path",{d:"M12 10h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M12 6h.01"}],["path",{d:"M16 10h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M16 6h.01"}],["path",{d:"M8 10h.01"}],["path",{d:"M8 14h.01"}],["path",{d:"M8 6h.01"}],["path",{d:"M9 22v-3a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2"}]];var rd=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}],["path",{d:"M8 14h.01"}],["path",{d:"M12 14h.01"}],["path",{d:"M16 14h.01"}],["path",{d:"M8 18h.01"}],["path",{d:"M12 18h.01"}],["path",{d:"M16 18h.01"}]];var od=[["path",{d:"M8 2v4"}],["path",{d:"M16 2v4"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2"}],["path",{d:"M3 10h18"}]];var nd=[["path",{d:"M13.997 4a2 2 0 0 1 1.76 1.05l.486.9A2 2 0 0 0 18.003 7H20a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9a2 2 0 0 1 2-2h1.997a2 2 0 0 0 1.759-1.048l.489-.904A2 2 0 0 1 10.004 4z"}],["circle",{cx:"12",cy:"13",r:"3"}]];var ad=[["path",{d:"M20 6 9 17l-5-5"}]];var sd=[["path",{d:"m6 9 6 6 6-6"}]];var id=[["path",{d:"m15 18-6-6 6-6"}]];var ld=[["path",{d:"m9 18 6-6-6-6"}]];var dd=[["path",{d:"m18 15-6-6-6 6"}]];var xi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m9 12 2 2 4-4"}]];var yi=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"m15 9-6 6"}],["path",{d:"m9 9 6 6"}]];var cd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4"}],["path",{d:"M21 14H11"}],["path",{d:"m15 10-4 4 4 4"}]];var pd=[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2"}]];var ud=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 6v6l4 2"}]];var fd=[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"}]];var md=[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10"}]];var gd=[["line",{x1:"12",x2:"12",y1:"2",y2:"22"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6"}]];var hd=[["path",{d:"M12 15V3"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}],["path",{d:"m7 10 5 5 5-5"}]];var bi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"12",cy:"5",r:"1"}],["circle",{cx:"12",cy:"19",r:"1"}]];var vi=[["circle",{cx:"12",cy:"12",r:"1"}],["circle",{cx:"19",cy:"12",r:"1"}],["circle",{cx:"5",cy:"12",r:"1"}]];var xd=[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143"}],["path",{d:"m2 2 20 20"}]];var yd=[["path",{d:"M15 3h6v6"}],["path",{d:"M10 14 21 3"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"}]];var bd=[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0"}],["circle",{cx:"12",cy:"12",r:"3"}]];var vd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 12.5 8 15l2 2.5"}],["path",{d:"m14 12.5 2 2.5-2 2.5"}]];var wd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M8 13h2"}],["path",{d:"M14 13h2"}],["path",{d:"M8 17h2"}],["path",{d:"M14 17h2"}]];var Cd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}],["path",{d:"M10 9H8"}],["path",{d:"M16 13H8"}],["path",{d:"M16 17H8"}]];var Sd=[["path",{d:"M6 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h8a2.4 2.4 0 0 1 1.704.706l3.588 3.588A2.4 2.4 0 0 1 20 8v12a2 2 0 0 1-2 2z"}],["path",{d:"M14 2v5a1 1 0 0 0 1 1h5"}]];var Ad=[["path",{d:"M15 2h-4a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8"}],["path",{d:"M16.706 2.706A2.4 2.4 0 0 0 15 2v5a1 1 0 0 0 1 1h5a2.4 2.4 0 0 0-.706-1.706z"}],["path",{d:"M5 7a2 2 0 0 0-2 2v11a2 2 0 0 0 2 2h8a2 2 0 0 0 1.732-1"}]];var Md=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}],["path",{d:"M7 3v18"}],["path",{d:"M3 7.5h4"}],["path",{d:"M3 12h18"}],["path",{d:"M3 16.5h4"}],["path",{d:"M17 3v18"}],["path",{d:"M17 7.5h4"}],["path",{d:"M17 16.5h4"}]];var Td=[["path",{d:"M4 22V4a1 1 0 0 1 .4-.8A6 6 0 0 1 8 2c3 0 5 2 7.333 2q2 0 3.067-.8A1 1 0 0 1 20 4v10a1 1 0 0 1-.4.8A6 6 0 0 1 16 16c-3 0-5-2-8-2a6 6 0 0 0-4 1.528"}]];var Ed=[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2"}]];var kd=[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"}]];var wi=[["path",{d:"M10 20a1 1 0 0 0 .553.895l2 1A1 1 0 0 0 14 21v-7a2 2 0 0 1 .517-1.341L21.74 4.67A1 1 0 0 0 21 3H3a1 1 0 0 0-.742 1.67l7.225 7.989A2 2 0 0 1 10 14z"}]];var Ld=[["path",{d:"M12 7v14"}],["path",{d:"M20 11v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8"}],["path",{d:"M7.5 7a1 1 0 0 1 0-5A4.8 8 0 0 1 12 7a4.8 8 0 0 1 4.5-5 1 1 0 0 1 0 5"}],["rect",{x:"3",y:"7",width:"18",height:"4",rx:"1"}]];var Pd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"}],["path",{d:"M2 12h20"}]];var Rd=[["line",{x1:"4",x2:"20",y1:"9",y2:"9"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21"}]];var Id=[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3"}]];var Wd=[["path",{d:"M2 9.5a5.5 5.5 0 0 1 9.591-3.676.56.56 0 0 0 .818 0A5.49 5.49 0 0 1 22 9.5c0 2.29-1.5 4-3 5.5l-5.492 5.313a2 2 0 0 1-3 .019L5 15c-1.5-1.5-3-3.2-3-5.5"}]];var Hd=[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}],["path",{d:"M3 3v5h5"}],["path",{d:"M12 7v5l4 2"}]];var Ci=[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-6a2 2 0 0 1 2.582 0l7 6A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"}]];var Bd=[["path",{d:"M16 5h6"}],["path",{d:"M19 2v6"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}],["circle",{cx:"9",cy:"9",r:"2"}]];var Dd=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2"}],["circle",{cx:"9",cy:"9",r:"2"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21"}]];var Fd=[["circle",{cx:"12",cy:"12",r:"10"}],["path",{d:"M12 16v-4"}],["path",{d:"M12 8h.01"}]];var Nd=[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4"}],["path",{d:"m21 2-9.6 9.6"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5"}]];var Od=[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71"}]];var Si=[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56"}]];var _d=[["path",{d:"M12 2v4"}],["path",{d:"m16.2 7.8 2.9-2.9"}],["path",{d:"M18 12h4"}],["path",{d:"m16.2 16.2 2.9 2.9"}],["path",{d:"M12 18v4"}],["path",{d:"m4.9 19.1 2.9-2.9"}],["path",{d:"M2 12h4"}],["path",{d:"m4.9 4.9 2.9 2.9"}]];var Ud=[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4"}]];var qd=[["path",{d:"m22 7-8.991 5.727a2 2 0 0 1-2.009 0L2 7"}],["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2"}]];var Vd=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}],["circle",{cx:"12",cy:"10",r:"3"}]];var zd=[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3"}]];var $d=[["path",{d:"M4 5h16"}],["path",{d:"M4 12h16"}],["path",{d:"M4 19h16"}]];var jd=[["path",{d:"M2.992 16.342a2 2 0 0 1 .094 1.167l-1.065 3.29a1 1 0 0 0 1.236 1.168l3.413-.998a2 2 0 0 1 1.099.092 10 10 0 1 0-4.777-4.719"}]];var Gd=[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z"}]];var Kd=[["path",{d:"M12 19v3"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3"}]];var Xd=[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3"}]];var Jd=[["path",{d:"M5 12h14"}]];var Qd=[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21"}]];var Yd=[["path",{d:"M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401"}]];var Zd=[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z"}],["path",{d:"M12 22V12"}],["polyline",{points:"3.29 7 12 12 20.71 7"}],["path",{d:"m7.5 4.27 9 5.15"}]];var ec=[["path",{d:"m16 6-8.414 8.586a2 2 0 0 0 2.829 2.829l8.414-8.586a4 4 0 1 0-5.657-5.657l-8.379 8.551a6 6 0 1 0 8.485 8.485l8.379-8.551"}]];var tc=[["rect",{x:"14",y:"3",width:"5",height:"18",rx:"1"}],["rect",{x:"5",y:"3",width:"5",height:"18",rx:"1"}]];var rc=[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z"}],["path",{d:"m15 5 4 4"}]];var oc=[["line",{x1:"19",x2:"5",y1:"5",y2:"19"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5"}]];var nc=[["path",{d:"M13.832 16.568a1 1 0 0 0 1.213-.303l.355-.465A2 2 0 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 6.392 6.384"}]];var ac=[["path",{d:"M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z"}]];var sc=[["path",{d:"M5 12h14"}],["path",{d:"M12 5v14"}]];var ic=[["path",{d:"M12 17V7"}],["path",{d:"M16 8h-6a2 2 0 0 0 0 4h4a2 2 0 0 1 0 4H8"}],["path",{d:"M4 3a1 1 0 0 1 1-1 1.3 1.3 0 0 1 .7.2l.933.6a1.3 1.3 0 0 0 1.4 0l.934-.6a1.3 1.3 0 0 1 1.4 0l.933.6a1.3 1.3 0 0 0 1.4 0l.933-.6a1.3 1.3 0 0 1 1.4 0l.934.6a1.3 1.3 0 0 0 1.4 0l.933-.6A1.3 1.3 0 0 1 19 2a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1 1.3 1.3 0 0 1-.7-.2l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.934.6a1.3 1.3 0 0 1-1.4 0l-.933-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-1.4 0l-.934-.6a1.3 1.3 0 0 0-1.4 0l-.933.6a1.3 1.3 0 0 1-.7.2 1 1 0 0 1-1-1z"}]];var lc=[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16"}],["path",{d:"M8 16H3v5"}]];var dc=[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"}],["path",{d:"M21 3v5h-5"}]];var cc=[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7"}]];var pc=[["path",{d:"m21 21-4.34-4.34"}],["circle",{cx:"11",cy:"11",r:"8"}]];var uc=[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z"}],["path",{d:"m21.854 2.147-10.94 10.939"}]];var fc=[["path",{d:"M9.671 4.136a2.34 2.34 0 0 1 4.659 0 2.34 2.34 0 0 0 3.319 1.915 2.34 2.34 0 0 1 2.33 4.033 2.34 2.34 0 0 0 0 3.831 2.34 2.34 0 0 1-2.33 4.033 2.34 2.34 0 0 0-3.319 1.915 2.34 2.34 0 0 1-4.659 0 2.34 2.34 0 0 0-3.32-1.915 2.34 2.34 0 0 1-2.33-4.033 2.34 2.34 0 0 0 0-3.831A2.34 2.34 0 0 1 6.35 6.051a2.34 2.34 0 0 0 3.319-1.915"}],["circle",{cx:"12",cy:"12",r:"3"}]];var mc=[["path",{d:"M12 2v13"}],["path",{d:"m16 6-4-4-4 4"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8"}]];var gc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"M12 8v4"}],["path",{d:"M12 16h.01"}]];var hc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m9 12 2 2 4-4"}]];var Ai=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}],["path",{d:"m14.5 9.5-5 5"}],["path",{d:"m9.5 9.5 5 5"}]];var xc=[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z"}]];var yc=[["path",{d:"M16 10a4 4 0 0 1-8 0"}],["path",{d:"M3.103 6.034h17.794"}],["path",{d:"M3.4 5.467a2 2 0 0 0-.4 1.2V20a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6.667a2 2 0 0 0-.4-1.2l-2-2.667A2 2 0 0 0 17 2H7a2 2 0 0 0-1.6.8z"}]];var bc=[["circle",{cx:"8",cy:"21",r:"1"}],["circle",{cx:"19",cy:"21",r:"1"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"}]];var vc=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2"}],["path",{d:"M12 18h.01"}]];var Mi=[["path",{d:"M11.017 2.814a1 1 0 0 1 1.966 0l1.051 5.558a2 2 0 0 0 1.594 1.594l5.558 1.051a1 1 0 0 1 0 1.966l-5.558 1.051a2 2 0 0 0-1.594 1.594l-1.051 5.558a1 1 0 0 1-1.966 0l-1.051-5.558a2 2 0 0 0-1.594-1.594l-5.558-1.051a1 1 0 0 1 0-1.966l5.558-1.051a2 2 0 0 0 1.594-1.594z"}],["path",{d:"M20 2v4"}],["path",{d:"M22 4h-4"}],["circle",{cx:"4",cy:"20",r:"2"}]];var wc=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}]];var Cc=[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z"}]];var Sc=[["path",{d:"M15 21v-5a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v5"}],["path",{d:"M17.774 10.31a1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.451 0 1.12 1.12 0 0 0-1.548 0 2.5 2.5 0 0 1-3.452 0 1.12 1.12 0 0 0-1.549 0 2.5 2.5 0 0 1-3.77-3.248l2.889-4.184A2 2 0 0 1 7 2h10a2 2 0 0 1 1.653.873l2.895 4.192a2.5 2.5 0 0 1-3.774 3.244"}],["path",{d:"M4 10.95V19a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8.05"}]];var Ac=[["circle",{cx:"12",cy:"12",r:"4"}],["path",{d:"M12 2v2"}],["path",{d:"M12 20v2"}],["path",{d:"m4.93 4.93 1.41 1.41"}],["path",{d:"m17.66 17.66 1.41 1.41"}],["path",{d:"M2 12h2"}],["path",{d:"M20 12h2"}],["path",{d:"m6.34 17.66-1.41 1.41"}],["path",{d:"m19.07 4.93-1.41 1.41"}]];var Mc=[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor"}]];var Tc=[["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"}],["path",{d:"M17 14V2"}]];var Ec=[["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"}],["path",{d:"M7 10v12"}]];var kc=[["line",{x1:"10",x2:"14",y1:"2",y2:"2"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11"}],["circle",{cx:"12",cy:"14",r:"8"}]];var Lc=[["path",{d:"M10 11v6"}],["path",{d:"M14 11v6"}],["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Pc=[["path",{d:"M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6"}],["path",{d:"M3 6h18"}],["path",{d:"M8 6V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"}]];var Ti=[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3"}],["path",{d:"M12 9v4"}],["path",{d:"M12 17h.01"}]];var Rc=[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2"}],["path",{d:"M15 18H9"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14"}],["circle",{cx:"17",cy:"18",r:"2"}],["circle",{cx:"7",cy:"18",r:"2"}]];var Ic=[["path",{d:"M12 3v12"}],["path",{d:"m17 8-5-5-5 5"}],["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}]];var Wc=[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2"}],["circle",{cx:"12",cy:"7",r:"4"}]];var Hc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["path",{d:"M16 9a5 5 0 0 1 0 6"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728"}]];var Bc=[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15"}]];var Dc=[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4"}]];var Fc=[["path",{d:"M18 6 6 18"}],["path",{d:"m6 6 12 12"}]];var Nc=[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"}]];var Ab={activity:zl,"arrow-down":$l,"arrow-up":Xl,"arrow-up-right":Kl,bot:ed,"chevron-down":sd,"chevron-up":dd,"chevron-right":ld,"chevron-left":id,check:ad,clipboard:pd,"clipboard-copy":cd,copy:fd,file:Sd,"file-code":vd,"file-spreadsheet":wd,"file-text":Cd,"image-plus":Bd,loader:_d,"loader-circle":Si,mic:Kd,paperclip:ec,"refresh-cw":lc,search:pc,send:uc,"shield-alert":gc,"shield-check":hc,"shield-x":Ai,square:wc,"thumbs-down":Tc,"thumbs-up":Ec,upload:Ic,"volume-2":Hc,x:Fc,user:Wc,mail:qd,phone:nc,calendar:od,clock:ud,building:td,"map-pin":Vd,lock:Ud,key:Nd,"credit-card":md,"at-sign":Jl,hash:Rd,globe:Pd,link:Od,"circle-check":xi,"circle-x":yi,"triangle-alert":Ti,info:Fd,ban:Ql,shield:xc,"arrow-left":jl,"arrow-right":Gl,"external-link":yd,ellipsis:vi,"ellipsis-vertical":bi,menu:$d,house:Ci,plus:sc,minus:Jd,pencil:rc,trash:Pc,"trash-2":Lc,save:cc,download:hd,share:mc,funnel:wi,settings:fc,"rotate-cw":dc,maximize:zd,minimize:Xd,"shopping-cart":bc,"shopping-bag":yc,package:Zd,truck:Rc,tag:Mc,gift:Ld,receipt:ic,wallet:Dc,store:Sc,"dollar-sign":gd,percent:oc,play:ac,pause:tc,"volume-x":Bc,camera:nd,image:Dd,film:Md,headphones:Id,"message-circle":jd,"message-square":Gd,bell:Yl,heart:Wd,star:Cc,eye:bd,"eye-off":xd,bookmark:Zl,"calendar-days":rd,history:Hd,timer:kc,folder:kd,"folder-open":Ed,files:Ad,sparkles:Mi,zap:Nc,sun:Ac,moon:Yd,flag:Td,monitor:Qd,smartphone:vc},fe=(e,t=24,r="currentColor",o=2)=>{let n=Ab[e];return n?Mb(n,t,r,o):(console.warn(`Lucide icon "${e}" is not in the Persona registry. Add it to packages/widget/src/utils/icons.ts (see docs/icon-registry-shortlist.md).`),null)};function Mb(e,t,r,o){if(!Array.isArray(e))return null;let n=document.createElementNS("http://www.w3.org/2000/svg","svg");return n.setAttribute("width",String(t)),n.setAttribute("height",String(t)),n.setAttribute("viewBox","0 0 24 24"),n.setAttribute("fill","none"),n.setAttribute("stroke",r),n.setAttribute("stroke-width",String(o)),n.setAttribute("stroke-linecap","round"),n.setAttribute("stroke-linejoin","round"),n.setAttribute("aria-hidden","true"),e.forEach(a=>{if(!Array.isArray(a)||a.length<2)return;let s=a[0],i=a[1];if(!i)return;let c=document.createElementNS("http://www.w3.org/2000/svg",s);Object.entries(i).forEach(([l,p])=>{l!=="stroke"&&c.setAttribute(l,String(p))}),n.appendChild(c)}),n}var Ei={allowedTypes:en,maxFileSize:10*1024*1024,maxFiles:4};function Tb(){return`attach_${Date.now()}_${Math.random().toString(36).substring(2,9)}`}function Eb(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 ea=class e{constructor(t={}){this.attachments=[];this.previewsContainer=null;var r,o,n;this.config={allowedTypes:(r=t.allowedTypes)!=null?r:Ei.allowedTypes,maxFileSize:(o=t.maxFileSize)!=null?o:Ei.maxFileSize,maxFiles:(n=t.maxFiles)!=null?n:Ei.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:Ei.allowedTypes),t.maxFileSize!==void 0&&(this.config.maxFileSize=t.maxFileSize),t.maxFiles!==void 0&&(this.config.maxFiles=t.maxFiles),t.onFileRejected!==void 0&&(this.config.onFileRejected=t.onFileRejected),t.onAttachmentsChange!==void 0&&(this.config.onAttachmentsChange=t.onAttachmentsChange)}getAttachments(){return[...this.attachments]}getContentParts(){return this.attachments.map(t=>t.contentPart)}hasAttachments(){return this.attachments.length>0}count(){return this.attachments.length}async handleFileSelect(t){!t||t.length===0||await this.handleFiles(Array.from(t))}async handleFiles(t){var r,o,n,a,s,i,c;if(t.length){for(let l of t){if(this.attachments.length>=this.config.maxFiles){(o=(r=this.config).onFileRejected)==null||o.call(r,l,"count");continue}let p=Jg(l,this.config.allowedTypes,this.config.maxFileSize);if(!p.valid){let f=(n=p.error)!=null&&n.includes("type")?"type":"size";(s=(a=this.config).onFileRejected)==null||s.call(a,l,f);continue}try{let f=await Xg(l),u=mi(l)?URL.createObjectURL(l):null,m={id:Tb(),file:l,previewUrl:u,contentPart:f};this.attachments.push(m),this.renderPreview(m)}catch(f){console.error("[AttachmentManager] Failed to process file:",f)}}this.updatePreviewsVisibility(),(c=(i=this.config).onAttachmentsChange)==null||c.call(i,this.getAttachments())}}removeAttachment(t){var a,s,i;let r=this.attachments.findIndex(c=>c.id===t);if(r===-1)return;let o=this.attachments[r];o.previewUrl&&URL.revokeObjectURL(o.previewUrl),this.attachments.splice(r,1);let n=(a=this.previewsContainer)==null?void 0:a.querySelector(`[data-attachment-id="${t}"]`);n&&n.remove(),this.updatePreviewsVisibility(),(i=(s=this.config).onAttachmentsChange)==null||i.call(s,this.getAttachments())}clearAttachments(){var t,r;for(let o of this.attachments)o.previewUrl&&URL.revokeObjectURL(o.previewUrl);this.attachments=[],this.previewsContainer&&(this.previewsContainer.innerHTML=""),this.updatePreviewsVisibility(),(r=(t=this.config).onAttachmentsChange)==null||r.call(t,this.getAttachments())}renderPreview(t){if(!this.previewsContainer)return;let r=mi(t.file),o=w("div","persona-attachment-preview persona-relative persona-inline-block");if(o.setAttribute("data-attachment-id",t.id),o.style.width="48px",o.style.height="48px",r&&t.previewUrl){let s=w("img");s.src=t.previewUrl,s.alt=t.file.name,s.className="persona-w-full persona-h-full persona-object-cover persona-rounded-lg persona-border persona-border-gray-200",s.style.width="48px",s.style.height="48px",s.style.objectFit="cover",s.style.borderRadius="8px",o.appendChild(s)}else{let s=w("div");s.style.width="48px",s.style.height="48px",s.style.borderRadius="8px",s.style.backgroundColor="var(--persona-container, #f3f4f6)",s.style.border="1px solid var(--persona-border, #e5e7eb)",s.style.display="flex",s.style.flexDirection="column",s.style.alignItems="center",s.style.justifyContent="center",s.style.gap="2px",s.style.overflow="hidden";let i=Eb(t.file.type),c=fe(i,20,"var(--persona-muted, #6b7280)",1.5);c&&s.appendChild(c);let l=w("span");l.textContent=Qg(t.file.type,t.file.name),l.style.fontSize="8px",l.style.fontWeight="600",l.style.color="var(--persona-muted, #6b7280)",l.style.textTransform="uppercase",l.style.lineHeight="1",s.appendChild(l),o.appendChild(s)}let n=w("button","persona-attachment-remove persona-absolute persona-flex persona-items-center persona-justify-center");n.type="button",n.setAttribute("aria-label","Remove attachment"),n.style.position="absolute",n.style.top="-4px",n.style.right="-4px",n.style.width="18px",n.style.height="18px",n.style.borderRadius="50%",n.style.backgroundColor="var(--persona-palette-colors-black-alpha-60, rgba(0, 0, 0, 0.6))",n.style.border="none",n.style.cursor="pointer",n.style.display="flex",n.style.alignItems="center",n.style.justifyContent="center",n.style.padding="0";let a=fe("x",10,"var(--persona-text-inverse, #ffffff)",2);a?n.appendChild(a):(n.textContent="\xD7",n.style.color="var(--persona-text-inverse, #ffffff)",n.style.fontSize="14px",n.style.lineHeight="1"),n.addEventListener("click",s=>{s.preventDefault(),s.stopPropagation(),this.removeAttachment(t.id)}),o.appendChild(n),this.previewsContainer.appendChild(o)}updatePreviewsVisibility(){this.previewsContainer&&(this.previewsContainer.style.display=this.attachments.length>0?"flex":"none")}static fromConfig(t,r){return new e({allowedTypes:t==null?void 0:t.allowedTypes,maxFileSize:t==null?void 0:t.maxFileSize,maxFiles:t==null?void 0:t.maxFiles,onFileRejected:t==null?void 0:t.onFileRejected,onAttachmentsChange:r})}};var nh=e=>typeof e=="object"&&e!==null&&!Array.isArray(e);function bs(e,t){if(!e)return t;if(!t)return e;let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];nh(a)&&nh(n)?r[o]=bs(a,n):r[o]=n}return r}var Yr="min(440px, calc(100vw - 24px))",ki="440px",kb={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:Yr,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)"},Wt={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:kb,copy:{welcomeTitle:"Hello \u{1F44B}",welcomeSubtitle:"Ask anything about your account or products.",inputPlaceholder:"How can I help...",sendButtonLabel:"Send"},sendButton:{borderWidth:"0px",paddingX:"12px",paddingY:"10px",borderColor:void 0,useIcon:!0,iconText:"\u2191",size:"40px",showTooltip:!0,tooltipText:"Send message",iconName:"send"},statusIndicator:{visible:!0,idleText:"Online",connectingText:"Connecting\u2026",connectedText:"Streaming\u2026",errorText:"Offline"},voiceRecognition:{enabled:!0,pauseDuration:2e3,iconName:"mic",iconSize:"39px",borderWidth:"0px",paddingX:"9px",paddingY:"14px",iconColor:void 0,backgroundColor:"transparent",borderColor:"transparent",recordingIconColor:void 0,recordingBackgroundColor:void 0,recordingBorderColor:"transparent",showTooltip:!0,tooltipText:"Start voice recognition"},features:{showReasoning:!0,showToolCalls:!0,scrollToBottom:{enabled:!0,iconName:"arrow-down",label:""},scrollBehavior:{mode:"follow",anchorTopOffset:16},toolCallDisplay:{collapsedMode:"tool-call",activePreview:!1,grouped:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},reasoningDisplay:{activePreview:!1,previewMaxLines:3,expandable:!0,loadingAnimation:"none"},streamAnimation:{type:"none",placeholder:"none",speed:120,duration:1800},askUserQuestion:{enabled:!0,slideInMs:180,freeTextLabel:"Other\u2026",freeTextPlaceholder:"Type your answer\u2026",submitLabel:"Send"}},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"],suggestionChipsConfig:{fontFamily:"sans-serif",fontWeight:"500",paddingX:"12px",paddingY:"6px"},layout:{header:{layout:"default",showIcon:!0,showTitle:!0,showSubtitle:!0,showCloseButton:!0,showClearChat:!0},messages:{layout:"bubble",avatar:{show:!1,position:"left"},timestamp:{show:!1,position:"below"},groupConsecutive:!1},slots:{}},markdown:{options:{gfm:!0,breaks:!0},disableDefaultStyles:!1},messageActions:{enabled:!0,showCopy:!0,showUpvote:!1,showDownvote:!1,visibility:"hover",align:"right",layout:"pill-inside"},debug:!1};function ah(e,t){if(!(!e&&!t))return e?t?bs(e,t):e:t}function Li(e){var t,r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S;return e?{...Wt,...e,theme:ah(Wt.theme,e.theme),darkTheme:ah(Wt.darkTheme,e.darkTheme),launcher:{...Wt.launcher,...e.launcher,dock:{...(t=Wt.launcher)==null?void 0:t.dock,...(r=e.launcher)==null?void 0:r.dock},clearChat:{...(o=Wt.launcher)==null?void 0:o.clearChat,...(n=e.launcher)==null?void 0:n.clearChat}},copy:{...Wt.copy,...e.copy},sendButton:{...Wt.sendButton,...e.sendButton},statusIndicator:{...Wt.statusIndicator,...e.statusIndicator},voiceRecognition:{...Wt.voiceRecognition,...e.voiceRecognition},features:(()=>{var se,ie,pe,Ve,_e,G,K,Me,Q,le;let v=(se=Wt.features)==null?void 0:se.artifacts,M=(ie=e.features)==null?void 0:ie.artifacts,W=(pe=Wt.features)==null?void 0:pe.scrollToBottom,H=(Ve=e.features)==null?void 0:Ve.scrollToBottom,I=(_e=Wt.features)==null?void 0:_e.scrollBehavior,D=(G=e.features)==null?void 0:G.scrollBehavior,O=(K=Wt.features)==null?void 0:K.streamAnimation,J=(Me=e.features)==null?void 0:Me.streamAnimation,me=(Q=Wt.features)==null?void 0:Q.askUserQuestion,ce=(le=e.features)==null?void 0:le.askUserQuestion,te=v===void 0&&M===void 0?void 0:{...v,...M,layout:{...v==null?void 0:v.layout,...M==null?void 0:M.layout}},Se=W===void 0&&H===void 0?void 0:{...W,...H},We=I===void 0&&D===void 0?void 0:{...I,...D},de=O===void 0&&J===void 0?void 0:{...O,...J},ve=me===void 0&&ce===void 0?void 0:{...me,...ce,styles:{...me==null?void 0:me.styles,...ce==null?void 0:ce.styles}};return{...Wt.features,...e.features,...Se!==void 0?{scrollToBottom:Se}:{},...We!==void 0?{scrollBehavior:We}:{},...te!==void 0?{artifacts:te}:{},...de!==void 0?{streamAnimation:de}:{},...ve!==void 0?{askUserQuestion:ve}:{}}})(),suggestionChips:(a=e.suggestionChips)!=null?a:Wt.suggestionChips,suggestionChipsConfig:{...Wt.suggestionChipsConfig,...e.suggestionChipsConfig},layout:{...Wt.layout,...e.layout,header:{...(s=Wt.layout)==null?void 0:s.header,...(i=e.layout)==null?void 0:i.header},messages:{...(c=Wt.layout)==null?void 0:c.messages,...(l=e.layout)==null?void 0:l.messages,avatar:{...(f=(p=Wt.layout)==null?void 0:p.messages)==null?void 0:f.avatar,...(m=(u=e.layout)==null?void 0:u.messages)==null?void 0:m.avatar},timestamp:{...(b=(x=Wt.layout)==null?void 0:x.messages)==null?void 0:b.timestamp,...(E=(L=e.layout)==null?void 0:L.messages)==null?void 0:E.timestamp}},slots:{...(A=Wt.layout)==null?void 0:A.slots,...(T=e.layout)==null?void 0:T.slots}},markdown:{...Wt.markdown,...e.markdown,options:{...(y=Wt.markdown)==null?void 0:y.options,...(S=e.markdown)==null?void 0:S.options}},messageActions:{...Wt.messageActions,...e.messageActions}}:Wt}var Oc={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"}},_c={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"}},Uc={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:Yr,maxWidth:ki,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 Wa(e,t){if(!t.startsWith("palette.")&&!t.startsWith("semantic.")&&!t.startsWith("components."))return t;let r=t.split("."),o=e;for(let n of r){if(o==null)return;o=o[n]}return typeof o=="string"&&(o.startsWith("palette.")||o.startsWith("semantic.")||o.startsWith("components."))?Wa(e,o):o}function Pi(e){let t={};function r(o,n){for(let[a,s]of Object.entries(o)){let i=`${n}.${a}`;if(typeof s=="string"){let c=Wa(e,s);c!==void 0&&(t[i]={path:i,value:c,type:n.includes("color")?"color":n.includes("spacing")?"spacing":n.includes("typography")?"typography":n.includes("shadow")?"shadow":n.includes("border")?"border":"color"})}else typeof s=="object"&&s!==null&&r(s,i)}}return r(e.palette,"palette"),r(e.semantic,"semantic"),r(e.components,"components"),t}function qc(e){let t=[],r=[];return e.palette||t.push({path:"palette",message:"Theme must include a palette",severity:"error"}),e.semantic||r.push({path:"semantic",message:"No semantic tokens defined - defaults will be used",severity:"warning"}),e.components||r.push({path:"components",message:"No component tokens defined - defaults will be used",severity:"warning"}),{valid:t.length===0,errors:t,warnings:r}}function sh(e,t){let r={...e};for(let[o,n]of Object.entries(t)){let a=r[o];a&&typeof a=="object"&&!Array.isArray(a)&&n&&typeof n=="object"&&!Array.isArray(n)?r[o]=sh(a,n):r[o]=n}return r}function Lb(e,t){return t?sh(e,t):e}function Ha(e,t={}){var n,a,s,i,c,l,p,f,u,m,x,b,L;let r={palette:Oc,semantic:_c,components:Uc},o={palette:{...r.palette,...e==null?void 0:e.palette,colors:{...r.palette.colors,...(n=e==null?void 0:e.palette)==null?void 0:n.colors},spacing:{...r.palette.spacing,...(a=e==null?void 0:e.palette)==null?void 0:a.spacing},typography:{...r.palette.typography,...(s=e==null?void 0:e.palette)==null?void 0:s.typography},shadows:{...r.palette.shadows,...(i=e==null?void 0:e.palette)==null?void 0:i.shadows},borders:{...r.palette.borders,...(c=e==null?void 0:e.palette)==null?void 0:c.borders},radius:{...r.palette.radius,...(l=e==null?void 0:e.palette)==null?void 0:l.radius}},semantic:{...r.semantic,...e==null?void 0:e.semantic,colors:{...r.semantic.colors,...(p=e==null?void 0:e.semantic)==null?void 0:p.colors,interactive:{...r.semantic.colors.interactive,...(u=(f=e==null?void 0:e.semantic)==null?void 0:f.colors)==null?void 0:u.interactive},feedback:{...r.semantic.colors.feedback,...(x=(m=e==null?void 0:e.semantic)==null?void 0:m.colors)==null?void 0:x.feedback}},spacing:{...r.semantic.spacing,...(b=e==null?void 0:e.semantic)==null?void 0:b.spacing},typography:{...r.semantic.typography,...(L=e==null?void 0:e.semantic)==null?void 0:L.typography}},components:Lb(r.components,e==null?void 0:e.components)};if(t.validate!==!1){let E=qc(o);if(!E.valid)throw new Error(`Theme validation failed: ${E.errors.map(A=>A.message).join(", ")}`)}if(t.plugins)for(let E of t.plugins)o=E.transform(o);return o}function Ri(e){var b,L,E,A,T,y,S,v,M,W,H,I,D,O,J,me,ce,te,Se,We,de,ve,se,ie,pe,Ve,_e,G,K,Me,Q,le,Re,rt,vt,Ut,jt,at,Ne,j,$e,ze,ye,we,Ze,Nt,re,Oe,xr,Ht,Qt,_o,So,P,ee,Ae,Ie,Ee,He,Ge,st,Lt,xt,F,Y,Ce,it,Je,qt,yr,yt,bt,Pt,wt,pr,Ot,_r,Tr,Er,wr,kr,uo,Ct,Ao,Mo,Uo,fo,pt,Rn,To,In,Br,da,nn,qo,an,sn,Wn,Hn,ln,ht,Ur,qr,Lr,St,to,ro,Vr,dn,Vo,cn,zr,Rt,Pr,oo,pn,zo,un;let t=Pi(e),r={};for(let[he,Dr]of Object.entries(t)){let Eo=he.replace(/\./g,"-");r[`--persona-${Eo}`]=Dr.value}r["--persona-primary"]=(b=r["--persona-semantic-colors-primary"])!=null?b:r["--persona-palette-colors-primary-500"],r["--persona-secondary"]=(L=r["--persona-semantic-colors-secondary"])!=null?L:r["--persona-palette-colors-secondary-500"],r["--persona-accent"]=(E=r["--persona-semantic-colors-accent"])!=null?E:r["--persona-palette-colors-accent-500"],r["--persona-surface"]=(A=r["--persona-semantic-colors-surface"])!=null?A:r["--persona-palette-colors-gray-50"],r["--persona-background"]=(T=r["--persona-semantic-colors-background"])!=null?T:r["--persona-palette-colors-gray-50"],r["--persona-container"]=(y=r["--persona-semantic-colors-container"])!=null?y:r["--persona-palette-colors-gray-100"],r["--persona-text"]=(S=r["--persona-semantic-colors-text"])!=null?S:r["--persona-palette-colors-gray-900"],r["--persona-text-muted"]=(v=r["--persona-semantic-colors-text-muted"])!=null?v:r["--persona-palette-colors-gray-500"],r["--persona-text-inverse"]=(M=r["--persona-semantic-colors-text-inverse"])!=null?M:r["--persona-palette-colors-gray-50"],r["--persona-border"]=(W=r["--persona-semantic-colors-border"])!=null?W:r["--persona-palette-colors-gray-200"],r["--persona-divider"]=(H=r["--persona-semantic-colors-divider"])!=null?H:r["--persona-palette-colors-gray-200"],r["--persona-muted"]=r["--persona-text-muted"],r["--persona-voice-recording-indicator"]=(I=r["--persona-components-voice-recording-indicator"])!=null?I:r["--persona-palette-colors-error-500"],r["--persona-voice-recording-bg"]=(D=r["--persona-components-voice-recording-background"])!=null?D:r["--persona-palette-colors-error-50"],r["--persona-voice-processing-icon"]=(O=r["--persona-components-voice-processing-icon"])!=null?O:r["--persona-palette-colors-primary-500"],r["--persona-voice-speaking-icon"]=(J=r["--persona-components-voice-speaking-icon"])!=null?J:r["--persona-palette-colors-success-500"],r["--persona-approval-bg"]=(me=r["--persona-components-approval-requested-background"])!=null?me:r["--persona-surface"],r["--persona-approval-border"]=(ce=r["--persona-components-approval-requested-border"])!=null?ce:r["--persona-border"],r["--persona-approval-text"]=(te=r["--persona-components-approval-requested-text"])!=null?te:r["--persona-palette-colors-gray-900"],r["--persona-approval-shadow"]=(Se=r["--persona-components-approval-requested-shadow"])!=null?Se:"0 1px 2px 0 rgba(11, 11, 11, 0.06), 0 2px 8px 0 rgba(11, 11, 11, 0.04)",r["--persona-approval-approve-bg"]=(We=r["--persona-components-approval-approve-background"])!=null?We:r["--persona-button-primary-bg"],r["--persona-approval-deny-bg"]=(de=r["--persona-components-approval-deny-background"])!=null?de:r["--persona-container"],r["--persona-attachment-image-bg"]=(ve=r["--persona-components-attachment-image-background"])!=null?ve:r["--persona-palette-colors-gray-100"],r["--persona-attachment-image-border"]=(se=r["--persona-components-attachment-image-border"])!=null?se:r["--persona-palette-colors-gray-200"],r["--persona-font-family"]=(ie=r["--persona-semantic-typography-fontFamily"])!=null?ie:r["--persona-palette-typography-fontFamily-sans"],r["--persona-font-size"]=(pe=r["--persona-semantic-typography-fontSize"])!=null?pe:r["--persona-palette-typography-fontSize-base"],r["--persona-font-weight"]=(Ve=r["--persona-semantic-typography-fontWeight"])!=null?Ve:r["--persona-palette-typography-fontWeight-normal"],r["--persona-line-height"]=(_e=r["--persona-semantic-typography-lineHeight"])!=null?_e:r["--persona-palette-typography-lineHeight-normal"],r["--persona-input-font-family"]=r["--persona-font-family"],r["--persona-input-font-weight"]=r["--persona-font-weight"],r["--persona-radius-sm"]=(G=r["--persona-palette-radius-sm"])!=null?G:"0.125rem",r["--persona-radius-md"]=(K=r["--persona-palette-radius-md"])!=null?K:"0.375rem",r["--persona-radius-lg"]=(Me=r["--persona-palette-radius-lg"])!=null?Me:"0.5rem",r["--persona-radius-xl"]=(Q=r["--persona-palette-radius-xl"])!=null?Q:"0.75rem",r["--persona-radius-full"]=(le=r["--persona-palette-radius-full"])!=null?le:"9999px",r["--persona-launcher-radius"]=(rt=(Re=r["--persona-components-launcher-borderRadius"])!=null?Re:r["--persona-palette-radius-full"])!=null?rt:"9999px",r["--persona-launcher-bg"]=(vt=r["--persona-components-launcher-background"])!=null?vt:r["--persona-primary"],r["--persona-launcher-fg"]=(Ut=r["--persona-components-launcher-foreground"])!=null?Ut:r["--persona-text-inverse"],r["--persona-launcher-border"]=(jt=r["--persona-components-launcher-border"])!=null?jt:r["--persona-border"],r["--persona-button-primary-bg"]=(at=r["--persona-components-button-primary-background"])!=null?at:r["--persona-primary"],r["--persona-button-primary-fg"]=(Ne=r["--persona-components-button-primary-foreground"])!=null?Ne:r["--persona-text-inverse"],r["--persona-button-radius"]=($e=(j=r["--persona-components-button-primary-borderRadius"])!=null?j:r["--persona-palette-radius-full"])!=null?$e:"9999px",r["--persona-panel-radius"]=(ye=(ze=r["--persona-components-panel-borderRadius"])!=null?ze:r["--persona-radius-xl"])!=null?ye:"0.75rem",r["--persona-panel-border"]=(we=r["--persona-components-panel-border"])!=null?we:`1px solid ${r["--persona-border"]}`,r["--persona-panel-shadow"]=(Nt=(Ze=r["--persona-components-panel-shadow"])!=null?Ze:r["--persona-palette-shadows-xl"])!=null?Nt:"0 25px 50px -12px rgba(0, 0, 0, 0.25)",r["--persona-launcher-shadow"]=(re=r["--persona-components-launcher-shadow"])!=null?re:"0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1)",r["--persona-input-radius"]=(xr=(Oe=r["--persona-components-input-borderRadius"])!=null?Oe:r["--persona-radius-lg"])!=null?xr:"0.5rem",r["--persona-message-user-radius"]=(Qt=(Ht=r["--persona-components-message-user-borderRadius"])!=null?Ht:r["--persona-radius-lg"])!=null?Qt:"0.5rem",r["--persona-message-assistant-radius"]=(So=(_o=r["--persona-components-message-assistant-borderRadius"])!=null?_o:r["--persona-radius-lg"])!=null?So:"0.5rem",r["--persona-header-bg"]=(P=r["--persona-components-header-background"])!=null?P:r["--persona-surface"],r["--persona-header-border"]=(ee=r["--persona-components-header-border"])!=null?ee:r["--persona-divider"],r["--persona-header-icon-bg"]=(Ae=r["--persona-components-header-iconBackground"])!=null?Ae:r["--persona-primary"],r["--persona-header-icon-fg"]=(Ie=r["--persona-components-header-iconForeground"])!=null?Ie:r["--persona-text-inverse"],r["--persona-header-title-fg"]=(Ee=r["--persona-components-header-titleForeground"])!=null?Ee:r["--persona-primary"],r["--persona-header-subtitle-fg"]=(He=r["--persona-components-header-subtitleForeground"])!=null?He:r["--persona-text-muted"],r["--persona-header-action-icon-fg"]=(Ge=r["--persona-components-header-actionIconForeground"])!=null?Ge:r["--persona-muted"];let o=(st=e.components)==null?void 0:st.header;o!=null&&o.shadow&&(r["--persona-header-shadow"]=o.shadow),o!=null&&o.borderBottom&&(r["--persona-header-border-bottom"]=o.borderBottom);let n=(Lt=e.components)==null?void 0:Lt.introCard;r["--persona-intro-card-bg"]=(xt=r["--persona-components-introCard-background"])!=null?xt:r["--persona-surface"],r["--persona-intro-card-radius"]=(F=r["--persona-components-introCard-borderRadius"])!=null?F:"1rem",r["--persona-intro-card-padding"]=(Y=r["--persona-components-introCard-padding"])!=null?Y:"1.5rem",r["--persona-intro-card-shadow"]=(it=(Ce=n==null?void 0:n.shadow)!=null?Ce:r["--persona-components-introCard-shadow"])!=null?it:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-input-background"]=(Je=r["--persona-components-input-background"])!=null?Je:r["--persona-surface"],r["--persona-input-placeholder"]=(qt=r["--persona-components-input-placeholder"])!=null?qt:r["--persona-text-muted"],r["--persona-message-user-bg"]=(yr=r["--persona-components-message-user-background"])!=null?yr:r["--persona-accent"],r["--persona-message-user-text"]=(yt=r["--persona-components-message-user-text"])!=null?yt:r["--persona-text-inverse"],r["--persona-message-user-shadow"]=(bt=r["--persona-components-message-user-shadow"])!=null?bt:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-message-assistant-bg"]=(Pt=r["--persona-components-message-assistant-background"])!=null?Pt:r["--persona-surface"],r["--persona-message-assistant-text"]=(wt=r["--persona-components-message-assistant-text"])!=null?wt:r["--persona-text"],r["--persona-message-assistant-border"]=(pr=r["--persona-components-message-assistant-border"])!=null?pr:r["--persona-border"],r["--persona-message-assistant-shadow"]=(Ot=r["--persona-components-message-assistant-shadow"])!=null?Ot:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-bg"]=(Tr=(_r=r["--persona-components-scrollToBottom-background"])!=null?_r:r["--persona-button-primary-bg"])!=null?Tr:r["--persona-accent"],r["--persona-scroll-to-bottom-fg"]=(wr=(Er=r["--persona-components-scrollToBottom-foreground"])!=null?Er:r["--persona-button-primary-fg"])!=null?wr:r["--persona-text-inverse"],r["--persona-scroll-to-bottom-border"]=(kr=r["--persona-components-scrollToBottom-border"])!=null?kr:r["--persona-primary"],r["--persona-scroll-to-bottom-size"]=(uo=r["--persona-components-scrollToBottom-size"])!=null?uo:"40px",r["--persona-scroll-to-bottom-radius"]=(Mo=(Ao=(Ct=r["--persona-components-scrollToBottom-borderRadius"])!=null?Ct:r["--persona-button-radius"])!=null?Ao:r["--persona-radius-full"])!=null?Mo:"9999px",r["--persona-scroll-to-bottom-shadow"]=(fo=(Uo=r["--persona-components-scrollToBottom-shadow"])!=null?Uo:r["--persona-palette-shadows-sm"])!=null?fo:"0 1px 2px 0 rgb(0 0 0 / 0.05)",r["--persona-scroll-to-bottom-padding"]=(pt=r["--persona-components-scrollToBottom-padding"])!=null?pt:"0.5rem 0.875rem",r["--persona-scroll-to-bottom-gap"]=(Rn=r["--persona-components-scrollToBottom-gap"])!=null?Rn:"0.5rem",r["--persona-scroll-to-bottom-font-size"]=(In=(To=r["--persona-components-scrollToBottom-fontSize"])!=null?To:r["--persona-palette-typography-fontSize-sm"])!=null?In:"0.875rem",r["--persona-scroll-to-bottom-icon-size"]=(Br=r["--persona-components-scrollToBottom-iconSize"])!=null?Br:"14px",r["--persona-tool-bubble-shadow"]=(da=r["--persona-components-toolBubble-shadow"])!=null?da:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-reasoning-bubble-shadow"]=(nn=r["--persona-components-reasoningBubble-shadow"])!=null?nn:"0 5px 15px rgba(15, 23, 42, 0.08)",r["--persona-composer-shadow"]=(qo=r["--persona-components-composer-shadow"])!=null?qo:"none",r["--persona-md-inline-code-bg"]=(an=r["--persona-components-markdown-inlineCode-background"])!=null?an:r["--persona-container"],r["--persona-md-inline-code-color"]=(sn=r["--persona-components-markdown-inlineCode-foreground"])!=null?sn:r["--persona-text"],r["--persona-md-link-color"]=(Hn=(Wn=r["--persona-components-markdown-link-foreground"])!=null?Wn:r["--persona-accent"])!=null?Hn:"#0f0f0f";let a=r["--persona-components-markdown-heading-h1-fontSize"];a&&(r["--persona-md-h1-size"]=a);let s=r["--persona-components-markdown-heading-h1-fontWeight"];s&&(r["--persona-md-h1-weight"]=s);let i=r["--persona-components-markdown-heading-h2-fontSize"];i&&(r["--persona-md-h2-size"]=i);let c=r["--persona-components-markdown-heading-h2-fontWeight"];c&&(r["--persona-md-h2-weight"]=c);let l=r["--persona-components-markdown-prose-fontFamily"];l&&l!=="inherit"&&(r["--persona-md-prose-font-family"]=l),r["--persona-md-code-block-bg"]=(ln=r["--persona-components-markdown-codeBlock-background"])!=null?ln:r["--persona-container"],r["--persona-md-code-block-border-color"]=(ht=r["--persona-components-markdown-codeBlock-borderColor"])!=null?ht:r["--persona-border"],r["--persona-md-code-block-text-color"]=(Ur=r["--persona-components-markdown-codeBlock-textColor"])!=null?Ur:"inherit",r["--persona-md-table-header-bg"]=(qr=r["--persona-components-markdown-table-headerBackground"])!=null?qr:r["--persona-container"],r["--persona-md-table-border-color"]=(Lr=r["--persona-components-markdown-table-borderColor"])!=null?Lr:r["--persona-border"],r["--persona-md-hr-color"]=(St=r["--persona-components-markdown-hr-color"])!=null?St:r["--persona-divider"],r["--persona-md-blockquote-border-color"]=(to=r["--persona-components-markdown-blockquote-borderColor"])!=null?to:r["--persona-palette-colors-gray-900"],r["--persona-md-blockquote-bg"]=(ro=r["--persona-components-markdown-blockquote-background"])!=null?ro:"transparent",r["--persona-md-blockquote-text-color"]=(Vr=r["--persona-components-markdown-blockquote-textColor"])!=null?Vr:r["--persona-palette-colors-gray-500"],r["--cw-container"]=(dn=r["--persona-components-collapsibleWidget-container"])!=null?dn:r["--persona-surface"],r["--cw-surface"]=(Vo=r["--persona-components-collapsibleWidget-surface"])!=null?Vo:r["--persona-surface"],r["--cw-border"]=(cn=r["--persona-components-collapsibleWidget-border"])!=null?cn:r["--persona-border"],r["--persona-message-border"]=(zr=r["--persona-components-message-border"])!=null?zr:r["--persona-border"];let p=e.components,f=p==null?void 0:p.iconButton;f&&(f.background&&(r["--persona-icon-btn-bg"]=f.background),f.border&&(r["--persona-icon-btn-border"]=f.border),f.color&&(r["--persona-icon-btn-color"]=f.color),f.padding&&(r["--persona-icon-btn-padding"]=f.padding),f.borderRadius&&(r["--persona-icon-btn-radius"]=f.borderRadius),f.hoverBackground&&(r["--persona-icon-btn-hover-bg"]=f.hoverBackground),f.hoverColor&&(r["--persona-icon-btn-hover-color"]=f.hoverColor),f.activeBackground&&(r["--persona-icon-btn-active-bg"]=f.activeBackground),f.activeBorder&&(r["--persona-icon-btn-active-border"]=f.activeBorder));let u=p==null?void 0:p.labelButton;u&&(u.background&&(r["--persona-label-btn-bg"]=u.background),u.border&&(r["--persona-label-btn-border"]=u.border),u.color&&(r["--persona-label-btn-color"]=u.color),u.padding&&(r["--persona-label-btn-padding"]=u.padding),u.borderRadius&&(r["--persona-label-btn-radius"]=u.borderRadius),u.hoverBackground&&(r["--persona-label-btn-hover-bg"]=u.hoverBackground),u.fontSize&&(r["--persona-label-btn-font-size"]=u.fontSize),u.gap&&(r["--persona-label-btn-gap"]=u.gap));let m=p==null?void 0:p.toggleGroup;m&&(m.gap&&(r["--persona-toggle-group-gap"]=m.gap),m.borderRadius&&(r["--persona-toggle-group-radius"]=m.borderRadius));let x=p==null?void 0:p.artifact;if(x!=null&&x.toolbar){let he=x.toolbar;he.iconHoverColor&&(r["--persona-artifact-toolbar-icon-hover-color"]=he.iconHoverColor),he.iconHoverBackground&&(r["--persona-artifact-toolbar-icon-hover-bg"]=he.iconHoverBackground),he.iconPadding&&(r["--persona-artifact-toolbar-icon-padding"]=he.iconPadding),he.iconBorderRadius&&(r["--persona-artifact-toolbar-icon-radius"]=he.iconBorderRadius),he.iconBorder&&(r["--persona-artifact-toolbar-icon-border"]=he.iconBorder),he.toggleGroupGap&&(r["--persona-artifact-toolbar-toggle-group-gap"]=he.toggleGroupGap),he.toggleBorderRadius&&(r["--persona-artifact-toolbar-toggle-radius"]=he.toggleBorderRadius),he.copyBackground&&(r["--persona-artifact-toolbar-copy-bg"]=he.copyBackground),he.copyBorder&&(r["--persona-artifact-toolbar-copy-border"]=he.copyBorder),he.copyColor&&(r["--persona-artifact-toolbar-copy-color"]=he.copyColor),he.copyBorderRadius&&(r["--persona-artifact-toolbar-copy-radius"]=he.copyBorderRadius),he.copyPadding&&(r["--persona-artifact-toolbar-copy-padding"]=he.copyPadding),he.copyMenuBackground&&(r["--persona-artifact-toolbar-copy-menu-bg"]=he.copyMenuBackground,r["--persona-dropdown-bg"]=(Rt=r["--persona-dropdown-bg"])!=null?Rt:he.copyMenuBackground),he.copyMenuBorder&&(r["--persona-artifact-toolbar-copy-menu-border"]=he.copyMenuBorder,r["--persona-dropdown-border"]=(Pr=r["--persona-dropdown-border"])!=null?Pr:he.copyMenuBorder),he.copyMenuShadow&&(r["--persona-artifact-toolbar-copy-menu-shadow"]=he.copyMenuShadow,r["--persona-dropdown-shadow"]=(oo=r["--persona-dropdown-shadow"])!=null?oo:he.copyMenuShadow),he.copyMenuBorderRadius&&(r["--persona-artifact-toolbar-copy-menu-radius"]=he.copyMenuBorderRadius,r["--persona-dropdown-radius"]=(pn=r["--persona-dropdown-radius"])!=null?pn:he.copyMenuBorderRadius),he.copyMenuItemHoverBackground&&(r["--persona-artifact-toolbar-copy-menu-item-hover-bg"]=he.copyMenuItemHoverBackground,r["--persona-dropdown-item-hover-bg"]=(zo=r["--persona-dropdown-item-hover-bg"])!=null?zo:he.copyMenuItemHoverBackground),he.iconBackground&&(r["--persona-artifact-toolbar-icon-bg"]=he.iconBackground),he.toolbarBorder&&(r["--persona-artifact-toolbar-border"]=he.toolbarBorder)}if(x!=null&&x.tab){let he=x.tab;he.background&&(r["--persona-artifact-tab-bg"]=he.background),he.activeBackground&&(r["--persona-artifact-tab-active-bg"]=he.activeBackground),he.activeBorder&&(r["--persona-artifact-tab-active-border"]=he.activeBorder),he.borderRadius&&(r["--persona-artifact-tab-radius"]=he.borderRadius),he.textColor&&(r["--persona-artifact-tab-color"]=he.textColor),he.hoverBackground&&(r["--persona-artifact-tab-hover-bg"]=he.hoverBackground),he.listBackground&&(r["--persona-artifact-tab-list-bg"]=he.listBackground),he.listBorderColor&&(r["--persona-artifact-tab-list-border-color"]=he.listBorderColor),he.listPadding&&(r["--persona-artifact-tab-list-padding"]=he.listPadding)}if(x!=null&&x.pane){let he=x.pane;if(he.toolbarBackground){let Dr=(un=Wa(e,he.toolbarBackground))!=null?un:he.toolbarBackground;r["--persona-artifact-toolbar-bg"]=Dr}}return r}var ih={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 Pb={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"}}},lh=e=>{if(!(!e||typeof e!="object"||Array.isArray(e)))return e},vs=()=>{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"},Rb=e=>{var r;let t=(r=e==null?void 0:e.colorScheme)!=null?r:"light";return t==="light"?"light":t==="dark"?"dark":vs()},Vc=e=>Rb(e),Ib=e=>Ha(e),Wb=e=>{var r;let t=Ha(void 0,{validate:!1});return Ha({...e,palette:{...t.palette,colors:{...Pb.colors,...(r=e==null?void 0:e.palette)==null?void 0:r.colors}}},{validate:!1})},Ba=e=>{let t=Vc(e),r=lh(e==null?void 0:e.theme),o=lh(e==null?void 0:e.darkTheme);return t==="dark"?Wb(bs(r!=null?r:{},o!=null?o:{})):Ib(r)},Hb=e=>Ri(e),Tn=(e,t)=>{let r=Ba(t),o=Hb(r);for(let[n,a]of Object.entries(o))e.style.setProperty(n,a)},Ii=e=>{let t=[];if(typeof document!="undefined"&&typeof MutationObserver!="undefined"){let r=new MutationObserver(()=>{e(vs())});r.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}),t.push(()=>r.disconnect())}if(typeof window!="undefined"&&window.matchMedia){let r=window.matchMedia("(prefers-color-scheme: dark)"),o=()=>e(vs());r.addEventListener?(r.addEventListener("change",o),t.push(()=>r.removeEventListener("change",o))):r.addListener&&(r.addListener(o),t.push(()=>r.removeListener(o)))}return()=>{t.forEach(r=>r())}};var dh=(function(){"use strict";let e=()=>{},t={morphStyle:"outerHTML",callbacks:{beforeNodeAdded:e,afterNodeAdded:e,beforeNodeMorphed:e,afterNodeMorphed:e,beforeNodeRemoved:e,afterNodeRemoved:e,beforeAttributeUpdated:e},head:{style:"merge",shouldPreserve:u=>u.getAttribute("im-preserve")==="true",shouldReAppend:u=>u.getAttribute("im-re-append")==="true",shouldRemove:e,afterHeadMorphed:e},restoreFocus:!0};function r(u,m,x={}){u=p(u);let b=f(m),L=l(u,b,x),E=n(L,()=>i(L,u,b,A=>A.morphStyle==="innerHTML"?(a(A,u,b),Array.from(u.childNodes)):o(A,u,b)));return L.pantry.remove(),E}function o(u,m,x){let b=f(m);return a(u,b,x,m,m.nextSibling),Array.from(b.childNodes)}function n(u,m){var T;if(!u.config.restoreFocus)return m();let x=document.activeElement;if(!(x instanceof HTMLInputElement||x instanceof HTMLTextAreaElement))return m();let{id:b,selectionStart:L,selectionEnd:E}=x,A=m();return b&&b!==((T=document.activeElement)==null?void 0:T.getAttribute("id"))&&(x=u.target.querySelector(`[id="${b}"]`),x==null||x.focus()),x&&!x.selectionEnd&&E&&x.setSelectionRange(L,E),A}let a=(function(){function u(y,S,v,M=null,W=null){S instanceof HTMLTemplateElement&&v instanceof HTMLTemplateElement&&(S=S.content,v=v.content),M||(M=S.firstChild);for(let H of v.childNodes){if(M&&M!=W){let D=x(y,H,M,W);if(D){D!==M&&L(y,M,D),s(D,H,y),M=D.nextSibling;continue}}if(H instanceof Element){let D=H.getAttribute("id");if(y.persistentIds.has(D)){let O=E(S,D,M,y);s(O,H,y),M=O.nextSibling;continue}}let I=m(S,H,M,y);I&&(M=I.nextSibling)}for(;M&&M!=W;){let H=M;M=M.nextSibling,b(y,H)}}function m(y,S,v,M){if(M.callbacks.beforeNodeAdded(S)===!1)return null;if(M.idMap.has(S)){let W=document.createElement(S.tagName);return y.insertBefore(W,v),s(W,S,M),M.callbacks.afterNodeAdded(W),W}else{let W=document.importNode(S,!0);return y.insertBefore(W,v),M.callbacks.afterNodeAdded(W),W}}let x=(function(){function y(M,W,H,I){let D=null,O=W.nextSibling,J=0,me=H;for(;me&&me!=I;){if(v(me,W)){if(S(M,me,W))return me;D===null&&(M.idMap.has(me)||(D=me))}if(D===null&&O&&v(me,O)&&(J++,O=O.nextSibling,J>=2&&(D=void 0)),M.activeElementAndParents.includes(me))break;me=me.nextSibling}return D||null}function S(M,W,H){let I=M.idMap.get(W),D=M.idMap.get(H);if(!D||!I)return!1;for(let O of I)if(D.has(O))return!0;return!1}function v(M,W){var D,O,J;let H=M,I=W;return H.nodeType===I.nodeType&&H.tagName===I.tagName&&(!((D=H.getAttribute)!=null&&D.call(H,"id"))||((O=H.getAttribute)==null?void 0:O.call(H,"id"))===((J=I.getAttribute)==null?void 0:J.call(I,"id")))}return y})();function b(y,S){var v;if(y.idMap.has(S))T(y.pantry,S,null);else{if(y.callbacks.beforeNodeRemoved(S)===!1)return;(v=S.parentNode)==null||v.removeChild(S),y.callbacks.afterNodeRemoved(S)}}function L(y,S,v){let M=S;for(;M&&M!==v;){let W=M;M=M.nextSibling,b(y,W)}return M}function E(y,S,v,M){var H,I;let W=((I=(H=M.target).getAttribute)==null?void 0:I.call(H,"id"))===S&&M.target||M.target.querySelector(`[id="${S}"]`)||M.pantry.querySelector(`[id="${S}"]`);return A(W,M),T(y,W,v),W}function A(y,S){let v=y.getAttribute("id");for(;y=y.parentNode;){let M=S.idMap.get(y);M&&(M.delete(v),M.size||S.idMap.delete(y))}}function T(y,S,v){if(y.moveBefore)try{y.moveBefore(S,v)}catch{y.insertBefore(S,v)}else y.insertBefore(S,v)}return u})(),s=(function(){function u(A,T,y){return y.ignoreActive&&A===document.activeElement?null:(y.callbacks.beforeNodeMorphed(A,T)===!1||(A instanceof HTMLHeadElement&&y.head.ignore||(A instanceof HTMLHeadElement&&y.head.style!=="morph"?c(A,T,y):(m(A,T,y),E(A,y)||a(y,A,T))),y.callbacks.afterNodeMorphed(A,T)),A)}function m(A,T,y){let S=T.nodeType;if(S===1){let v=A,M=T,W=v.attributes,H=M.attributes;for(let I of H)L(I.name,v,"update",y)||v.getAttribute(I.name)!==I.value&&v.setAttribute(I.name,I.value);for(let I=W.length-1;0<=I;I--){let D=W[I];if(D&&!M.hasAttribute(D.name)){if(L(D.name,v,"remove",y))continue;v.removeAttribute(D.name)}}E(v,y)||x(v,M,y)}(S===8||S===3)&&A.nodeValue!==T.nodeValue&&(A.nodeValue=T.nodeValue)}function x(A,T,y){if(A instanceof HTMLInputElement&&T instanceof HTMLInputElement&&T.type!=="file"){let S=T.value,v=A.value;b(A,T,"checked",y),b(A,T,"disabled",y),T.hasAttribute("value")?v!==S&&(L("value",A,"update",y)||(A.setAttribute("value",S),A.value=S)):L("value",A,"remove",y)||(A.value="",A.removeAttribute("value"))}else if(A instanceof HTMLOptionElement&&T instanceof HTMLOptionElement)b(A,T,"selected",y);else if(A instanceof HTMLTextAreaElement&&T instanceof HTMLTextAreaElement){let S=T.value,v=A.value;if(L("value",A,"update",y))return;S!==v&&(A.value=S),A.firstChild&&A.firstChild.nodeValue!==S&&(A.firstChild.nodeValue=S)}}function b(A,T,y,S){let v=T[y],M=A[y];if(v!==M){let W=L(y,A,"update",S);W||(A[y]=T[y]),v?W||A.setAttribute(y,""):L(y,A,"remove",S)||A.removeAttribute(y)}}function L(A,T,y,S){return A==="value"&&S.ignoreActiveValue&&T===document.activeElement?!0:S.callbacks.beforeAttributeUpdated(A,T,y)===!1}function E(A,T){return!!T.ignoreActiveValue&&A===document.activeElement&&A!==document.body}return u})();function i(u,m,x,b){if(u.head.block){let L=m.querySelector("head"),E=x.querySelector("head");if(L&&E){let A=c(L,E,u);return Promise.all(A).then(()=>{let T=Object.assign(u,{head:{block:!1,ignore:!0}});return b(T)})}}return b(u)}function c(u,m,x){let b=[],L=[],E=[],A=[],T=new Map;for(let S of m.children)T.set(S.outerHTML,S);for(let S of u.children){let v=T.has(S.outerHTML),M=x.head.shouldReAppend(S),W=x.head.shouldPreserve(S);v||W?M?L.push(S):(T.delete(S.outerHTML),E.push(S)):x.head.style==="append"?M&&(L.push(S),A.push(S)):x.head.shouldRemove(S)!==!1&&L.push(S)}A.push(...T.values());let y=[];for(let S of A){let v=document.createRange().createContextualFragment(S.outerHTML).firstChild;if(x.callbacks.beforeNodeAdded(v)!==!1){if("href"in v&&v.href||"src"in v&&v.src){let M,W=new Promise(function(H){M=H});v.addEventListener("load",function(){M()}),y.push(W)}u.appendChild(v),x.callbacks.afterNodeAdded(v),b.push(v)}}for(let S of L)x.callbacks.beforeNodeRemoved(S)!==!1&&(u.removeChild(S),x.callbacks.afterNodeRemoved(S));return x.head.afterHeadMorphed(u,{added:b,kept:E,removed:L}),y}let l=(function(){function u(y,S,v){let{persistentIds:M,idMap:W}=A(y,S),H=m(v),I=H.morphStyle||"outerHTML";if(!["innerHTML","outerHTML"].includes(I))throw`Do not understand how to morph style ${I}`;return{target:y,newContent:S,config:H,morphStyle:I,ignoreActive:H.ignoreActive,ignoreActiveValue:H.ignoreActiveValue,restoreFocus:H.restoreFocus,idMap:W,persistentIds:M,pantry:x(),activeElementAndParents:b(y),callbacks:H.callbacks,head:H.head}}function m(y){let S=Object.assign({},t);return Object.assign(S,y),S.callbacks=Object.assign({},t.callbacks,y.callbacks),S.head=Object.assign({},t.head,y.head),S}function x(){let y=document.createElement("div");return y.hidden=!0,document.body.insertAdjacentElement("afterend",y),y}function b(y){let S=[],v=document.activeElement;if((v==null?void 0:v.tagName)!=="BODY"&&y.contains(v))for(;v&&(S.push(v),v!==y);)v=v.parentElement;return S}function L(y){var v;let S=Array.from(y.querySelectorAll("[id]"));return(v=y.getAttribute)!=null&&v.call(y,"id")&&S.push(y),S}function E(y,S,v,M){for(let W of M){let H=W.getAttribute("id");if(S.has(H)){let I=W;for(;I;){let D=y.get(I);if(D==null&&(D=new Set,y.set(I,D)),D.add(H),I===v)break;I=I.parentElement}}}}function A(y,S){let v=L(y),M=L(S),W=T(v,M),H=new Map;E(H,W,y,v);let I=S.__idiomorphRoot||S;return E(H,W,I,M),{persistentIds:W,idMap:H}}function T(y,S){let v=new Set,M=new Map;for(let{id:H,tagName:I}of y)M.has(H)?v.add(H):M.set(H,I);let W=new Set;for(let{id:H,tagName:I}of S)W.has(H)?v.add(H):M.get(H)===I&&W.add(H);for(let H of v)W.delete(H);return W}return u})(),{normalizeElement:p,normalizeParent:f}=(function(){let u=new WeakSet;function m(E){return E instanceof Document?E.documentElement:E}function x(E){if(E==null)return document.createElement("div");if(typeof E=="string")return x(L(E));if(u.has(E))return E;if(E instanceof Node){if(E.parentNode)return new b(E);{let A=document.createElement("div");return A.append(E),A}}else{let A=document.createElement("div");for(let T of[...E])A.append(T);return A}}class b{constructor(A){this.originalNode=A,this.realParentNode=A.parentNode,this.previousSibling=A.previousSibling,this.nextSibling=A.nextSibling}get childNodes(){let A=[],T=this.previousSibling?this.previousSibling.nextSibling:this.realParentNode.firstChild;for(;T&&T!=this.nextSibling;)A.push(T),T=T.nextSibling;return A}querySelectorAll(A){return this.childNodes.reduce((T,y)=>{if(y instanceof Element){y.matches(A)&&T.push(y);let S=y.querySelectorAll(A);for(let v=0;v<S.length;v++)T.push(S[v])}return T},[])}insertBefore(A,T){return this.realParentNode.insertBefore(A,T)}moveBefore(A,T){return this.realParentNode.moveBefore(A,T)}get __idiomorphRoot(){return this.originalNode}}function L(E){let A=new DOMParser,T=E.replace(/<svg(\s[^>]*>|>)([\s\S]*?)<\/svg>/gim,"");if(T.match(/<\/html>/)||T.match(/<\/head>/)||T.match(/<\/body>/)){let y=A.parseFromString(E,"text/html");if(T.match(/<\/html>/))return u.add(y),y;{let S=y.firstChild;return S&&u.add(S),S}}else{let S=A.parseFromString("<body><template>"+E+"</template></body>","text/html").body.querySelector("template").content;return u.add(S),S}}return{normalizeElement:m,normalizeParent:x}})();return{morph:r,defaults:t}})();var Wi=(e,t,r={})=>{let{preserveTypingAnimation:o=!0}=r;dh.morph(e,t.innerHTML,{morphStyle:"innerHTML",callbacks:{beforeNodeMorphed(n,a){var s,i;if(n instanceof HTMLElement&&o){if(n.classList.contains("persona-animate-typing")||n.hasAttribute("data-preserve-runtime"))return!1;if(n.hasAttribute("data-preserve-animation")){if(a instanceof HTMLElement&&!a.hasAttribute("data-preserve-animation"))return;if(a instanceof HTMLElement&&a.hasAttribute("data-preserve-animation")){let c=(s=n.textContent)!=null?s:"",l=(i=a.textContent)!=null?i:"";if(c!==l)return}return!1}}}}})};var ch=e=>e.replace(/^\n+/,"").replace(/\s+$/,"");var Hi={index:-1,draft:""};function ph(e){let{direction:t,history:r,currentValue:o,atStart:n,state:a}=e,s=a.index!==-1;if(r.length===0)return{handled:!1,state:a};if(t==="up"){if(!s&&!n)return{handled:!1,state:a};if(!s){let i=r.length-1;return{handled:!0,value:r[i],state:{index:i,draft:o}}}if(a.index>0){let i=a.index-1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,state:a}}if(!s)return{handled:!1,state:a};if(a.index<r.length-1){let i=a.index+1;return{handled:!0,value:r[i],state:{index:i,draft:a.draft}}}return{handled:!0,value:a.draft,state:{...Hi}}}function uh(e,t){var r,o,n,a,s,i,c,l,p,f,u,m,x,b,L,E,A,T,y,S,v,M,W,H,I,D,O,J,me,ce,te,Se,We,de,ve,se,ie,pe;return[e.id,e.role,(o=(r=e.content)==null?void 0:r.length)!=null?o:0,(a=(n=e.content)==null?void 0:n.slice(-32))!=null?a:"",e.streaming?"1":"0",e.voiceProcessing?"1":"0",(s=e.variant)!=null?s:"",(c=(i=e.rawContent)==null?void 0:i.length)!=null?c:0,(p=(l=e.llmContent)==null?void 0:l.length)!=null?p:0,(u=(f=e.approval)==null?void 0:f.status)!=null?u:"",(x=(m=e.toolCall)==null?void 0:m.status)!=null?x:"",(L=(b=e.toolCall)==null?void 0:b.name)!=null?L:"",(T=(A=(E=e.toolCall)==null?void 0:E.chunks)==null?void 0:A.length)!=null?T:0,(M=(v=(S=(y=e.toolCall)==null?void 0:y.chunks)==null?void 0:S[e.toolCall.chunks.length-1])==null?void 0:v.slice(-32))!=null?M:"",typeof((W=e.toolCall)==null?void 0:W.args)=="string"?e.toolCall.args.length:(H=e.toolCall)!=null&&H.args?JSON.stringify(e.toolCall.args).length:0,(O=(D=(I=e.reasoning)==null?void 0:I.chunks)==null?void 0:D.length)!=null?O:0,(te=(ce=(me=(J=e.reasoning)==null?void 0:J.chunks)==null?void 0:me[e.reasoning.chunks.length-1])==null?void 0:ce.length)!=null?te:0,(ve=(de=(We=(Se=e.reasoning)==null?void 0:Se.chunks)==null?void 0:We[e.reasoning.chunks.length-1])==null?void 0:de.slice(-32))!=null?ve:"",(ie=(se=e.contentParts)==null?void 0:se.length)!=null?ie:0,(pe=e.stopReason)!=null?pe:"",t].join("\0")}function fh(){return new Map}function mh(e,t,r){let o=e.get(t);return o&&o.fingerprint===r?o.wrapper:null}function gh(e,t,r,o){e.set(t,{fingerprint:r,wrapper:o})}function hh(e,t){for(let r of e.keys())t.has(r)||e.delete(r)}function Bi(e=!0){let t=e;return{isFollowing:()=>t,pause:()=>t?(t=!1,!0):!1,resume:()=>t?!1:(t=!0,!0)}}function tn(e){return Math.max(0,e.scrollHeight-e.clientHeight)}function ta(e,t){return tn(e)-e.scrollTop<=t}function Di(e){let{following:t,currentScrollTop:r,lastScrollTop:o,nearBottom:n,userScrollThreshold:a,isAutoScrolling:s=!1,pauseOnUpwardScroll:i=!1,pauseWhenAwayFromBottom:c=!0,resumeRequiresDownwardScroll:l=!1}=e,p=r-o;return s||Math.abs(p)<a?{action:"none",delta:p,nextLastScrollTop:r}:!t&&n&&(!l||p>0)?{action:"resume",delta:p,nextLastScrollTop:r}:t&&i&&p<0?{action:"pause",delta:p,nextLastScrollTop:r}:t&&c&&!n?{action:"pause",delta:p,nextLastScrollTop:r}:{action:"none",delta:p,nextLastScrollTop:r}}function Fi(e){let{following:t,deltaY:r,nearBottom:o=!1,resumeWhenNearBottom:n=!1}=e;return t&&r<0?"pause":!t&&n&&r>0&&o?"resume":"none"}function xh(e,t){return!e||e.isCollapsed?!1:t.contains(e.anchorNode)||t.contains(e.focusNode)}function yh(e){let t=Math.max(0,e.anchorOffsetTop-e.topOffset),r=Math.max(0,t+e.viewportHeight-e.contentHeight);return{targetScrollTop:t,spacerHeight:r}}function bh(e){let t=Math.max(0,e.currentContentHeight-e.contentHeightAtAnchor);return Math.max(0,e.initialSpacerHeight-t)}var Ar={idle:"Online",connecting:"Connecting\u2026",connected:"Streaming\u2026",error:"Offline"},Mr=1e5,En=Mr+1;var ws={type:"none",placeholder:"none",speed:120,duration:1800,buffer:"none"},Bb=["pre","code","a","script","style"],Ni=e=>{var t,r,o,n,a;return{type:(t=e==null?void 0:e.type)!=null?t:ws.type,placeholder:(r=e==null?void 0:e.placeholder)!=null?r:ws.placeholder,speed:(o=e==null?void 0:e.speed)!=null?o:ws.speed,duration:(n=e==null?void 0:e.duration)!=null?n:ws.duration,buffer:(a=e==null?void 0:e.buffer)!=null?a:ws.buffer}},wh=[{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"}],Cs=new Map;for(let e of wh)Cs.set(e.name,e);var ra=e=>{Cs.set(e.name,e)},jc=e=>{wh.some(t=>t.name===e)||Cs.delete(e)},Gc=()=>Array.from(Cs.keys()),Ss=(e,t)=>{var r,o;return e==="none"?null:t&&Object.prototype.hasOwnProperty.call(t,e)?(r=t[e])!=null?r:null:(o=Cs.get(e))!=null?o:null},Oi=(e,t,r,o,n)=>{if(!n)return e;if(r!=null&&r.bufferContent)return r.bufferContent(e,o);if(!e)return e;if(t==="word"){let a=e.search(/\s(?=\S*$)/);return a<0?"":e.slice(0,a)}if(t==="line"){let a=e.lastIndexOf(`
20
- `);return a<0?"":e.slice(0,a)}return e},Db=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},Fb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},zc=/\s/,Nb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Ob=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(zc.test(a[i])){let l=i;for(;l<a.length&&zc.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!zc.test(a[p]);)l.appendChild(Db(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(l),i=p}n.replaceChild(s,e)},_b=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(Fb(o,l,t,r.value)),r.value+=1));n.replaceChild(s,e)},As=(e,t,r,o)=>{var f,u;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:Bb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Nb(c,a)||i.push(c),c=s.nextNode();let l={value:(u=o==null?void 0:o.startIndex)!=null?u:0},p=t==="char"?Ob:_b;for(let m of i)p(m,r,l);return n.innerHTML},_i=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ms=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},vh=new WeakMap,Ub=(e,t)=>{var a;if(!e.styles)return;let r=vh.get(t);if(r||(r=new Set,vh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},$c=new WeakMap,qb=(e,t)=>{if(!e.onAttach)return;let r=$c.get(t);if(r||(r=new Map,$c.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Ch=e=>{let t=$c.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Kc=(e,t)=>{Ub(e,t),qb(e,t)};function Xc(e,t=Mr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ts=0,kn=null;function Jc(e=document){var r;if(Ts++,Ts===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;kn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ts=Math.max(0,Ts-1),Ts===0&&kn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=kn.originalOverflow,n.style.position=kn.originalPosition,n.style.top=kn.originalTop,n.style.width=kn.originalWidth,a.scrollTo(0,kn.scrollY),kn=null}}}var Es={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Ln=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Zr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Es.side,width:(n=t==null?void 0:t.width)!=null?n:Es.width,animate:(a=t==null?void 0:t.animate)!=null?a:Es.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Es.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Es.maxHeight}};var Co={"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 Vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ui=(e,t={})=>{var L,E,A,T,y,S;let{showClose:r=!0,wrapperClassName:o=Vb,buttonSize:n,iconSize:a="28px"}=t,s=(L=e==null?void 0:e.launcher)!=null?L:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=w("div",o),l=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,f=(y=s.closeButtonIconName)!=null?y:"x",u=(S=s.closeButtonIconText)!=null?S:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=Mt("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Hr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=fe(f,a,"currentColor",1);if(b?(b.style.display="block",x.appendChild(b)):x.textContent=u,c.appendChild(x),p&&l){let v=null,M=()=>{if(v)return;let H=x.ownerDocument,I=H.body;if(!I)return;v=No(H,"div","persona-clear-chat-tooltip"),v.textContent=l;let D=No(H,"div");D.className="persona-clear-chat-tooltip-arrow",v.appendChild(D);let O=x.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(En),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",I.appendChild(v)},W=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",W),x.addEventListener("focus",M),x.addEventListener("blur",W),c._cleanupTooltip=()=>{W(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",W),x.removeEventListener("focus",M),x.removeEventListener("blur",W)}}return{button:x,wrapper:c}},zb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qi=(e,t={})=>{var v,M,W,H,I,D,O,J,me,ce,te,Se,We;let{wrapperClassName:r=zb,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",p=(D=s.backgroundColor)!=null?D:"",f=(O=s.borderWidth)!=null?O:"",u=(J=s.borderColor)!=null?J:"",m=(me=s.borderRadius)!=null?me:"",x=(ce=s.paddingX)!=null?ce:"",b=(te=s.paddingY)!=null?te:"",L=(Se=s.tooltipText)!=null?Se:"Clear chat",E=(We=s.showTooltip)!=null?We:!0,A=w("div",r),T=!!(f||u),y=Mt("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:i,width:i,color:l||Hr.actionIconColor,backgroundColor:p||void 0,border:T?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),S=fe(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),A.appendChild(y),E&&L){let de=null,ve=()=>{if(de)return;let ie=y.ownerDocument,pe=ie.body;if(!pe)return;de=No(ie,"div","persona-clear-chat-tooltip"),de.textContent=L;let Ve=No(ie,"div");Ve.className="persona-clear-chat-tooltip-arrow",de.appendChild(Ve);let _e=y.getBoundingClientRect();de.style.position="fixed",de.style.zIndex=String(En),de.style.left=`${_e.left+_e.width/2}px`,de.style.top=`${_e.top-8}px`,de.style.transform="translate(-50%, -100%)",pe.appendChild(de)},se=()=>{de&&de.parentNode&&(de.parentNode.removeChild(de),de=null)};A.addEventListener("mouseenter",ve),A.addEventListener("mouseleave",se),y.addEventListener("focus",ve),y.addEventListener("blur",se),A._cleanupTooltip=()=>{se(),A.removeEventListener("mouseenter",ve),A.removeEventListener("mouseleave",se),y.removeEventListener("focus",ve),y.removeEventListener("blur",se)}}return{button:y,wrapper:A}};var Hr={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))"},rn=e=>{var S,v,M,W,H,I,D,O,J,me,ce,te,Se,We,de,ve;let{config:t,showClose:r=!0}=e,o=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)))"}}),n=(S=t==null?void 0:t.launcher)!=null?S:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,l=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let se=parseFloat(a)||24,ie=fe(c,se*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(I=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?I:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let se=w("img");se.src=t.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=a,se.style.width=a,l.replaceChildren(se)}else l.textContent=(J=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?J:"\u{1F4AC}";let p=w("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Mt("span",{className:"persona-text-base persona-font-semibold",text:(ce=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ce:"Chat Assistant",style:{color:Hr.titleColor}}),u=Mt("span",{className:"persona-text-xs",text:(Se=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Se:"Here to help you get answers fast",style:{color:Hr.subtitleColor}});p.append(f,u),i?o.append(p):o.append(l,p);let m=(We=n.clearChat)!=null?We:{},x=(de=m.enabled)!=null?de:!0,b=(ve=m.placement)!=null?ve:"inline",L=null,E=null;if(x){let ie=qi(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=ie.button,E=ie.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&b==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:y}=Ui(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:T,closeButtonWrapper:y,clearChatButton:L,clearChatButtonWrapper:E}},oa=(e,t,r)=>{var s,i,c,l;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(c=o.clearChat)==null?void 0:c.placement)!=null?l:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Pn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=w("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(En)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let L=fe(m.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let b=document.createElement("span");b.textContent=m.label,x.appendChild(b),x.addEventListener("click",L=>{L.stopPropagation(),p(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function cr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=w("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let l=fe(t,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&c.appendChild(l),s&&c.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))c.setAttribute(p,f);return c}function ks(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let p=w("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let u=fe(t,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=w("span");if(f.textContent=r,p.appendChild(f),i&&p.addEventListener("click",i),c)for(let[u,m]of Object.entries(c))p.setAttribute(u,m);return p}function Sh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=w("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let f;p.icon?f=cr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(f=w("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,c()}return{element:a,setSelected:l}}function Vi(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,l=w("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=w("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let f=fe(r,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),c&&(l.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",l.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var b,L;l.style.backgroundColor=(b=c.background)!=null?b:"",l.style.borderColor=(L=c.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Pn({items:o,onSelect:b=>{l.setAttribute("aria-expanded","false"),n(b)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",b=>{b.stopPropagation();let L=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),u.toggle()}),l.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l.click())}),{element:l,setLabel:b=>{p.textContent=b,l.setAttribute("aria-label",b)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let b=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",b?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Qc=e=>{var o;let t=rn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function $b(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=fe(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=w("div","persona-relative");c.appendChild(i);let l=Pn({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var Yc=e=>{var A,T,y,S,v,M,W,H,I;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=w("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,l,p;if(c)l=Vi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,l.style.color=Hr.titleColor,p=(y=l.querySelector(".persona-combo-btn-label"))!=null?y:l;else{if(l=w("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=w("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Hr.titleColor,p.textContent=(S=s.title)!=null?S:"Chat Assistant",l.appendChild(p),$b(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=n.onTitleClick;l.addEventListener("click",J=>{J.target.closest("button")||O()}),l.addEventListener("keydown",J=>{(J.key==="Enter"||J.key===" ")&&(J.preventDefault(),O())})}let D=n==null?void 0:n.titleRowHover;D&&(l.style.borderRadius=(M=D.borderRadius)!=null?M:"10px",l.style.padding=(W=D.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,J;l.style.backgroundColor=(O=D.background)!=null?O:"",l.style.borderColor=(J=D.border)!=null?J:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(H=s.closeButtonSize)!=null?H:"32px",u=w("div",""),m=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||Hr.actionIconColor;let x=(I=s.closeButtonIconName)!=null?I:"x",b=fe(x,"28px","currentColor",1);b?m.appendChild(b):m.textContent="\xD7",o&&m.addEventListener("click",o),u.appendChild(m),i.appendChild(u);let L=w("div");L.style.display="none";let E=w("span");return E.style.display="none",{header:i,iconHolder:L,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},zi={default:Qc,minimal:Yc},Zc=e=>{var t;return(t=zi[e])!=null?t:zi.default},Da=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=w("div");p.style.display="none";let f=w("span"),u=w("span"),m=w("button");m.style.display="none";let x=w("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=Zc(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var $i=e=>{var s,i;let t=w("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},ji=e=>{var S,v,M,W,H,I,D,O,J,me,ce,te;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(H=t.tooltipText)!=null?H:"Send message",i=(I=t.stopTooltipText)!=null?I:"Stop generating",c=(O=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?O:"Send",l=(me=(J=e==null?void 0:e.copy)==null?void 0:J.stopButtonLabel)!=null?me:"Stop",p=(ce=t.showTooltip)!=null?ce:!1,f=(te=t.size)!=null?te:"40px",u=t.backgroundColor,m=t.textColor,x=w("div","persona-send-button-wrapper"),b=Mt("button",{className:ss("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!u&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?f:void 0,height:r?f:void 0,minWidth:r?f:void 0,minHeight:r?f:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&u||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}}),L=null,E=null;if(r){let Se=parseFloat(f)||24,We=(m==null?void 0:m.trim())||"currentColor";n?(L=fe(n,Se,We,2),L?b.appendChild(L):b.textContent=o):b.textContent=o,E=fe(a,Se,We,2)}else b.textContent=c;let A=null;p&&s&&(A=w("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),b.setAttribute("aria-label",s),x.appendChild(b);let T="send";return{button:b,wrapper:x,setMode:Se=>{if(Se===T)return;T=Se;let We=Se==="stop"?i:s;if(b.setAttribute("aria-label",We),A&&(A.textContent=We),r){if(L&&E){let de=Se==="stop"?E:L;b.replaceChildren(de)}}else b.textContent=Se==="stop"?l:c}}},Gi=e=>{var A,T,y,S,v,M,W,H,I,D,O,J;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(S=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?S:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,l=parseFloat(c)||24,p=(H=t.backgroundColor)!=null?H:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,f=(D=t.iconColor)!=null?D:(I=e==null?void 0:e.sendButton)==null?void 0:I.textColor,u=w("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=fe(i,l,f||"currentColor",1.5);b?m.appendChild(b):m.textContent="\u{1F3A4}",u.appendChild(m);let L=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((J=t.showTooltip)!=null?J:!1)&&L){let me=w("div","persona-send-button-tooltip");me.textContent=L,u.appendChild(me)}return{button:m,wrapper:u}},Ki=e=>{var x,b,L,E,A,T,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(L=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?L:"40px",o=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=w("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:en).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),l=w("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":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let f=fe(a,c,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),l.appendChild(p);let u=(S=t.buttonTooltipText)!=null?S:"Attach file",m=w("div","persona-send-button-tooltip");return m.textContent=u,l.appendChild(m),{button:p,wrapper:l,input:n,previewsContainer:o}},Xi=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=w("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let l=w("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},Ji=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Fa=e=>{var x,b,L,E,A,T;let{config:t}=e,r=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"}}),o=Ji(),n=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:a,attachAutoResize:s}=$i(t);s();let i=ji(t),c=Gi(t),l=Ki(t),p=Xi(t);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=w("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=w("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),f.append(u,m),n.append(f),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=w("span","persona-pill-peek__icon"),r=fe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=w("span","persona-pill-peek__text"),n=w("span","persona-pill-peek__caret"),a=fe("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,b,L,E,A,T;let{config:t}=e,r=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ji();o.style.display="none";let n=Xi(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=$i(t);a.style.maxHeight="100px",s();let i=ji(t),c=Gi(t),l=Ki(t);l&&l.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"}}),f=w("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=w("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&u.append(c.wrapper),u.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&r.append(l.previewsContainer),r.append(p,o,n);let m=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Th=e=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,W,H,I;let t=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?f:!0,r=nr(e);if(Ln(e)){let D=(m=(u=e==null?void 0:e.launcher)==null?void 0:u.composerBar)!=null?m:{},O=w("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(x=D.expandedSize)!=null?x:"anchored",O.style.zIndex=String((L=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?L:Mr);let J=w("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");J.style.width="100%",O.appendChild(J);let me=w("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=D.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:Mr),{wrapper:O,panel:J,pillRoot:me}}if(r){let D=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return D.appendChild(O),{wrapper:D,panel:O}}if(!t){let D=w("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=w("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),J=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return D.style.width=J,O.style.width="100%",D.appendChild(O),{wrapper:D,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&Co[n.position]?Co[n.position]:Co["bottom-right"],s=w("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?W:Mr);let i=w("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(I=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?I:e==null?void 0:e.launcherWidth,l=c!=null?c:Yr;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},jb=(e,t)=>{var y,S,v,M,W,H,I,D,O;let r=w("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?v:!0,s=null,i=null;if(a){let J=qi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=J.button,i=J.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=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"}});l.style.setProperty("scrollbar-gutter","stable");let p=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),f=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),u=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},p,f),m=w("div","persona-flex persona-flex-col persona-gap-3"),x=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let L=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=Mh({config:e}),{root:A,textNode:T}=Ah();return r.append(c,n,l,L),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:L,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:f,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:w("span"),headerTitle:w("span"),headerSubtitle:w("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},Eh=(e,t=!0)=>{var L,E,A,T,y,S,v,M,W;if(Ln(e))return jb(e,t);let r=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"}}),o=(L=e==null?void 0:e.layout)==null?void 0:L.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Da(e,o,{showClose:t}):rn({config:e,showClose:t}),s=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"}});s.style.setProperty("scrollbar-gutter","stable");let i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products."}),l=Mt("div",{className:"persona-rounded-2xl persona-bg-persona-surface persona-p-6",attrs:{"data-persona-intro-card":""},style:{boxShadow:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=w("div","persona-flex persona-flex-col persona-gap-3"),f=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(l.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(l,p);let m=Fa({config:e}),x=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;n?oa(r,a,e):(a.header.style.display="none",oa(r,a,e)),r.append(s);let b=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 x||(m.footer.style.display="none"),r.append(m.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var ep=(e,t)=>{let r=w("button");r.type="button",r.innerHTML=`
20
+ `);return a<0?"":e.slice(0,a)}return e},Db=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-char",n.id=`stream-c-${r}-${o}`,n.style.setProperty("--char-index",String(o)),n.textContent=t,n},Fb=(e,t,r,o)=>{let n=e.createElement("span");return n.className="persona-stream-word",n.id=`stream-w-${r}-${o}`,n.style.setProperty("--word-index",String(o)),n.textContent=t,n},zc=/\s/,Nb=(e,t)=>{let r=e.parentNode;for(;r;){if(r.nodeType===1){let o=r;if(t.has(o.tagName.toLowerCase()))return!0}r=r.parentNode}return!1},Ob=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=0;for(;i<a.length;)if(zc.test(a[i])){let l=i;for(;l<a.length&&zc.test(a[l]);)l+=1;s.appendChild(o.createTextNode(a.slice(i,l))),i=l}else{let l=o.createElement("span");l.className="persona-stream-word-group";let p=i;for(;p<a.length&&!zc.test(a[p]);)l.appendChild(Db(o,a[p],t,r.value)),r.value+=1,p+=1;s.appendChild(l),i=p}n.replaceChild(s,e)},_b=(e,t,r)=>{var c;let o=e.ownerDocument,n=e.parentNode;if(!o||!n)return;let a=(c=e.nodeValue)!=null?c:"";if(!a)return;let s=o.createDocumentFragment(),i=a.split(/(\s+)/);for(let l of i)l&&(/^\s+$/.test(l)?s.appendChild(o.createTextNode(l)):(s.appendChild(Fb(o,l,t,r.value)),r.value+=1));n.replaceChild(s,e)},As=(e,t,r,o)=>{var f,u;if(!e||typeof document=="undefined")return e;let n=document.createElement("div");n.innerHTML=e;let a=new Set(((f=o==null?void 0:o.skipTags)!=null?f:Bb).map(m=>m.toLowerCase())),s=document.createTreeWalker(n,NodeFilter.SHOW_TEXT,null),i=[],c=s.nextNode();for(;c;)Nb(c,a)||i.push(c),c=s.nextNode();let l={value:(u=o==null?void 0:o.startIndex)!=null?u:0},p=t==="char"?Ob:_b;for(let m of i)p(m,r,l);return n.innerHTML},_i=(e=document)=>{let t=e.createElement("span");return t.className="persona-stream-caret",t.setAttribute("aria-hidden","true"),t.setAttribute("data-preserve-animation","stream-caret"),t},Ms=(e=document)=>{let t=e.createElement("div");t.className="persona-stream-skeleton",t.setAttribute("data-preserve-animation","stream-skeleton"),t.setAttribute("aria-hidden","true");let r=e.createElement("div");return r.className="persona-stream-skeleton-line",t.appendChild(r),t},vh=new WeakMap,Ub=(e,t)=>{var a;if(!e.styles)return;let r=vh.get(t);if(r||(r=new Set,vh.set(t,r)),r.has(e.name)){let s=e.name.replace(/["\\]/g,"\\$&");if(t.querySelector(`style[data-persona-animation="${s}"]`))return;r.delete(e.name)}r.add(e.name);let n=(t instanceof ShadowRoot?t.ownerDocument:(a=t.ownerDocument)!=null?a:document).createElement("style");n.setAttribute("data-persona-animation",e.name),n.textContent=e.styles,t.appendChild(n)},$c=new WeakMap,qb=(e,t)=>{if(!e.onAttach)return;let r=$c.get(t);if(r||(r=new Map,$c.set(t,r)),r.has(e.name))return;let o=e.onAttach(t);r.set(e.name,o)},Ch=e=>{let t=$c.get(e);if(t){for(let r of t.values())typeof r=="function"&&r();t.clear()}},Kc=(e,t)=>{Ub(e,t),qb(e,t)};function Xc(e,t=Mr){let r=e.style.position,o=e.style.zIndex,n=e.style.isolation,a=getComputedStyle(e),s=a.position==="static"||a.position==="";return s&&(e.style.position="relative"),e.style.zIndex=String(t),e.style.isolation="isolate",()=>{s&&(e.style.position=r),e.style.zIndex=o,e.style.isolation=n}}var Ts=0,kn=null;function Jc(e=document){var r;if(Ts++,Ts===1){let o=e.body,a=((r=e.defaultView)!=null?r:window).scrollY||e.documentElement.scrollTop;kn={originalOverflow:o.style.overflow,originalPosition:o.style.position,originalTop:o.style.top,originalWidth:o.style.width,scrollY:a},o.style.overflow="hidden",o.style.position="fixed",o.style.top=`-${a}px`,o.style.width="100%"}let t=!1;return()=>{var o;if(!t&&(t=!0,Ts=Math.max(0,Ts-1),Ts===0&&kn)){let n=e.body,a=(o=e.defaultView)!=null?o:window;n.style.overflow=kn.originalOverflow,n.style.position=kn.originalPosition,n.style.top=kn.originalTop,n.style.width=kn.originalWidth,a.scrollTo(0,kn.scrollY),kn=null}}}var Es={side:"right",width:"420px",animate:!0,reveal:"resize",maxHeight:"100dvh"},nr=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="docked"},Ln=e=>{var t,r;return((r=(t=e==null?void 0:e.launcher)==null?void 0:t.mountMode)!=null?r:"floating")==="composer-bar"},Zr=e=>{var r,o,n,a,s,i;let t=(r=e==null?void 0:e.launcher)==null?void 0:r.dock;return{side:(o=t==null?void 0:t.side)!=null?o:Es.side,width:(n=t==null?void 0:t.width)!=null?n:Es.width,animate:(a=t==null?void 0:t.animate)!=null?a:Es.animate,reveal:(s=t==null?void 0:t.reveal)!=null?s:Es.reveal,maxHeight:(i=t==null?void 0:t.maxHeight)!=null?i:Es.maxHeight}};var Co={"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 Vb="persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",Ui=(e,t={})=>{var L,E,A,T,y,S;let{showClose:r=!0,wrapperClassName:o=Vb,buttonSize:n,iconSize:a="28px"}=t,s=(L=e==null?void 0:e.launcher)!=null?L:{},i=(E=n!=null?n:s.closeButtonSize)!=null?E:"32px",c=w("div",o),l=(A=s.closeButtonTooltipText)!=null?A:"Close chat",p=(T=s.closeButtonShowTooltip)!=null?T:!0,f=(y=s.closeButtonIconName)!=null?y:"x",u=(S=s.closeButtonIconText)!=null?S:"\xD7",m=!!(s.closeButtonBorderWidth||s.closeButtonBorderColor),x=Mt("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!s.closeButtonBackgroundColor&&"hover:persona-bg-gray-100",!m&&"persona-border-none",!s.closeButtonBorderRadius&&"persona-rounded-full"),attrs:{type:"button","aria-label":l},style:{height:i,width:i,display:r?void 0:"none",color:s.closeButtonColor||Hr.actionIconColor,backgroundColor:s.closeButtonBackgroundColor||void 0,border:m?`${s.closeButtonBorderWidth||"0px"} solid ${s.closeButtonBorderColor||"transparent"}`:void 0,borderRadius:s.closeButtonBorderRadius||void 0,paddingLeft:s.closeButtonPaddingX||void 0,paddingRight:s.closeButtonPaddingX||void 0,paddingTop:s.closeButtonPaddingY||void 0,paddingBottom:s.closeButtonPaddingY||void 0}}),b=fe(f,a,"currentColor",1);if(b?(b.style.display="block",x.appendChild(b)):x.textContent=u,c.appendChild(x),p&&l){let v=null,M=()=>{if(v)return;let H=x.ownerDocument,I=H.body;if(!I)return;v=No(H,"div","persona-clear-chat-tooltip"),v.textContent=l;let D=No(H,"div");D.className="persona-clear-chat-tooltip-arrow",v.appendChild(D);let O=x.getBoundingClientRect();v.style.position="fixed",v.style.zIndex=String(En),v.style.left=`${O.left+O.width/2}px`,v.style.top=`${O.top-8}px`,v.style.transform="translate(-50%, -100%)",I.appendChild(v)},W=()=>{v&&v.parentNode&&(v.parentNode.removeChild(v),v=null)};c.addEventListener("mouseenter",M),c.addEventListener("mouseleave",W),x.addEventListener("focus",M),x.addEventListener("blur",W),c._cleanupTooltip=()=>{W(),c.removeEventListener("mouseenter",M),c.removeEventListener("mouseleave",W),x.removeEventListener("focus",M),x.removeEventListener("blur",W)}}return{button:x,wrapper:c}},zb="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",qi=(e,t={})=>{var v,M,W,H,I,D,O,J,me,ce,te,Se,We;let{wrapperClassName:r=zb,buttonSize:o,iconSize:n="20px"}=t,s=(M=((v=e==null?void 0:e.launcher)!=null?v:{}).clearChat)!=null?M:{},i=(W=o!=null?o:s.size)!=null?W:"32px",c=(H=s.iconName)!=null?H:"refresh-cw",l=(I=s.iconColor)!=null?I:"",p=(D=s.backgroundColor)!=null?D:"",f=(O=s.borderWidth)!=null?O:"",u=(J=s.borderColor)!=null?J:"",m=(me=s.borderRadius)!=null?me:"",x=(ce=s.paddingX)!=null?ce:"",b=(te=s.paddingY)!=null?te:"",L=(Se=s.tooltipText)!=null?Se:"Clear chat",E=(We=s.showTooltip)!=null?We:!0,A=w("div",r),T=!!(f||u),y=Mt("button",{className:ss("persona-inline-flex persona-items-center persona-justify-center persona-cursor-pointer",!p&&"hover:persona-bg-gray-100",!T&&"persona-border-none",!m&&"persona-rounded-full"),attrs:{type:"button","aria-label":L},style:{height:i,width:i,color:l||Hr.actionIconColor,backgroundColor:p||void 0,border:T?`${f||"0px"} solid ${u||"transparent"}`:void 0,borderRadius:m||void 0,paddingLeft:x||void 0,paddingRight:x||void 0,paddingTop:b||void 0,paddingBottom:b||void 0}}),S=fe(c,n,"currentColor",1);if(S&&(S.style.display="block",y.appendChild(S)),A.appendChild(y),E&&L){let de=null,ve=()=>{if(de)return;let ie=y.ownerDocument,pe=ie.body;if(!pe)return;de=No(ie,"div","persona-clear-chat-tooltip"),de.textContent=L;let Ve=No(ie,"div");Ve.className="persona-clear-chat-tooltip-arrow",de.appendChild(Ve);let _e=y.getBoundingClientRect();de.style.position="fixed",de.style.zIndex=String(En),de.style.left=`${_e.left+_e.width/2}px`,de.style.top=`${_e.top-8}px`,de.style.transform="translate(-50%, -100%)",pe.appendChild(de)},se=()=>{de&&de.parentNode&&(de.parentNode.removeChild(de),de=null)};A.addEventListener("mouseenter",ve),A.addEventListener("mouseleave",se),y.addEventListener("focus",ve),y.addEventListener("blur",se),A._cleanupTooltip=()=>{se(),A.removeEventListener("mouseenter",ve),A.removeEventListener("mouseleave",se),y.removeEventListener("focus",ve),y.removeEventListener("blur",se)}}return{button:y,wrapper:A}};var Hr={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))"},rn=e=>{var S,v,M,W,H,I,D,O,J,me,ce,te,Se,We,de,ve;let{config:t,showClose:r=!0}=e,o=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)))"}}),n=(S=t==null?void 0:t.launcher)!=null?S:{},a=(v=n.headerIconSize)!=null?v:"48px",s=(M=n.closeButtonPlacement)!=null?M:"inline",i=(W=n.headerIconHidden)!=null?W:!1,c=n.headerIconName,l=Mt("div",{className:"persona-flex persona-items-center persona-justify-center persona-rounded-xl persona-text-xl",style:{height:a,width:a,backgroundColor:"var(--persona-header-icon-bg, var(--persona-primary, #0f0f0f))",color:"var(--persona-header-icon-fg, var(--persona-text-inverse, #ffffff))"}});if(!i)if(c){let se=parseFloat(a)||24,ie=fe(c,se*.6,"currentColor",1);ie?l.replaceChildren(ie):l.textContent=(I=(H=t==null?void 0:t.launcher)==null?void 0:H.agentIconText)!=null?I:"\u{1F4AC}"}else if((D=t==null?void 0:t.launcher)!=null&&D.iconUrl){let se=w("img");se.src=t.launcher.iconUrl,se.alt="",se.className="persona-rounded-xl persona-object-cover",se.style.height=a,se.style.width=a,l.replaceChildren(se)}else l.textContent=(J=(O=t==null?void 0:t.launcher)==null?void 0:O.agentIconText)!=null?J:"\u{1F4AC}";let p=w("div","persona-flex persona-flex-col persona-flex-1 persona-min-w-0"),f=Mt("span",{className:"persona-text-base persona-font-semibold",text:(ce=(me=t==null?void 0:t.launcher)==null?void 0:me.title)!=null?ce:"Chat Assistant",style:{color:Hr.titleColor}}),u=Mt("span",{className:"persona-text-xs",text:(Se=(te=t==null?void 0:t.launcher)==null?void 0:te.subtitle)!=null?Se:"Here to help you get answers fast",style:{color:Hr.subtitleColor}});p.append(f,u),i?o.append(p):o.append(l,p);let m=(We=n.clearChat)!=null?We:{},x=(de=m.enabled)!=null?de:!0,b=(ve=m.placement)!=null?ve:"inline",L=null,E=null;if(x){let ie=qi(t,{wrapperClassName:b==="top-right"?"persona-absolute persona-top-4 persona-z-50":"persona-relative persona-ml-auto persona-clear-chat-button-wrapper"});L=ie.button,E=ie.wrapper,b==="top-right"&&(E.style.right="48px"),b==="inline"&&o.appendChild(E)}let A=s==="top-right"?"persona-absolute persona-top-4 persona-right-4 persona-z-50":x&&b==="inline"?"persona-relative persona-inline-flex persona-items-center persona-justify-center":"persona-relative persona-ml-auto persona-inline-flex persona-items-center persona-justify-center",{button:T,wrapper:y}=Ui(t,{showClose:r,wrapperClassName:A});return s!=="top-right"&&o.appendChild(y),{header:o,iconHolder:l,headerTitle:f,headerSubtitle:u,closeButton:T,closeButtonWrapper:y,clearChatButton:L,clearChatButtonWrapper:E}},oa=(e,t,r)=>{var s,i,c,l;let o=(s=r==null?void 0:r.launcher)!=null?s:{},n=(i=o.closeButtonPlacement)!=null?i:"inline",a=(l=(c=o.clearChat)==null?void 0:c.placement)!=null?l:"inline";e.appendChild(t.header),n==="top-right"&&(e.style.position="relative",e.appendChild(t.closeButtonWrapper)),t.clearChatButtonWrapper&&a==="top-right"&&(e.style.position="relative",e.appendChild(t.clearChatButtonWrapper))};function Pn(e){let{items:t,onSelect:r,anchor:o,position:n="bottom-left",portal:a}=e,s=w("div","persona-dropdown-menu persona-hidden");s.setAttribute("role","menu"),s.setAttribute("data-persona-theme-zone","dropdown"),a?(s.style.position="fixed",s.style.zIndex=String(En)):(s.style.position="absolute",s.style.top="100%",s.style.marginTop="4px",n==="bottom-right"?s.style.right="0":s.style.left="0");for(let m of t){if(m.dividerBefore){let L=document.createElement("hr");s.appendChild(L)}let x=document.createElement("button");if(x.type="button",x.setAttribute("role","menuitem"),x.setAttribute("data-dropdown-item-id",m.id),m.destructive&&x.setAttribute("data-destructive",""),m.icon){let L=fe(m.icon,16,"currentColor",1.5);L&&x.appendChild(L)}let b=document.createElement("span");b.textContent=m.label,x.appendChild(b),x.addEventListener("click",L=>{L.stopPropagation(),p(),r(m.id)}),s.appendChild(x)}let i=null;function c(){if(!a)return;let m=o.getBoundingClientRect();s.style.top=`${m.bottom+4}px`,n==="bottom-right"?(s.style.right=`${window.innerWidth-m.right}px`,s.style.left="auto"):(s.style.left=`${m.left}px`,s.style.right="auto")}function l(){c(),s.classList.remove("persona-hidden"),requestAnimationFrame(()=>{let m=x=>{!s.contains(x.target)&&!o.contains(x.target)&&p()};document.addEventListener("click",m,!0),i=()=>document.removeEventListener("click",m,!0)})}function p(){s.classList.add("persona-hidden"),i==null||i(),i=null}function f(){s.classList.contains("persona-hidden")?l():p()}function u(){p(),s.remove()}return a&&a.appendChild(s),{element:s,show:l,hide:p,toggle:f,destroy:u}}function cr(e){let{icon:t,label:r,size:o,strokeWidth:n,className:a,onClick:s,aria:i}=e,c=w("button","persona-icon-btn"+(a?" "+a:""));c.type="button",c.setAttribute("aria-label",r),c.title=r;let l=fe(t,o!=null?o:16,"currentColor",n!=null?n:2);if(l&&c.appendChild(l),s&&c.addEventListener("click",s),i)for(let[p,f]of Object.entries(i))c.setAttribute(p,f);return c}function ks(e){let{icon:t,label:r,variant:o="default",size:n="sm",iconSize:a,className:s,onClick:i,aria:c}=e,l="persona-label-btn";o!=="default"&&(l+=" persona-label-btn--"+o),l+=" persona-label-btn--"+n,s&&(l+=" "+s);let p=w("button",l);if(p.type="button",p.setAttribute("aria-label",r),t){let u=fe(t,a!=null?a:14,"currentColor",2);u&&p.appendChild(u)}let f=w("span");if(f.textContent=r,p.appendChild(f),i&&p.addEventListener("click",i),c)for(let[u,m]of Object.entries(c))p.setAttribute(u,m);return p}function Sh(e){let{items:t,selectedId:r,onSelect:o,className:n}=e,a=w("div","persona-toggle-group"+(n?" "+n:""));a.setAttribute("role","group");let s=r,i=[];function c(){for(let p of i)p.btn.setAttribute("aria-pressed",p.id===s?"true":"false")}for(let p of t){let f;p.icon?f=cr({icon:p.icon,label:p.label,onClick:()=>{s=p.id,c(),o(p.id)}}):(f=w("button","persona-icon-btn"),f.type="button",f.setAttribute("aria-label",p.label),f.title=p.label,f.textContent=p.label,f.addEventListener("click",()=>{s=p.id,c(),o(p.id)})),f.setAttribute("aria-pressed",p.id===s?"true":"false"),i.push({id:p.id,btn:f}),a.appendChild(f)}function l(p){s=p,c()}return{element:a,setSelected:l}}function Vi(e){var m,x;let{label:t,icon:r="chevron-down",menuItems:o,onSelect:n,position:a="bottom-left",portal:s,className:i,hover:c}=e,l=w("div","persona-combo-btn"+(i?" "+i:""));l.style.position="relative",l.style.display="inline-flex",l.style.alignItems="center",l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0"),l.setAttribute("aria-haspopup","true"),l.setAttribute("aria-expanded","false"),l.setAttribute("aria-label",t);let p=w("span","persona-combo-btn-label");p.textContent=t,l.appendChild(p);let f=fe(r,14,"currentColor",2);f&&(f.style.marginLeft="4px",f.style.opacity="0.6",l.appendChild(f)),c&&(l.style.borderRadius=(m=c.borderRadius)!=null?m:"10px",l.style.padding=(x=c.padding)!=null?x:"6px 4px 6px 12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.addEventListener("mouseenter",()=>{var b,L;l.style.backgroundColor=(b=c.background)!=null?b:"",l.style.borderColor=(L=c.border)!=null?L:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}));let u=Pn({items:o,onSelect:b=>{l.setAttribute("aria-expanded","false"),n(b)},anchor:l,position:a,portal:s});return s||l.appendChild(u.element),l.addEventListener("click",b=>{b.stopPropagation();let L=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",L?"false":"true"),u.toggle()}),l.addEventListener("keydown",b=>{(b.key==="Enter"||b.key===" ")&&(b.preventDefault(),l.click())}),{element:l,setLabel:b=>{p.textContent=b,l.setAttribute("aria-label",b)},open:()=>{l.setAttribute("aria-expanded","true"),u.show()},close:()=>{l.setAttribute("aria-expanded","false"),u.hide()},toggle:()=>{let b=!u.element.classList.contains("persona-hidden");l.setAttribute("aria-expanded",b?"false":"true"),u.toggle()},destroy:()=>{u.destroy(),l.remove()}}}var Qc=e=>{var o;let t=rn({config:e.config,showClose:e.showClose,onClose:e.onClose,onClearChat:e.onClearChat}),r=(o=e.layoutHeaderConfig)==null?void 0:o.onTitleClick;if(r){let n=t.headerTitle.parentElement;n&&(n.style.cursor="pointer",n.setAttribute("role","button"),n.setAttribute("tabindex","0"),n.addEventListener("click",()=>r()),n.addEventListener("keydown",a=>{(a.key==="Enter"||a.key===" ")&&(a.preventDefault(),r())}))}return t};function $b(e,t,r){var o,n,a;if(t!=null&&t.length)for(let s of t){let i=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-md persona-border-none persona-bg-transparent persona-p-0 persona-text-persona-muted hover:persona-opacity-80");if(i.type="button",i.setAttribute("aria-label",(n=(o=s.ariaLabel)!=null?o:s.label)!=null?n:s.id),s.icon){let c=fe(s.icon,14,"currentColor",2);c&&i.appendChild(c)}else s.label&&(i.textContent=s.label);if((a=s.menuItems)!=null&&a.length){let c=w("div","persona-relative");c.appendChild(i);let l=Pn({items:s.menuItems,onSelect:p=>r==null?void 0:r(p),anchor:c,position:"bottom-left"});c.appendChild(l.element),i.addEventListener("click",p=>{p.stopPropagation(),l.toggle()}),e.appendChild(c)}else i.addEventListener("click",()=>r==null?void 0:r(s.id)),e.appendChild(i)}}var Yc=e=>{var A,T,y,S,v,M,W,H,I;let{config:t,showClose:r=!0,onClose:o,layoutHeaderConfig:n,onHeaderAction:a}=e,s=(A=t==null?void 0:t.launcher)!=null?A:{},i=w("div","persona-flex persona-items-center persona-justify-between persona-px-6 persona-py-4");i.setAttribute("data-persona-theme-zone","header"),i.style.backgroundColor="var(--persona-header-bg, var(--persona-surface, #ffffff))",i.style.borderBottomColor="var(--persona-header-border, var(--persona-divider, #f1f5f9))",i.style.boxShadow="var(--persona-header-shadow, none)",i.style.borderBottom="var(--persona-header-border-bottom, 1px solid var(--persona-header-border, var(--persona-divider, #f1f5f9)))";let c=n==null?void 0:n.titleMenu,l,p;if(c)l=Vi({label:(T=s.title)!=null?T:"Chat Assistant",menuItems:c.menuItems,onSelect:c.onSelect,hover:c.hover,className:""}).element,l.style.color=Hr.titleColor,p=(y=l.querySelector(".persona-combo-btn-label"))!=null?y:l;else{if(l=w("div","persona-flex persona-min-w-0 persona-flex-1 persona-items-center persona-gap-1"),p=w("span","persona-text-base persona-font-semibold persona-truncate"),p.style.color=Hr.titleColor,p.textContent=(S=s.title)!=null?S:"Chat Assistant",l.appendChild(p),$b(l,n==null?void 0:n.trailingActions,(v=n==null?void 0:n.onAction)!=null?v:a),n!=null&&n.onTitleClick){l.style.cursor="pointer",l.setAttribute("role","button"),l.setAttribute("tabindex","0");let O=n.onTitleClick;l.addEventListener("click",J=>{J.target.closest("button")||O()}),l.addEventListener("keydown",J=>{(J.key==="Enter"||J.key===" ")&&(J.preventDefault(),O())})}let D=n==null?void 0:n.titleRowHover;D&&(l.style.borderRadius=(M=D.borderRadius)!=null?M:"10px",l.style.padding=(W=D.padding)!=null?W:"6px 4px 6px 12px",l.style.margin="-6px 0 -6px -12px",l.style.border="1px solid transparent",l.style.transition="background-color 0.15s ease, border-color 0.15s ease",l.style.width="fit-content",l.style.flex="none",l.addEventListener("mouseenter",()=>{var O,J;l.style.backgroundColor=(O=D.background)!=null?O:"",l.style.borderColor=(J=D.border)!=null?J:""}),l.addEventListener("mouseleave",()=>{l.style.backgroundColor="",l.style.borderColor="transparent"}))}i.appendChild(l);let f=(H=s.closeButtonSize)!=null?H:"32px",u=w("div",""),m=w("button","persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-bg-gray-100 persona-cursor-pointer persona-border-none");m.style.height=f,m.style.width=f,m.type="button",m.setAttribute("aria-label","Close chat"),m.style.display=r?"":"none",m.style.color=s.closeButtonColor||Hr.actionIconColor;let x=(I=s.closeButtonIconName)!=null?I:"x",b=fe(x,"28px","currentColor",1);b?m.appendChild(b):m.textContent="\xD7",o&&m.addEventListener("click",o),u.appendChild(m),i.appendChild(u);let L=w("div");L.style.display="none";let E=w("span");return E.style.display="none",{header:i,iconHolder:L,headerTitle:p,headerSubtitle:E,closeButton:m,closeButtonWrapper:u,clearChatButton:null,clearChatButtonWrapper:null}},zi={default:Qc,minimal:Yc},Zc=e=>{var t;return(t=zi[e])!=null?t:zi.default},Da=(e,t,r)=>{var s,i,c;if(t!=null&&t.render){let l=t.render({config:e,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,trailingActions:t.trailingActions,onAction:t.onAction}),p=w("div");p.style.display="none";let f=w("span"),u=w("span"),m=w("button");m.style.display="none";let x=w("div");return x.style.display="none",{header:l,iconHolder:p,headerTitle:f,headerSubtitle:u,closeButton:m,closeButtonWrapper:x,clearChatButton:null,clearChatButtonWrapper:null}}let o=(s=t==null?void 0:t.layout)!=null?s:"default",a=Zc(o)({config:e,showClose:(c=(i=t==null?void 0:t.showCloseButton)!=null?i:r==null?void 0:r.showClose)!=null?c:!0,onClose:r==null?void 0:r.onClose,onClearChat:r==null?void 0:r.onClearChat,layoutHeaderConfig:t,onHeaderAction:t==null?void 0:t.onAction});return t&&(t.showIcon===!1&&(a.iconHolder.style.display="none"),t.showTitle===!1&&(a.headerTitle.style.display="none"),t.showSubtitle===!1&&(a.headerSubtitle.style.display="none"),t.showCloseButton===!1&&(a.closeButton.style.display="none"),t.showClearChat===!1&&a.clearChatButtonWrapper&&(a.clearChatButtonWrapper.style.display="none")),a};var $i=e=>{var s,i;let t=w("textarea");t.setAttribute("data-persona-composer-input",""),t.placeholder=(i=(s=e==null?void 0:e.copy)==null?void 0:s.inputPlaceholder)!=null?i:"Type your message\u2026",t.className="persona-w-full persona-min-h-[24px] persona-resize-none persona-border-none persona-bg-transparent persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-none persona-composer-textarea",t.rows=1,t.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',t.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))";let r=3,o=20;t.style.maxHeight=`${r*o}px`,t.style.overflowY="auto";let n=()=>{let c=parseFloat(t.style.maxHeight);return Number.isFinite(c)&&c>0?c:r*o},a=()=>{t.addEventListener("input",()=>{t.style.height="auto";let c=Math.min(t.scrollHeight,n());t.style.height=`${c}px`})};return t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.addEventListener("focus",()=>{t.style.border="none",t.style.outline="none",t.style.borderWidth="0",t.style.borderStyle="none",t.style.borderColor="transparent",t.style.boxShadow="none"}),t.addEventListener("blur",()=>{t.style.border="none",t.style.outline="none"}),{textarea:t,attachAutoResize:a}},ji=e=>{var S,v,M,W,H,I,D,O,J,me,ce,te;let t=(S=e==null?void 0:e.sendButton)!=null?S:{},r=(v=t.useIcon)!=null?v:!1,o=(M=t.iconText)!=null?M:"\u2191",n=t.iconName,a=(W=t.stopIconName)!=null?W:"square",s=(H=t.tooltipText)!=null?H:"Send message",i=(I=t.stopTooltipText)!=null?I:"Stop generating",c=(O=(D=e==null?void 0:e.copy)==null?void 0:D.sendButtonLabel)!=null?O:"Send",l=(me=(J=e==null?void 0:e.copy)==null?void 0:J.stopButtonLabel)!=null?me:"Stop",p=(ce=t.showTooltip)!=null?ce:!1,f=(te=t.size)!=null?te:"40px",u=t.backgroundColor,m=t.textColor,x=w("div","persona-send-button-wrapper"),b=Mt("button",{className:ss("persona-rounded-button disabled:persona-opacity-50 persona-cursor-pointer",r?"persona-flex persona-items-center persona-justify-center":"persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold",r&&!u&&"persona-bg-persona-primary",!r&&!m&&"persona-text-white"),attrs:{type:"submit","data-persona-composer-submit":""},style:{width:r?f:void 0,height:r?f:void 0,minWidth:r?f:void 0,minHeight:r?f:void 0,fontSize:r?"18px":void 0,lineHeight:r?"1":void 0,color:r?m||"var(--persona-button-primary-fg, #ffffff)":m||void 0,backgroundColor:r&&u||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}}),L=null,E=null;if(r){let Se=parseFloat(f)||24,We=(m==null?void 0:m.trim())||"currentColor";n?(L=fe(n,Se,We,2),L?b.appendChild(L):b.textContent=o):b.textContent=o,E=fe(a,Se,We,2)}else b.textContent=c;let A=null;p&&s&&(A=w("div","persona-send-button-tooltip"),A.textContent=s,x.appendChild(A)),b.setAttribute("aria-label",s),x.appendChild(b);let T="send";return{button:b,wrapper:x,setMode:Se=>{if(Se===T)return;T=Se;let We=Se==="stop"?i:s;if(b.setAttribute("aria-label",We),A&&(A.textContent=We),r){if(L&&E){let de=Se==="stop"?E:L;b.replaceChildren(de)}}else b.textContent=Se==="stop"?l:c}}},Gi=e=>{var A,T,y,S,v,M,W,H,I,D,O,J;let t=(A=e==null?void 0:e.voiceRecognition)!=null?A:{};if(!(t.enabled===!0))return null;let o=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),n=((T=t.provider)==null?void 0:T.type)==="runtype";if(!(o||n))return null;let s=(S=(y=e==null?void 0:e.sendButton)==null?void 0:y.size)!=null?S:"40px",i=(v=t.iconName)!=null?v:"mic",c=(M=t.iconSize)!=null?M:s,l=parseFloat(c)||24,p=(H=t.backgroundColor)!=null?H:(W=e==null?void 0:e.sendButton)==null?void 0:W.backgroundColor,f=(D=t.iconColor)!=null?D:(I=e==null?void 0:e.sendButton)==null?void 0:I.textColor,u=w("div","persona-send-button-wrapper"),m=Mt("button",{className:"persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",attrs:{type:"button","data-persona-composer-mic":"","aria-label":"Start voice recognition"},style:{width:c,height:c,minWidth:c,minHeight:c,fontSize:"18px",lineHeight:"1",color:f||"var(--persona-text, #111827)",backgroundColor:p||void 0,borderWidth:t.borderWidth||void 0,borderStyle:t.borderWidth?"solid":void 0,borderColor:t.borderColor||void 0,paddingLeft:t.paddingX||void 0,paddingRight:t.paddingX||void 0,paddingTop:t.paddingY||void 0,paddingBottom:t.paddingY||void 0}}),b=fe(i,l,f||"currentColor",1.5);b?m.appendChild(b):m.textContent="\u{1F3A4}",u.appendChild(m);let L=(O=t.tooltipText)!=null?O:"Start voice recognition";if(((J=t.showTooltip)!=null?J:!1)&&L){let me=w("div","persona-send-button-tooltip");me.textContent=L,u.appendChild(me)}return{button:m,wrapper:u}},Ki=e=>{var x,b,L,E,A,T,y,S;let t=(x=e==null?void 0:e.attachments)!=null?x:{};if(t.enabled!==!0)return null;let r=(L=(b=e==null?void 0:e.sendButton)==null?void 0:b.size)!=null?L:"40px",o=w("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2");o.setAttribute("data-persona-composer-attachment-previews",""),o.style.display="none";let n=w("input");n.type="file",n.setAttribute("data-persona-composer-attachment-input",""),n.accept=((E=t.allowedTypes)!=null?E:en).join(","),n.multiple=((A=t.maxFiles)!=null?A:4)>1,n.style.display="none",n.setAttribute("aria-label","Attach files");let a=(T=t.buttonIconName)!=null?T:"paperclip",s=r,i=parseFloat(s)||40,c=Math.round(i*.6),l=w("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":(y=t.buttonTooltipText)!=null?y:"Attach file"},style:{width:s,height:s,minWidth:s,minHeight:s,fontSize:"18px",lineHeight:"1",backgroundColor:"transparent",color:"var(--persona-primary, #111827)",border:"none",borderRadius:"6px",transition:"background-color 0.15s ease"}});p.addEventListener("mouseenter",()=>{p.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),p.addEventListener("mouseleave",()=>{p.style.backgroundColor="transparent"});let f=fe(a,c,"currentColor",1.5);f?p.appendChild(f):p.textContent="\u{1F4CE}",p.addEventListener("click",v=>{v.preventDefault(),n.click()}),l.appendChild(p);let u=(S=t.buttonTooltipText)!=null?S:"Attach file",m=w("div","persona-send-button-tooltip");return m.textContent=u,l.appendChild(m),{button:p,wrapper:l,input:n,previewsContainer:o}},Xi=e=>{var s,i,c;let t=(s=e==null?void 0:e.statusIndicator)!=null?s:{},r=t.align==="left"?"persona-text-left":t.align==="center"?"persona-text-center":"persona-text-right",o=w("div",`persona-mt-2 ${r} persona-text-xs persona-text-persona-muted`);o.setAttribute("data-persona-composer-status","");let n=(i=t.visible)!=null?i:!0;o.style.display=n?"":"none";let a=(c=t.idleText)!=null?c:"Online";if(t.idleLink){let l=w("a");l.href=t.idleLink,l.target="_blank",l.rel="noopener noreferrer",l.textContent=a,l.style.color="inherit",l.style.textDecoration="none",o.appendChild(l)}else o.textContent=a;return o},Ji=()=>Mt("div",{className:"persona-mb-3 persona-flex persona-flex-wrap persona-gap-2",attrs:{"data-persona-composer-suggestions":""}});var Fa=e=>{var x,b,L,E,A,T;let{config:t}=e,r=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"}}),o=Ji(),n=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:a,attachAutoResize:s}=$i(t);s();let i=ji(t),c=Gi(t),l=Ki(t),p=Xi(t);l&&(l.previewsContainer.style.gap="8px",n.append(l.previewsContainer,l.input)),n.append(a);let f=Mt("div",{className:"persona-widget-composer__actions persona-flex persona-items-center persona-justify-between persona-w-full",attrs:{"data-persona-composer-actions":""}}),u=w("div","persona-widget-composer__left-actions persona-flex persona-items-center persona-gap-2"),m=w("div","persona-widget-composer__right-actions persona-flex persona-items-center persona-gap-1");return l&&u.append(l.wrapper),c&&m.append(c.wrapper),m.append(i.wrapper),f.append(u,m),n.append(f),n.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),r.append(o,n,p),{footer:r,suggestions:o,composerForm:n,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:p,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:f,leftActions:u,rightActions:m,setSendButtonMode:i.setMode}};var Ah=()=>{let e=Mt("button",{className:"persona-pill-peek",attrs:{type:"button","data-persona-pill-peek":"","aria-label":"Show conversation",tabindex:"-1"}}),t=w("span","persona-pill-peek__icon"),r=fe("message-square",16,"currentColor",1.5);r&&t.appendChild(r);let o=w("span","persona-pill-peek__text"),n=w("span","persona-pill-peek__caret"),a=fe("chevron-up",16,"currentColor",1.5);return a&&n.appendChild(a),e.append(t,o,n),{root:e,textNode:o}},Mh=e=>{var x,b,L,E,A,T;let{config:t}=e,r=Mt("div",{className:"persona-widget-footer persona-widget-footer--pill",attrs:{"data-persona-theme-zone":"composer"}}),o=Ji();o.style.display="none";let n=Xi(t);n.style.display="none";let{textarea:a,attachAutoResize:s}=$i(t);a.style.maxHeight="100px",s();let i=ji(t),c=Gi(t),l=Ki(t);l&&l.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"}}),f=w("div","persona-widget-composer__left-actions persona-pill-composer__left");l&&f.append(l.wrapper);let u=w("div","persona-widget-composer__right-actions persona-pill-composer__right");c&&u.append(c.wrapper),u.append(i.wrapper),p.addEventListener("click",y=>{y.target!==i.button&&y.target!==i.wrapper&&y.target!==(c==null?void 0:c.button)&&y.target!==(c==null?void 0:c.wrapper)&&y.target!==(l==null?void 0:l.button)&&y.target!==(l==null?void 0:l.wrapper)&&a.focus()}),l&&p.append(l.input),p.append(f,a,u),l&&r.append(l.previewsContainer),r.append(p,o,n);let m=p;return{footer:r,suggestions:o,composerForm:p,textarea:a,sendButton:i.button,sendButtonWrapper:i.wrapper,micButton:(x=c==null?void 0:c.button)!=null?x:null,micButtonWrapper:(b=c==null?void 0:c.wrapper)!=null?b:null,statusText:n,attachmentButton:(L=l==null?void 0:l.button)!=null?L:null,attachmentButtonWrapper:(E=l==null?void 0:l.wrapper)!=null?E:null,attachmentInput:(A=l==null?void 0:l.input)!=null?A:null,attachmentPreviewsContainer:(T=l==null?void 0:l.previewsContainer)!=null?T:null,actionsRow:m,leftActions:f,rightActions:u,setSendButtonMode:i.setMode}};var Th=e=>{var p,f,u,m,x,b,L,E,A,T,y,S,v,M,W,H,I;let t=(f=(p=e==null?void 0:e.launcher)==null?void 0:p.enabled)!=null?f:!0,r=nr(e);if(Ln(e)){let D=(m=(u=e==null?void 0:e.launcher)==null?void 0:u.composerBar)!=null?m:{},O=w("div","persona-widget-wrapper persona-fixed persona-transition");O.setAttribute("data-persona-composer-bar",""),O.dataset.state="collapsed",O.dataset.expandedSize=(x=D.expandedSize)!=null?x:"anchored",O.style.zIndex=String((L=(b=e==null?void 0:e.launcher)==null?void 0:b.zIndex)!=null?L:Mr);let J=w("div","persona-widget-panel persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");J.style.width="100%",O.appendChild(J);let me=w("div","persona-widget-pill-root");return me.setAttribute("data-persona-composer-bar",""),me.dataset.state="collapsed",me.dataset.expandedSize=(E=D.expandedSize)!=null?E:"anchored",me.style.zIndex=String((T=(A=e==null?void 0:e.launcher)==null?void 0:A.zIndex)!=null?T:Mr),{wrapper:O,panel:J,pillRoot:me}}if(r){let D=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col"),O=w("div","persona-relative persona-h-full persona-w-full persona-flex persona-flex-1 persona-min-h-0 persona-flex-col");return D.appendChild(O),{wrapper:D,panel:O}}if(!t){let D=w("div","persona-relative persona-h-full persona-flex persona-flex-col persona-flex-1 persona-min-h-0"),O=w("div","persona-relative persona-flex-1 persona-flex persona-flex-col persona-min-h-0"),J=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.width)!=null?S:"100%";return D.style.width=J,O.style.width="100%",D.appendChild(O),{wrapper:D,panel:O}}let n=(v=e==null?void 0:e.launcher)!=null?v:{},a=n.position&&Co[n.position]?Co[n.position]:Co["bottom-right"],s=w("div",`persona-widget-wrapper persona-fixed ${a} persona-transition`);s.style.zIndex=String((W=(M=e==null?void 0:e.launcher)==null?void 0:M.zIndex)!=null?W:Mr);let i=w("div","persona-widget-panel persona-relative persona-min-h-[320px]"),c=(I=(H=e==null?void 0:e.launcher)==null?void 0:H.width)!=null?I:e==null?void 0:e.launcherWidth,l=c!=null?c:Yr;return i.style.width=l,i.style.maxWidth=l,s.appendChild(i),{wrapper:s,panel:i}},jb=(e,t)=>{var y,S,v,M,W,H,I,D,O;let r=w("div","persona-widget-container persona-relative persona-flex persona-flex-1 persona-min-h-0 persona-flex-col persona-text-persona-primary");r.setAttribute("data-persona-theme-zone","container");let{button:o,wrapper:n}=Ui(e,{showClose:t,wrapperClassName:"persona-composer-bar-close",buttonSize:"16px",iconSize:"14px"});n.style.position="absolute",n.style.top="8px",n.style.right="8px",n.style.zIndex="10";let a=(v=(S=(y=e==null?void 0:e.launcher)==null?void 0:y.clearChat)==null?void 0:S.enabled)!=null?v:!0,s=null,i=null;if(a){let J=qi(e,{wrapperClassName:"persona-composer-bar-clear-chat",buttonSize:"16px",iconSize:"14px"});s=J.button,i=J.wrapper,i.style.position="absolute",i.style.top="8px",i.style.right="32px",i.style.zIndex="10"}let c=Mt("span",{className:"persona-widget-header",attrs:{"data-persona-theme-zone":"header"},style:{display:"none"}}),l=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"}});l.style.setProperty("scrollbar-gutter","stable");let p=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(W=(M=e==null?void 0:e.copy)==null?void 0:M.welcomeTitle)!=null?W:"Hello \u{1F44B}"}),f=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(I=(H=e==null?void 0:e.copy)==null?void 0:H.welcomeSubtitle)!=null?I:"Ask anything about your account or products."}),u=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,f),m=w("div","persona-flex persona-flex-col persona-gap-3"),x=(D=e==null?void 0:e.layout)==null?void 0:D.contentMaxWidth;x&&(m.style.maxWidth=x,m.style.marginLeft="auto",m.style.marginRight="auto",m.style.width="100%"),((O=e==null?void 0:e.copy)==null?void 0:O.showWelcomeCard)!==!1||(u.style.display="none",l.classList.remove("persona-gap-6"),l.classList.add("persona-gap-3")),l.append(u,m);let L=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=Mh({config:e}),{root:A,textNode:T}=Ah();return r.append(c,n,l,L),i&&r.appendChild(i),{container:r,body:l,messagesWrapper:m,composerOverlay:L,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:f,closeButton:o,closeButtonWrapper:n,clearChatButton:s,clearChatButtonWrapper:i,iconHolder:w("span"),headerTitle:w("span"),headerSubtitle:w("span"),header:c,footer:E.footer,attachmentButton:E.attachmentButton,attachmentButtonWrapper:E.attachmentButtonWrapper,attachmentInput:E.attachmentInput,attachmentPreviewsContainer:E.attachmentPreviewsContainer,actionsRow:E.actionsRow,leftActions:E.leftActions,rightActions:E.rightActions,setSendButtonMode:E.setSendButtonMode,peekBanner:A,peekTextNode:T}},Eh=(e,t=!0)=>{var L,E,A,T,y,S,v,M,W;if(Ln(e))return jb(e,t);let r=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"}}),o=(L=e==null?void 0:e.layout)==null?void 0:L.header,n=((E=e==null?void 0:e.layout)==null?void 0:E.showHeader)!==!1,a=o?Da(e,o,{showClose:t}):rn({config:e,showClose:t}),s=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"}});s.style.setProperty("scrollbar-gutter","stable");let i=Mt("h2",{className:"persona-text-lg persona-font-semibold persona-text-persona-primary",text:(T=(A=e==null?void 0:e.copy)==null?void 0:A.welcomeTitle)!=null?T:"Hello \u{1F44B}"}),c=Mt("p",{className:"persona-mt-2 persona-text-sm persona-text-persona-muted",text:(S=(y=e==null?void 0:e.copy)==null?void 0:y.welcomeSubtitle)!=null?S:"Ask anything about your account or products."}),l=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:nr(e)?"none":"var(--persona-intro-card-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))"}},i,c),p=w("div","persona-flex persona-flex-col persona-gap-3"),f=(v=e==null?void 0:e.layout)==null?void 0:v.contentMaxWidth;f&&(p.style.maxWidth=f,p.style.marginLeft="auto",p.style.marginRight="auto",p.style.width="100%"),((M=e==null?void 0:e.copy)==null?void 0:M.showWelcomeCard)!==!1||(l.style.display="none",s.classList.remove("persona-gap-6"),s.classList.add("persona-gap-3")),s.append(l,p);let m=Fa({config:e}),x=((W=e==null?void 0:e.layout)==null?void 0:W.showFooter)!==!1;n?oa(r,a,e):(a.header.style.display="none",oa(r,a,e)),r.append(s);let b=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 x||(m.footer.style.display="none"),r.append(m.footer),r.append(b),{container:r,body:s,messagesWrapper:p,composerOverlay:b,suggestions:m.suggestions,textarea:m.textarea,sendButton:m.sendButton,sendButtonWrapper:m.sendButtonWrapper,micButton:m.micButton,micButtonWrapper:m.micButtonWrapper,composerForm:m.composerForm,statusText:m.statusText,introTitle:i,introSubtitle:c,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,header:a.header,footer:m.footer,attachmentButton:m.attachmentButton,attachmentButtonWrapper:m.attachmentButtonWrapper,attachmentInput:m.attachmentInput,attachmentPreviewsContainer:m.attachmentPreviewsContainer,actionsRow:m.actionsRow,leftActions:m.leftActions,rightActions:m.rightActions,setSendButtonMode:m.setSendButtonMode}};var ep=(e,t)=>{let r=w("button");r.type="button",r.innerHTML=`
21
21
  <span class="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full persona-bg-persona-primary persona-text-white" data-role="launcher-icon">\u{1F4AC}</span>
22
22
  <img data-role="launcher-image" class="persona-rounded-full persona-object-cover" alt="" style="display:none" />
23
23
  <span class="persona-flex persona-min-w-0 persona-flex-1 persona-flex-col persona-items-start persona-text-left">
@@ -25,7 +25,7 @@ _Details: ${r.message}_`:o}var ys=e=>({isError:!0,content:[{type:"text",text:e}]
25
25
  <span class="persona-block persona-w-full persona-truncate persona-text-xs persona-text-persona-muted" data-role="launcher-subtitle"></span>
26
26
  </span>
27
27
  <span class="persona-ml-2 persona-grid persona-place-items-center persona-rounded-full persona-bg-persona-primary persona-text-persona-call-to-action" data-role="launcher-call-to-action-icon">\u2197</span>
28
- `,r.addEventListener("click",t);let o=a=>{var T,y,S,v,M,W,H,I,D,O,J,me,ce;let s=(T=a.launcher)!=null?T:{},i=nr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let te=(y=s.title)!=null?y:"Chat Assistant";c.textContent=te,c.setAttribute("title",te)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let te=(S=s.subtitle)!=null?S:"Here to help you get answers fast";l.textContent=te,l.setAttribute("title",te)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let te=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=te,f.style.width=te,f.innerHTML="",s.agentIconName){let Se=parseFloat(te)||24,We=fe(s.agentIconName,Se*.6,"var(--persona-text-inverse, #ffffff)",2);We?(f.appendChild(We),f.style.display=""):(f.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let te=(H=s.agentIconSize)!=null?H:"40px";u.style.height=te,u.style.width=te,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let te=(I=s.callToActionIconSize)!=null?I:"32px";m.style.height=te,m.style.width=te,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Se=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Se=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let We=parseFloat(te)||24,de=Math.max(We-Se,8),ve=fe(s.callToActionIconName,de,"currentColor",2);ve?m.appendChild(ve):m.textContent=(D=s.callToActionIconText)!=null?D:"\u2197"}else m.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let x=s.position&&Co[s.position]?Co[s.position]:Co["bottom-right"],b="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?L:`${b} ${x}`,i||(r.style.zIndex=String((J=s.zIndex)!=null?J:Mr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ce=s.collapsedMaxWidth)!=null?ce:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var kh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Th(e),a=Eh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:l,replaceHeader:u=>(c.element.replaceWith(u.header),c.element=u.header,c.iconHolder=u.iconHolder,c.headerTitle=u.headerTitle,c.headerSubtitle=u.headerSubtitle,c.closeButton=u.closeButton,c.closeButtonWrapper=u.closeButtonWrapper,c.clearChatButton=u.clearChatButton,c.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{l.footer.replaceWith(u),l.footer=u}}},tp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>ep(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=ep(e,r);return{instance:n,element:n.element}};var Gb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Kb=(e,t)=>{if(!e)return null;let r=Gb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Xb=(e,t)=>{let r=w("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Jb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},rp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},op=320,Ph=320,Qb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Yb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Zb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ev=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),tv=(e,t,r)=>{if(e.length===0)return null;try{let o=w("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var f;let l=w("img");l.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${c+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${op}px`,l.style.maxHeight=`${Ph}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;n+=1,l.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{p=!0}),Jb(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},rv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!rp(o.audio))return;let n=w("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ov=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!rp(o.video))return;let n=w("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}px`,n.style.maxHeight=`${Ph}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},nv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!rp(o.data))return;let n=w("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},na=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},np=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:na};if(t){let n=t(o);if(n!==null)return n}return na()},av=(e,t)=>{let r=w("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=w("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Lh=(e,t,r="div")=>{let o=w(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},sv=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},ap=(e,t,r)=>{var x,b,L,E,A,T,y;let o=(x=t.showCopy)!=null?x:!0,n=(b=t.showUpvote)!=null?b:!0,a=(L=t.showDownvote)!=null?L:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=w("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",l=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],u=w("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(S,v,M)=>{let W=cr({icon:S,label:v,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&u.appendChild(m("copy","Copy message","copy")),s&&u.appendChild(m("volume-2","Read aloud","read-aloud")),n&&u.appendChild(m("thumbs-up","Upvote","upvote")),a&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},Na=(e,t,r,o,n,a)=>{var se,ie,pe,Ve,_e,G,K,Me,Q,le,Re,rt,vt,Ut,jt,at,Ne;let s=r!=null?r:{},i=(se=s.layout)!=null?se:"bubble",c=s.avatar,l=s.timestamp,p=(ie=c==null?void 0:c.show)!=null?ie:!1,f=(pe=l==null?void 0:l.show)!=null?pe:!1,u=(Ve=c==null?void 0:c.position)!=null?Ve:"left",m=(_e=l==null?void 0:l.position)!=null?_e:"below",x=sv(e.role,i),b=w("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=Qb(e),E=(K=(G=e.content)==null?void 0:G.trim())!=null?K:"",T=L.length>0&&E===fi,y=Ni((Q=(Me=a==null?void 0:a.widgetConfig)==null?void 0:Me.features)==null?void 0:Q.streamAnimation),S=(rt=(Re=(le=a==null?void 0:a.widgetConfig)==null?void 0:le.features)==null?void 0:Re.streamAnimation)==null?void 0:rt.plugins,v=e.role==="assistant"&&y.type!=="none"?Ss(y.type,S):null,M=e.role==="assistant"&&((vt=v==null?void 0:v.isAnimating)==null?void 0:vt.call(v,e))===!0,W=e.role==="assistant"&&v!==null&&(!!e.streaming||M);W&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),e.streaming&&H.classList.add("persona-content-streaming"),W&&v&&(v.containerClass&&H.classList.add(v.containerClass),H.style.setProperty("--persona-stream-step",`${y.speed}ms`),H.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let I=W?Oi((Ut=e.content)!=null?Ut:"",y.buffer,v,e,!!e.streaming):(jt=e.content)!=null?jt:"",D=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=D;W&&(v==null?void 0:v.wrap)==="char"?O=As(D,"char",e.id,{skipTags:v.skipTags}):W&&(v==null?void 0:v.wrap)==="word"&&(O=As(D,"word",e.id,{skipTags:v.skipTags}));let J=null;if(T?(J=document.createElement("div"),J.innerHTML=O,J.style.display="none",H.appendChild(J)):H.innerHTML=O,W&&(v!=null&&v.useCaret)&&!T&&E){let j=_i(),$e=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=$e[$e.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(j,ze.nextSibling);else{let ye=H.lastElementChild;ye?ye.appendChild(j):H.appendChild(j)}}if(f&&m==="inline"&&e.createdAt){let j=Lh(e,l,"span");j.classList.add("persona-timestamp-inline");let $e=H.lastElementChild;$e?$e.appendChild(j):H.appendChild(j)}if(L.length>0){let j=tv(L,!T&&!!E,()=>{T&&J&&(J.style.display="")});j?b.appendChild(j):T&&J&&(J.style.display="")}let me=Yb(e);if(me.length>0){let j=rv(me);j&&b.appendChild(j)}let ce=Zb(e);if(ce.length>0){let j=ov(ce);j&&b.appendChild(j)}let te=ev(e);if(te.length>0){let j=nv(te);j&&b.appendChild(j)}if(b.appendChild(H),f&&m==="below"&&e.createdAt){let j=Lh(e,l);j.classList.add("persona-mt-1"),b.appendChild(j)}let Se=e.role==="assistant"?Kb(e.stopReason,(Ne=(at=a==null?void 0:a.widgetConfig)==null?void 0:at.copy)==null?void 0:Ne.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let j=!!(I&&I.trim()),$e=y.placeholder==="skeleton",ze=$e&&y.buffer==="line"&&j;if(j)ze&&b.appendChild(Ms());else if($e)b.appendChild(Ms());else{let ye=np("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);ye&&b.appendChild(ye)}}if(Se&&e.stopReason&&!e.streaming&&(E||(H.style.display="none"),b.appendChild(Xb(e.stopReason,Se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let j=ap(e,o,n);b.appendChild(j)}if(!p||e.role==="system")return b;let de=w("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=av(c,e.role);return u==="right"||u==="left"&&e.role==="user"?de.append(b,ve):de.append(ve,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),de},Rh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Na(e,t,r,o,n,a)};var Oa=new Set,iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),lv=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
28
+ `,r.addEventListener("click",t);let o=a=>{var T,y,S,v,M,W,H,I,D,O,J,me,ce;let s=(T=a.launcher)!=null?T:{},i=nr(a),c=r.querySelector("[data-role='launcher-title']");if(c){let te=(y=s.title)!=null?y:"Chat Assistant";c.textContent=te,c.setAttribute("title",te)}let l=r.querySelector("[data-role='launcher-subtitle']");if(l){let te=(S=s.subtitle)!=null?S:"Here to help you get answers fast";l.textContent=te,l.setAttribute("title",te)}let p=r.querySelector(".persona-flex-col");p&&(s.textHidden||i?p.style.display="none":p.style.display="");let f=r.querySelector("[data-role='launcher-icon']");if(f)if(s.agentIconHidden)f.style.display="none";else{let te=(v=s.agentIconSize)!=null?v:"40px";if(f.style.height=te,f.style.width=te,s.agentIconBackgroundColor?(f.style.backgroundColor=s.agentIconBackgroundColor,f.classList.remove("persona-bg-persona-primary")):(f.style.backgroundColor="",f.classList.add("persona-bg-persona-primary")),f.innerHTML="",s.agentIconName){let Se=parseFloat(te)||24,We=fe(s.agentIconName,Se*.6,"var(--persona-text-inverse, #ffffff)",2);We?(f.appendChild(We),f.style.display=""):(f.textContent=(M=s.agentIconText)!=null?M:"\u{1F4AC}",f.style.display="")}else s.iconUrl?f.style.display="none":(f.textContent=(W=s.agentIconText)!=null?W:"\u{1F4AC}",f.style.display="")}let u=r.querySelector("[data-role='launcher-image']");if(u){let te=(H=s.agentIconSize)!=null?H:"40px";u.style.height=te,u.style.width=te,s.iconUrl&&!s.agentIconName&&!s.agentIconHidden?(u.src=s.iconUrl,u.style.display="block"):u.style.display="none"}let m=r.querySelector("[data-role='launcher-call-to-action-icon']");if(m){let te=(I=s.callToActionIconSize)!=null?I:"32px";m.style.height=te,m.style.width=te,s.callToActionIconBackgroundColor?(m.style.backgroundColor=s.callToActionIconBackgroundColor,m.classList.remove("persona-bg-persona-primary")):(m.style.backgroundColor="",m.classList.add("persona-bg-persona-primary")),s.callToActionIconColor?(m.style.color=s.callToActionIconColor,m.classList.remove("persona-text-persona-call-to-action")):(m.style.color="",m.classList.add("persona-text-persona-call-to-action"));let Se=0;if(s.callToActionIconPadding?(m.style.boxSizing="border-box",m.style.padding=s.callToActionIconPadding,Se=(parseFloat(s.callToActionIconPadding)||0)*2):(m.style.boxSizing="",m.style.padding=""),s.callToActionIconHidden)m.style.display="none";else if(m.style.display=i?"none":"",m.innerHTML="",s.callToActionIconName){let We=parseFloat(te)||24,de=Math.max(We-Se,8),ve=fe(s.callToActionIconName,de,"currentColor",2);ve?m.appendChild(ve):m.textContent=(D=s.callToActionIconText)!=null?D:"\u2197"}else m.textContent=(O=s.callToActionIconText)!=null?O:"\u2197"}let x=s.position&&Co[s.position]?Co[s.position]:Co["bottom-right"],b="persona-fixed persona-flex persona-items-center persona-gap-3 persona-rounded-launcher persona-bg-persona-surface persona-py-2.5 persona-pl-3 persona-pr-3 persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer",L="persona-relative persona-mt-4 persona-mb-4 persona-mx-auto persona-flex persona-items-center persona-justify-center persona-rounded-launcher persona-bg-persona-surface persona-transition hover:persona-translate-y-[-2px] persona-cursor-pointer";r.className=i?L:`${b} ${x}`,i||(r.style.zIndex=String((J=s.zIndex)!=null?J:Mr));let E="1px solid var(--persona-border, #e5e7eb)",A="var(--persona-launcher-shadow, 0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -4px rgba(0, 0, 0, 0.1))";r.style.border=(me=s.border)!=null?me:E,r.style.boxShadow=s.shadow!==void 0?s.shadow.trim()===""?"none":s.shadow:A,i?(r.style.width="0",r.style.minWidth="0",r.style.maxWidth="0",r.style.padding="0",r.style.overflow="hidden",r.style.border="none",r.style.boxShadow="none"):(r.style.width="",r.style.minWidth="",r.style.maxWidth=(ce=s.collapsedMaxWidth)!=null?ce:"",r.style.justifyContent="",r.style.padding="",r.style.overflow="")},n=()=>{r.removeEventListener("click",t),r.remove()};return e&&o(e),{element:r,update:o,destroy:n}};var kh=({config:e,showClose:t})=>{let{wrapper:r,panel:o,pillRoot:n}=Th(e),a=Eh(e,t),s={wrapper:r,panel:o,pillRoot:n},i={container:a.container,body:a.body,messagesWrapper:a.messagesWrapper,composerOverlay:a.composerOverlay,introTitle:a.introTitle,introSubtitle:a.introSubtitle},c={element:a.header,iconHolder:a.iconHolder,headerTitle:a.headerTitle,headerSubtitle:a.headerSubtitle,closeButton:a.closeButton,closeButtonWrapper:a.closeButtonWrapper,clearChatButton:a.clearChatButton,clearChatButtonWrapper:a.clearChatButtonWrapper},l={footer:a.footer,form:a.composerForm,textarea:a.textarea,sendButton:a.sendButton,sendButtonWrapper:a.sendButtonWrapper,micButton:a.micButton,micButtonWrapper:a.micButtonWrapper,statusText:a.statusText,suggestions:a.suggestions,attachmentButton:a.attachmentButton,attachmentButtonWrapper:a.attachmentButtonWrapper,attachmentInput:a.attachmentInput,attachmentPreviewsContainer:a.attachmentPreviewsContainer,actionsRow:a.actionsRow,leftActions:a.leftActions,rightActions:a.rightActions,setSendButtonMode:a.setSendButtonMode,peekBanner:a.peekBanner,peekTextNode:a.peekTextNode};return{shell:s,panelElements:a,transcript:i,header:c,composer:l,replaceHeader:u=>(c.element.replaceWith(u.header),c.element=u.header,c.iconHolder=u.iconHolder,c.headerTitle=u.headerTitle,c.headerSubtitle=u.headerSubtitle,c.closeButton=u.closeButton,c.closeButtonWrapper=u.closeButtonWrapper,c.clearChatButton=u.clearChatButton,c.clearChatButtonWrapper=u.clearChatButtonWrapper,u),replaceComposer:u=>{l.footer.replaceWith(u),l.footer=u}}},tp=({config:e,plugins:t,onToggle:r})=>{let o=t.find(a=>a.renderLauncher);if(o!=null&&o.renderLauncher){let a=o.renderLauncher({config:e,defaultRenderer:()=>ep(e,r).element,onToggle:r});if(a)return{instance:null,element:a}}let n=ep(e,r);return{instance:n,element:n.element}};var Gb=e=>{switch(e){case"max_tool_calls":return"Stopped after calling a tool. Send a follow-up to continue.";case"length":return"Response cut off as max tokens reached. Ask for more to continue.";case"content_filter":return"The provider filtered this response.";case"error":return"Something went wrong generating this response.";default:return null}},Kb=(e,t)=>{if(!e)return null;let r=Gb(e);if(r===null)return null;let o=t==null?void 0:t[e],n=o!==void 0?o:r;return n||null},Xb=(e,t)=>{let r=w("div","persona-message-stop-reason persona-text-xs persona-mt-2 persona-italic");return r.setAttribute("data-stop-reason",e),r.setAttribute("role","note"),r.style.opacity="0.75",r.textContent=t,r},Jb=e=>{let t=e.toLowerCase();return t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:image/")||!e.includes(":"))},rp=e=>{let t=e.toLowerCase();return t.startsWith("javascript:")||t.startsWith("data:text/html")||t.startsWith("data:text/javascript")||t.startsWith("data:text/xml")||t.startsWith("data:application/xhtml")||t.startsWith("data:image/svg+xml")?!1:!!(/^(?:https?|blob):/i.test(e)||t.startsWith("data:")||!e.includes(":"))},op=320,Ph=320,Qb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="image"&&typeof t.image=="string"&&t.image.trim().length>0),Yb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="audio"&&typeof t.audio=="string"&&t.audio.trim().length>0),Zb=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="video"&&typeof t.video=="string"&&t.video.trim().length>0),ev=e=>!e.contentParts||e.contentParts.length===0?[]:e.contentParts.filter(t=>t.type==="file"&&typeof t.data=="string"&&t.data.trim().length>0),tv=(e,t,r)=>{if(e.length===0)return null;try{let o=w("div","persona-flex persona-flex-col persona-gap-2");o.setAttribute("data-message-attachments","images"),t&&(o.style.marginBottom="8px");let n=0,a=!1,s=()=>{a||(a=!0,o.remove(),r==null||r())};return e.forEach((i,c)=>{var f;let l=w("img");l.alt=((f=i.alt)==null?void 0:f.trim())||`Attached image ${c+1}`,l.loading="lazy",l.decoding="async",l.referrerPolicy="no-referrer",l.style.display="block",l.style.width="100%",l.style.maxWidth=`${op}px`,l.style.maxHeight=`${Ph}px`,l.style.height="auto",l.style.objectFit="contain",l.style.borderRadius="10px",l.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",l.style.border="1px solid var(--persona-attachment-image-border, var(--persona-border, #e5e7eb))";let p=!1;n+=1,l.addEventListener("error",()=>{p||(p=!0,n=Math.max(0,n-1),l.remove(),n===0&&s())}),l.addEventListener("load",()=>{p=!0}),Jb(i.image)?(l.src=i.image,o.appendChild(l)):(p=!0,n=Math.max(0,n-1),l.remove())}),n===0?(s(),null):o}catch{return r==null||r(),null}},rv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","audio");let r=0;return e.forEach(o=>{if(!rp(o.audio))return;let n=w("audio");n.controls=!0,n.preload="metadata",n.src=o.audio,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}px`,t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},ov=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","video");let r=0;return e.forEach(o=>{if(!rp(o.video))return;let n=w("video");n.controls=!0,n.preload="metadata",n.src=o.video,n.style.display="block",n.style.width="100%",n.style.maxWidth=`${op}px`,n.style.maxHeight=`${Ph}px`,n.style.borderRadius="10px",n.style.backgroundColor="var(--persona-attachment-image-bg, var(--persona-container, #f3f4f6))",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},nv=e=>{if(e.length===0)return null;try{let t=w("div","persona-flex persona-flex-col persona-gap-2");t.setAttribute("data-message-attachments","files");let r=0;return e.forEach(o=>{if(!rp(o.data))return;let n=w("a");n.href=o.data,n.download=o.filename,n.target="_blank",n.rel="noopener noreferrer",n.textContent=o.filename,n.className="persona-message-file-attachment",n.style.display="inline-flex",n.style.alignItems="center",n.style.gap="6px",n.style.padding="6px 10px",n.style.borderRadius="8px",n.style.fontSize="0.875rem",n.style.textDecoration="underline",n.style.backgroundColor="var(--persona-attachment-file-bg, var(--persona-container, #f3f4f6))",n.style.border="1px solid var(--persona-attachment-file-border, var(--persona-border, #e5e7eb))",n.style.color="inherit",t.appendChild(n),r+=1}),r===0?(t.remove(),null):t}catch{return null}},na=()=>{let e=document.createElement("div");e.className="persona-flex persona-items-center persona-space-x-1 persona-h-5 persona-mt-2";let t=document.createElement("div");t.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",t.style.backgroundColor="currentColor",t.style.opacity="0.4",t.style.animationDelay="0ms";let r=document.createElement("div");r.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",r.style.backgroundColor="currentColor",r.style.opacity="0.4",r.style.animationDelay="250ms";let o=document.createElement("div");o.className="persona-animate-typing persona-rounded-full persona-h-1.5 persona-w-1.5",o.style.backgroundColor="currentColor",o.style.opacity="0.4",o.style.animationDelay="500ms";let n=document.createElement("span");return n.className="persona-sr-only",n.textContent="Loading",e.appendChild(t),e.appendChild(r),e.appendChild(o),e.appendChild(n),e},np=(e,t,r)=>{let o={config:r!=null?r:{},streaming:!0,location:e,defaultRenderer:na};if(t){let n=t(o);if(n!==null)return n}return na()},av=(e,t)=>{let r=w("div","persona-flex-shrink-0 persona-w-8 persona-h-8 persona-rounded-full persona-flex persona-items-center persona-justify-center persona-text-sm"),o=t==="user"?e.userAvatar:e.assistantAvatar;if(o)if(o.startsWith("http")||o.startsWith("/")||o.startsWith("data:")){let n=w("img");n.src=o,n.alt=t==="user"?"User":"Assistant",n.className="persona-w-full persona-h-full persona-rounded-full persona-object-cover",r.appendChild(n)}else r.textContent=o,r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");else r.textContent=t==="user"?"U":"A",r.classList.add(t==="user"?"persona-bg-persona-accent":"persona-bg-persona-primary","persona-text-white");return r},Lh=(e,t,r="div")=>{let o=w(r,"persona-text-xs persona-text-persona-muted"),n=new Date(e.createdAt);return t.format?o.textContent=t.format(n):o.textContent=n.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"}),o},sv=(e,t="bubble")=>{let r=["persona-message-bubble","persona-max-w-[85%]"];switch(t){case"flat":e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-text-persona-primary","persona-py-2"):r.push("persona-message-assistant-bubble","persona-text-persona-primary","persona-py-2");break;case"minimal":r.push("persona-text-sm","persona-leading-relaxed"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-3","persona-py-2","persona-rounded-lg"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-text-persona-primary","persona-px-3","persona-py-2","persona-rounded-lg");break;default:r.push("persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm"),e==="user"?r.push("persona-message-user-bubble","persona-ml-auto","persona-bg-persona-accent","persona-text-white","persona-px-5","persona-py-3"):r.push("persona-message-assistant-bubble","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3");break}return r},ap=(e,t,r)=>{var x,b,L,E,A,T,y;let o=(x=t.showCopy)!=null?x:!0,n=(b=t.showUpvote)!=null?b:!0,a=(L=t.showDownvote)!=null?L:!0,s=(E=t.showReadAloud)!=null?E:!1;if(!o&&!n&&!a&&!s){let S=w("div");return S.style.display="none",S.id=`actions-${e.id}`,S.setAttribute("data-actions-for",e.id),S}let i=(A=t.visibility)!=null?A:"hover",c=(T=t.align)!=null?T:"right",l=(y=t.layout)!=null?y:"pill-inside",p={left:"persona-message-actions-left",center:"persona-message-actions-center",right:"persona-message-actions-right"}[c],f={"pill-inside":"persona-message-actions-pill","row-inside":"persona-message-actions-row"}[l],u=w("div",`persona-message-actions persona-flex persona-items-center persona-gap-1 persona-mt-2 ${p} ${f} ${i==="hover"?"persona-message-actions-hover":""}`);u.id=`actions-${e.id}`,u.setAttribute("data-actions-for",e.id);let m=(S,v,M)=>{let W=cr({icon:S,label:v,size:14,className:"persona-message-action-btn"});return W.setAttribute("data-action",M),W};return o&&u.appendChild(m("copy","Copy message","copy")),s&&u.appendChild(m("volume-2","Read aloud","read-aloud")),n&&u.appendChild(m("thumbs-up","Upvote","upvote")),a&&u.appendChild(m("thumbs-down","Downvote","downvote")),u},Na=(e,t,r,o,n,a)=>{var se,ie,pe,Ve,_e,G,K,Me,Q,le,Re,rt,vt,Ut,jt,at,Ne;let s=r!=null?r:{},i=(se=s.layout)!=null?se:"bubble",c=s.avatar,l=s.timestamp,p=(ie=c==null?void 0:c.show)!=null?ie:!1,f=(pe=l==null?void 0:l.show)!=null?pe:!1,u=(Ve=c==null?void 0:c.position)!=null?Ve:"left",m=(_e=l==null?void 0:l.position)!=null?_e:"below",x=sv(e.role,i),b=w("div",x.join(" "));b.id=`bubble-${e.id}`,b.setAttribute("data-message-id",e.id),b.setAttribute("data-persona-theme-zone",e.role==="user"?"user-message":"assistant-message"),e.role==="user"?(b.style.backgroundColor="var(--persona-message-user-bg, var(--persona-accent))",b.style.color="var(--persona-message-user-text, white)"):e.role==="assistant"&&(b.style.backgroundColor="var(--persona-message-assistant-bg, var(--persona-surface))",b.style.color="var(--persona-message-assistant-text, var(--persona-text))");let L=Qb(e),E=(K=(G=e.content)==null?void 0:G.trim())!=null?K:"",T=L.length>0&&E===fi,y=Ni((Q=(Me=a==null?void 0:a.widgetConfig)==null?void 0:Me.features)==null?void 0:Q.streamAnimation),S=(rt=(Re=(le=a==null?void 0:a.widgetConfig)==null?void 0:le.features)==null?void 0:Re.streamAnimation)==null?void 0:rt.plugins,v=e.role==="assistant"&&y.type!=="none"?Ss(y.type,S):null,M=e.role==="assistant"&&((vt=v==null?void 0:v.isAnimating)==null?void 0:vt.call(v,e))===!0,W=e.role==="assistant"&&v!==null&&(!!e.streaming||M);W&&(v!=null&&v.bubbleClass)&&b.classList.add(v.bubbleClass);let H=document.createElement("div");H.classList.add("persona-message-content"),e.streaming&&H.classList.add("persona-content-streaming"),W&&v&&(v.containerClass&&H.classList.add(v.containerClass),H.style.setProperty("--persona-stream-step",`${y.speed}ms`),H.style.setProperty("--persona-stream-duration",`${y.duration}ms`));let I=W?Oi((Ut=e.content)!=null?Ut:"",y.buffer,v,e,!!e.streaming):(jt=e.content)!=null?jt:"",D=t({text:I,message:e,streaming:!!e.streaming,raw:e.rawContent}),O=D;W&&(v==null?void 0:v.wrap)==="char"?O=As(D,"char",e.id,{skipTags:v.skipTags}):W&&(v==null?void 0:v.wrap)==="word"&&(O=As(D,"word",e.id,{skipTags:v.skipTags}));let J=null;if(T?(J=document.createElement("div"),J.innerHTML=O,J.style.display="none",H.appendChild(J)):H.innerHTML=O,W&&(v!=null&&v.useCaret)&&!T&&E){let j=_i(),$e=H.querySelectorAll(".persona-stream-char, .persona-stream-word"),ze=$e[$e.length-1];if(ze!=null&&ze.parentNode)ze.parentNode.insertBefore(j,ze.nextSibling);else{let ye=H.lastElementChild;ye?ye.appendChild(j):H.appendChild(j)}}if(f&&m==="inline"&&e.createdAt){let j=Lh(e,l,"span");j.classList.add("persona-timestamp-inline");let $e=H.lastElementChild;$e?$e.appendChild(j):H.appendChild(j)}if(L.length>0){let j=tv(L,!T&&!!E,()=>{T&&J&&(J.style.display="")});j?b.appendChild(j):T&&J&&(J.style.display="")}let me=Yb(e);if(me.length>0){let j=rv(me);j&&b.appendChild(j)}let ce=Zb(e);if(ce.length>0){let j=ov(ce);j&&b.appendChild(j)}let te=ev(e);if(te.length>0){let j=nv(te);j&&b.appendChild(j)}if(b.appendChild(H),f&&m==="below"&&e.createdAt){let j=Lh(e,l);j.classList.add("persona-mt-1"),b.appendChild(j)}let Se=e.role==="assistant"?Kb(e.stopReason,(Ne=(at=a==null?void 0:a.widgetConfig)==null?void 0:at.copy)==null?void 0:Ne.stopReasonNotice):null;if(e.streaming&&e.role==="assistant"){let j=!!(I&&I.trim()),$e=y.placeholder==="skeleton",ze=$e&&y.buffer==="line"&&j;if(j)ze&&b.appendChild(Ms());else if($e)b.appendChild(Ms());else{let ye=np("inline",a==null?void 0:a.loadingIndicatorRenderer,a==null?void 0:a.widgetConfig);ye&&b.appendChild(ye)}}if(Se&&e.stopReason&&!e.streaming&&(E||(H.style.display="none"),b.appendChild(Xb(e.stopReason,Se))),e.role==="assistant"&&!e.streaming&&e.content&&e.content.trim()&&(o==null?void 0:o.enabled)!==!1&&o){let j=ap(e,o,n);b.appendChild(j)}if(!p||e.role==="system")return b;let de=w("div",`persona-flex persona-gap-2 ${e.role==="user"?"persona-flex-row-reverse":""}`),ve=av(c,e.role);return u==="right"||u==="left"&&e.role==="user"?de.append(b,ve):de.append(ve,b),b.classList.remove("persona-max-w-[85%]"),b.classList.add("persona-max-w-[calc(85%-2.5rem)]"),de},Rh=(e,t,r,o,n,a)=>{let s=r!=null?r:{};return e.role==="user"&&s.renderUserMessage?s.renderUserMessage({message:e,config:{},streaming:!!e.streaming}):e.role==="assistant"&&s.renderAssistantMessage?s.renderAssistantMessage({message:e,config:{},streaming:!!e.streaming}):Na(e,t,r,o,n,a)};var Oa=new Set,iv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),lv=(e,t)=>{var o,n;let r=(n=(o=e.reasoning)==null?void 0:o.chunks.join("").trim())!=null?n:"";return r?r.split(/\r?\n/).map(a=>a.trim()).filter(Boolean).slice(0,t).join(`
29
29
  `):""},Ih=(e,t)=>{let r=Oa.has(e),o=t.querySelector('button[data-expand-header="true"]'),n=t.querySelector(".persona-border-t"),a=t.querySelector('[data-persona-collapsed-preview="reasoning"]');if(!o||!n)return;o.setAttribute("aria-expanded",r?"true":"false");let s=o.querySelector(".persona-ml-auto"),i=s==null?void 0:s.querySelector(":scope > .persona-flex.persona-items-center");if(i){i.innerHTML="";let l=fe(r?"chevron-up":"chevron-down",16,"currentColor",2);l?i.appendChild(l):i.textContent=r?"Hide":"Show"}n.style.display=r?"":"none",a&&(a.style.display=r?"none":a.textContent||a.childNodes.length?"":"none")},sp=(e,t)=>{var ce,te,Se,We,de,ve,se,ie,pe,Ve,_e;let r=e.reasoning,o=w("div",["persona-message-bubble","persona-reasoning-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(o.id=`bubble-${e.id}`,o.setAttribute("data-message-id",e.id),!r)return o;let n=(te=(ce=t==null?void 0:t.features)==null?void 0:ce.reasoningDisplay)!=null?te:{},a=n.expandable!==!1,s=a&&Oa.has(e.id),i=r.status!=="complete",c=lv(e,(Se=n.previewMaxLines)!=null?Se:3),l=w("button",a?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");l.type="button",a&&(l.setAttribute("aria-expanded",s?"true":"false"),l.setAttribute("data-expand-header","true")),l.setAttribute("data-bubble-type","reasoning");let p=w("div","persona-flex persona-flex-col persona-text-left"),f=w("span","persona-text-xs persona-text-persona-primary"),u="Thinking...",m=(We=t==null?void 0:t.reasoning)!=null?We:{},x=String((de=r.startedAt)!=null?de:Date.now()),b=()=>{let G=w("span","");return G.setAttribute("data-tool-elapsed",x),G.textContent=si(r),G},L=(ve=m.renderCollapsedSummary)==null?void 0:ve.call(m,{message:e,reasoning:r,defaultSummary:u,previewText:c,isActive:i,config:t!=null?t:{},elapsed:si(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(f.textContent=L,p.appendChild(f)):L instanceof HTMLElement?p.appendChild(L):(f.textContent=u,p.appendChild(f));let E=w("span","persona-text-xs persona-text-persona-primary");E.textContent=Bg(r),p.appendChild(E);let A=(se=n.loadingAnimation)!=null?se:"none",T=m.activeTextTemplate,y=m.completeTextTemplate,S=i?T:y,v=L instanceof HTMLElement,M=(G,K,Me)=>{let Q=Me;for(let le of K){let Re=w("span","persona-tool-char");Re.style.setProperty("--char-index",String(Q)),Re.textContent=le===" "?"\xA0":le,G.appendChild(Re),Q++}return Q},W=(G,K)=>{f.textContent="";let Me=ii(G,""),Q=0;for(let le of Me){let Re=le.styles.length>0?(()=>{let rt=w("span",le.styles.map(vt=>`persona-tool-text-${vt}`).join(" "));return f.appendChild(rt),rt})():f;if(le.isDuration&&i)Re.appendChild(b());else{let rt=le.isDuration?si(r):le.text;K?Q=M(Re,rt,Q):Re.appendChild(document.createTextNode(rt))}}};if(!v&&S)if(E.style.display="none",f.style.display="",i&&A!=="none"){let G=(ie=m.loadingAnimationDuration)!=null?ie:2e3;f.setAttribute("data-preserve-animation","true"),A==="pulse"?(f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),W(S,!1)):(f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor)),W(S,!0))}else W(S,!1);else if(!v&&i&&A!=="none"){f.style.display="";let G=(pe=m.loadingAnimationDuration)!=null?pe:2e3;if(f.setAttribute("data-preserve-animation","true"),A==="pulse")f.classList.add("persona-tool-loading-pulse"),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`);else{f.classList.add(`persona-tool-loading-${A}`),f.style.setProperty("--persona-tool-anim-duration",`${G}ms`),A==="shimmer-color"&&(m.loadingAnimationColor&&f.style.setProperty("--persona-tool-anim-color",m.loadingAnimationColor),m.loadingAnimationSecondaryColor&&f.style.setProperty("--persona-tool-anim-secondary-color",m.loadingAnimationSecondaryColor));let K=f.textContent||u;f.textContent="",M(f,K,0)}r.status==="complete"&&(f.style.display="none")}else v||(r.status==="complete"?f.style.display="none":f.style.display="");let H=null;if(a){H=w("div","persona-flex persona-items-center");let K=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);K?H.appendChild(K):H.textContent=s?"Hide":"Show";let Me=w("div","persona-flex persona-items-center persona-ml-auto");Me.append(H),l.append(p,Me)}else l.append(p);let I=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(I.setAttribute("data-persona-collapsed-preview","reasoning"),I.style.display="none",I.style.whiteSpace="pre-wrap",!s&&i&&n.activePreview&&c){let G=(_e=(Ve=t==null?void 0:t.reasoning)==null?void 0:Ve.renderCollapsedPreview)==null?void 0:_e.call(Ve,{message:e,reasoning:r,defaultPreview:c,isActive:i,config:t!=null?t:{}});iv(I,G)||(I.textContent=c),I.style.display=""}if(!s&&i&&n.activeMinHeight&&(o.style.minHeight=n.activeMinHeight),!a)return o.append(l,I),o;let D=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-px-4 persona-py-3");D.style.display=s?"":"none";let O=r.chunks.join(""),J=w("div","persona-whitespace-pre-wrap persona-text-xs persona-leading-snug persona-text-persona-muted");return J.textContent=O||(r.status==="complete"?"No additional context was shared.":"Waiting for details\u2026"),D.appendChild(J),(()=>{if(l.setAttribute("aria-expanded",s?"true":"false"),H){H.innerHTML="";let K=fe(s?"chevron-up":"chevron-down",16,"currentColor",2);K?H.appendChild(K):H.textContent=s?"Hide":"Show"}D.style.display=s?"":"none",I.style.display=s?"none":I.textContent||I.childNodes.length?"":"none"})(),o.append(l,I,D),o};var _a=new Set,dv=(e,t)=>t==null?!1:typeof t=="string"?(e.textContent=t,!0):(e.appendChild(t),!0),cv=(e,t)=>{var a;let r=e.toolCall;if(!r)return"";let o=((a=r.chunks)!=null?a:[]).join("").trim();if(o)return o.split(/\r?\n/).map(i=>i.trim()).filter(Boolean).slice(-t).join(`
30
30
  `);let n=Sn(r.args).trim();return n?n.split(/\r?\n/).map(s=>s.trim()).filter(Boolean).slice(0,t).join(`
31
31
  `):""},ip=(e,t)=>{var r,o,n;e.style.backgroundColor=(r=t.codeBlockBackgroundColor)!=null?r:"var(--persona-container, #f3f4f6)",e.style.borderColor=(o=t.codeBlockBorderColor)!=null?o:"var(--persona-border, #e5e7eb)",e.style.color=(n=t.codeBlockTextColor)!=null?n:"var(--persona-text, #171717)"},pv=(e,t)=>{var p,f,u,m,x;let r=e.toolCall,o=(p=t==null?void 0:t.features)==null?void 0:p.toolCallDisplay,n=(f=o==null?void 0:o.collapsedMode)!=null?f:"tool-call",a=cv(e,(u=o==null?void 0:o.previewMaxLines)!=null?u:3),s=r?Dg(r):"";if(!r)return{summary:s,previewText:a,isActive:!1};let i=r.status!=="complete",c=(m=t==null?void 0:t.toolCall)!=null?m:{},l=s;return n==="tool-name"?l=((x=r.name)==null?void 0:x.trim())||s:n==="tool-preview"&&a&&(l=a),i&&c.activeTextTemplate?l=Ol(r,c.activeTextTemplate,l):!i&&c.completeTextTemplate&&(l=Ol(r,c.completeTextTemplate,l)),{summary:l,previewText:a,isActive:i}},Wh=(e,t,r)=>{var p;let o=_a.has(e),n=(p=r==null?void 0:r.toolCall)!=null?p:{},a=t.querySelector('button[data-expand-header="true"]'),s=t.querySelector(".persona-border-t"),i=t.querySelector('[data-persona-collapsed-preview="tool"]');if(!a||!s)return;a.setAttribute("aria-expanded",o?"true":"false");let c=a.querySelector(".persona-ml-auto"),l=c==null?void 0:c.querySelector(":scope > .persona-flex.persona-items-center");if(l){l.innerHTML="";let f=n.toggleTextColor||n.headerTextColor||"var(--persona-primary, #171717)",u=fe(o?"chevron-up":"chevron-down",16,f,2);u?l.appendChild(u):l.textContent=o?"Hide":"Show"}s.style.display=o?"":"none",i&&(i.style.display=o?"none":i.textContent||i.childNodes.length?"":"none")},lp=(e,t)=>{var O,J,me,ce,te,Se,We,de,ve;let r=e.toolCall,o=(O=t==null?void 0:t.toolCall)!=null?O:{},n=w("div",["persona-message-bubble","persona-tool-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-shadow-sm","persona-overflow-hidden","persona-px-0","persona-py-0"].join(" "));if(n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),o.backgroundColor&&(n.style.backgroundColor=o.backgroundColor),o.borderColor&&(n.style.borderColor=o.borderColor),o.borderWidth&&(n.style.borderWidth=o.borderWidth),o.borderRadius&&(n.style.borderRadius=o.borderRadius),n.style.boxShadow=o.shadow!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-tool-bubble-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return n;let a=(me=(J=t==null?void 0:t.features)==null?void 0:J.toolCallDisplay)!=null?me:{},s=a.expandable!==!1,i=s&&_a.has(e.id),{summary:c,previewText:l,isActive:p}=pv(e,t),f=w("button",s?"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-pointer persona-border-none":"persona-flex persona-w-full persona-items-center persona-justify-between persona-gap-3 persona-bg-transparent persona-px-4 persona-py-3 persona-text-left persona-cursor-default persona-border-none");f.type="button",s&&(f.setAttribute("aria-expanded",i?"true":"false"),f.setAttribute("data-expand-header","true")),f.setAttribute("data-bubble-type","tool"),o.headerBackgroundColor&&(f.style.backgroundColor=o.headerBackgroundColor),o.headerPaddingX&&(f.style.paddingLeft=o.headerPaddingX,f.style.paddingRight=o.headerPaddingX),o.headerPaddingY&&(f.style.paddingTop=o.headerPaddingY,f.style.paddingBottom=o.headerPaddingY);let u=w("div","persona-flex persona-flex-col persona-text-left"),m=w("span","persona-text-xs persona-text-persona-primary");o.headerTextColor&&(m.style.color=o.headerTextColor);let x=String((ce=r.startedAt)!=null?ce:Date.now()),b=()=>{let se=w("span","");return se.setAttribute("data-tool-elapsed",x),se.textContent=fs(r),se},L=(Se=o.renderCollapsedSummary)==null?void 0:Se.call(o,{message:e,toolCall:r,defaultSummary:c,previewText:l,collapsedMode:(te=a.collapsedMode)!=null?te:"tool-call",isActive:p,config:t!=null?t:{},elapsed:fs(r),createElapsedElement:b});typeof L=="string"&&L.trim()?(m.textContent=L,u.appendChild(m)):L instanceof HTMLElement?u.appendChild(L):(m.textContent=c,u.appendChild(m));let E=(We=a.loadingAnimation)!=null?We:"none",A=o.activeTextTemplate,T=o.completeTextTemplate,y=p?A:T,S=L instanceof HTMLElement,v=(se,ie,pe)=>{let Ve=pe;for(let _e of ie){let G=w("span","persona-tool-char");G.style.setProperty("--char-index",String(Ve)),G.textContent=_e===" "?"\xA0":_e,se.appendChild(G),Ve++}return Ve},M=(se,ie)=>{var G;m.textContent="";let pe=((G=r.name)==null?void 0:G.trim())||"tool",Ve=ii(se,pe),_e=0;for(let K of Ve){let Me=K.styles.length>0?(()=>{let Q=w("span",K.styles.map(le=>`persona-tool-text-${le}`).join(" "));return m.appendChild(Q),Q})():m;if(K.isDuration&&p)Me.appendChild(b());else{let Q=K.isDuration?fs(r):K.text;ie?_e=v(Me,Q,_e):Me.appendChild(document.createTextNode(Q))}}};if(!S)if(p&&E!=="none"){let se=(de=o.loadingAnimationDuration)!=null?de:2e3;if(m.setAttribute("data-preserve-animation","true"),E==="pulse")m.classList.add("persona-tool-loading-pulse"),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),y&&M(y,!1);else if(m.classList.add(`persona-tool-loading-${E}`),m.style.setProperty("--persona-tool-anim-duration",`${se}ms`),E==="shimmer-color"&&(o.loadingAnimationColor&&m.style.setProperty("--persona-tool-anim-color",o.loadingAnimationColor),o.loadingAnimationSecondaryColor&&m.style.setProperty("--persona-tool-anim-secondary-color",o.loadingAnimationSecondaryColor)),y)M(y,!0);else{let ie=m.textContent||c;m.textContent="",v(m,ie,0)}}else y&&M(y,!1);let W=null;if(s){W=w("div","persona-flex persona-items-center");let se=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",ie=fe(i?"chevron-up":"chevron-down",16,se,2);ie?W.appendChild(ie):W.textContent=i?"Hide":"Show";let pe=w("div","persona-flex persona-items-center persona-gap-2 persona-ml-auto");pe.append(W),f.append(u,pe)}else f.append(u);let H=w("div","persona-px-4 persona-py-3 persona-text-xs persona-leading-snug persona-text-persona-muted");if(H.setAttribute("data-persona-collapsed-preview","tool"),H.style.display="none",H.style.whiteSpace="pre-wrap",!i&&p&&a.activePreview&&l){let se=(ve=o.renderCollapsedPreview)==null?void 0:ve.call(o,{message:e,toolCall:r,defaultPreview:l,isActive:p,config:t!=null?t:{}});dv(H,se)||(H.textContent=l),H.style.display=""}if(!i&&p&&a.activeMinHeight&&(n.style.minHeight=a.activeMinHeight),!s)return n.append(f,H),n;let I=w("div","persona-border-t persona-border-gray-200 persona-bg-gray-50 persona-space-y-3 persona-px-4 persona-py-3");if(I.style.display=i?"":"none",o.contentBackgroundColor&&(I.style.backgroundColor=o.contentBackgroundColor),o.contentTextColor&&(I.style.color=o.contentTextColor),o.contentPaddingX&&(I.style.paddingLeft=o.contentPaddingX,I.style.paddingRight=o.contentPaddingX),o.contentPaddingY&&(I.style.paddingTop=o.contentPaddingY,I.style.paddingBottom=o.contentPaddingY),r.name){let se=w("div","persona-text-xs persona-text-persona-muted persona-italic");o.contentTextColor?se.style.color=o.contentTextColor:o.headerTextColor&&(se.style.color=o.headerTextColor),se.textContent=r.name,I.appendChild(se)}if(r.args!==void 0){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Arguments";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=Sn(r.args),se.append(ie,pe),I.appendChild(se)}if(r.chunks&&r.chunks.length){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Activity";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=r.chunks.join(""),se.append(ie,pe),I.appendChild(se)}if(r.status==="complete"&&r.result!==void 0){let se=w("div","persona-space-y-1"),ie=w("div","persona-text-xs persona-text-persona-muted");o.labelTextColor&&(ie.style.color=o.labelTextColor),ie.textContent="Result";let pe=w("pre","persona-max-h-48 persona-overflow-auto persona-whitespace-pre-wrap persona-rounded-lg persona-border persona-px-3 persona-py-2 persona-text-xs");pe.style.fontSize="0.75rem",pe.style.lineHeight="1rem",ip(pe,o),pe.textContent=Sn(r.result),se.append(ie,pe),I.appendChild(se)}if(r.status==="complete"&&typeof r.duration=="number"){let se=w("div","persona-text-xs persona-text-persona-muted");o.contentTextColor&&(se.style.color=o.contentTextColor),se.textContent=`Duration: ${r.duration}ms`,I.appendChild(se)}return(()=>{if(f.setAttribute("aria-expanded",i?"true":"false"),W){W.innerHTML="";let se=o.toggleTextColor||o.headerTextColor||"var(--persona-primary, #171717)",ie=fe(i?"chevron-up":"chevron-down",16,se,2);ie?W.appendChild(ie):W.textContent=i?"Hide":"Show"}I.style.display=i?"":"none",H.style.display=i?"none":H.textContent||H.childNodes.length?"":"none"})(),n.append(f,H,I),n};var aa=new Map,Qi=e=>{let r=(e.startsWith(vo)?e.slice(vo.length):e).replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[_\-\s.]+/).filter(Boolean);if(r.length===0)return e;let o=r.join(" ").toLowerCase();return o.charAt(0).toUpperCase()+o.slice(1)},Hh=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,Bh=(e,t)=>{var o,n,a;let r=(n=(o=Hh(t))==null?void 0:o.detailsDisplay)!=null?n:"collapsed";return(a=aa.get(e))!=null?a:r==="expanded"},Dh=(e,t,r)=>{var s,i;let o=Hh(r);e.setAttribute("aria-expanded",t?"true":"false");let n=e.querySelector("[data-approval-details-label]");n&&(n.textContent=t?(s=o==null?void 0:o.hideDetailsLabel)!=null?s:"Hide details":(i=o==null?void 0:o.showDetailsLabel)!=null?i:"Show details");let a=e.querySelector("[data-approval-details-chevron]");if(a){a.innerHTML="";let c=fe(t?"chevron-up":"chevron-down",14,"currentColor",2);c&&a.appendChild(c)}},Fh=(e,t,r)=>{let o=t.querySelector('button[data-bubble-type="approval"]'),n=t.querySelector("[data-approval-details]");if(!o||!n)return;let a=Bh(e,r);Dh(o,a,r),n.style.display=a?"":"none"};var Yi=(e,t)=>{var M,W,H,I,D,O,J,me,ce,te,Se,We,de,ve,se;let r=e.approval,o=(t==null?void 0:t.approval)!==!1?t==null?void 0:t.approval:void 0,n=(r==null?void 0:r.status)==="pending",a=w("div",["persona-approval-bubble","persona-w-full","persona-max-w-[85%]","persona-rounded-2xl","persona-border","persona-shadow-sm","persona-overflow-hidden"].join(" "));if(a.id=`bubble-${e.id}`,a.setAttribute("data-message-id",e.id),a.style.backgroundColor=(M=o==null?void 0:o.backgroundColor)!=null?M:"var(--persona-approval-bg, #fefce8)",a.style.borderColor=(W=o==null?void 0:o.borderColor)!=null?W:"var(--persona-approval-border, #fef08a)",a.style.boxShadow=(o==null?void 0:o.shadow)!==void 0?o.shadow.trim()===""?"none":o.shadow:"var(--persona-approval-shadow, 0 5px 15px rgba(15, 23, 42, 0.08))",!r)return a;let s=w("div","persona-flex persona-items-start persona-gap-3 persona-px-4 persona-py-3"),i=w("div","persona-flex-shrink-0 persona-mt-0.5");i.setAttribute("data-approval-icon","true");let c=r.status==="denied"?"shield-x":r.status==="timeout"?"shield-alert":"shield-check",l=r.status==="approved"?"var(--persona-feedback-success, #16a34a)":r.status==="denied"?"var(--persona-feedback-error, #dc2626)":r.status==="timeout"?"var(--persona-feedback-warning, #ca8a04)":(H=o==null?void 0:o.titleColor)!=null?H:"currentColor",p=fe(c,20,l,2);p&&i.appendChild(p);let f=w("div","persona-flex-1 persona-min-w-0"),u=w("div","persona-flex persona-items-center persona-gap-2"),m=w("span","persona-text-sm persona-font-medium persona-text-persona-primary");if(o!=null&&o.titleColor&&(m.style.color=o.titleColor),m.textContent=(I=o==null?void 0:o.title)!=null?I:"Approval Required",u.appendChild(m),!n){let ie=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded-full persona-text-xs persona-font-medium");ie.setAttribute("data-approval-status",r.status),r.status==="approved"?(ie.style.backgroundColor="var(--persona-palette-colors-success-100, #dcfce7)",ie.style.color="var(--persona-palette-colors-success-700, #15803d)",ie.textContent="Approved"):r.status==="denied"?(ie.style.backgroundColor="var(--persona-palette-colors-error-100, #fee2e2)",ie.style.color="var(--persona-palette-colors-error-700, #b91c1c)",ie.textContent="Denied"):r.status==="timeout"&&(ie.style.backgroundColor="var(--persona-palette-colors-warning-100, #fef3c7)",ie.style.color="var(--persona-palette-colors-warning-700, #b45309)",ie.textContent="Timeout"),u.appendChild(ie)}f.appendChild(u);let b=r.toolType==="webmcp"||r.toolName.startsWith(vo)?as(r.toolName):void 0,L=(D=o==null?void 0:o.formatDescription)==null?void 0:D.call(o,{toolName:r.toolName,toolType:r.toolType,description:r.description,parameters:r.parameters,...b?{displayTitle:b}:{},...r.reason?{reason:r.reason}:{}}),E=!r.toolName,A=L||(E?r.description:`The assistant wants to use \u201C${b!=null?b:Qi(r.toolName)}\u201D.`),T=w("p","persona-text-sm persona-mt-0.5 persona-text-persona-muted");if(T.setAttribute("data-approval-summary","true"),o!=null&&o.descriptionColor&&(T.style.color=o.descriptionColor),T.textContent=A,f.appendChild(T),r.reason){let ie=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");ie.setAttribute("data-approval-reason","true"),o!=null&&o.reasonColor?ie.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ie.style.color=o.descriptionColor);let pe=w("span","persona-font-medium");pe.textContent=`${(O=o==null?void 0:o.reasonLabel)!=null?O:"Agent's stated reason:"} `,ie.appendChild(pe),ie.appendChild(document.createTextNode(r.reason)),f.appendChild(ie)}let y=(J=o==null?void 0:o.detailsDisplay)!=null?J:"collapsed",S=!!r.description&&!E,v=S||!!r.parameters;if(y!=="hidden"&&v){let ie=Bh(e.id,t),pe=w("button","persona-inline-flex persona-items-center persona-gap-1 persona-mt-1 persona-p-0 persona-border-none persona-bg-transparent persona-text-xs persona-font-medium persona-cursor-pointer persona-text-persona-muted");pe.type="button",pe.setAttribute("data-expand-header","true"),pe.setAttribute("data-bubble-type","approval"),o!=null&&o.descriptionColor&&(pe.style.color=o.descriptionColor);let Ve=w("span");Ve.setAttribute("data-approval-details-label","true");let _e=w("span","persona-inline-flex persona-items-center");_e.setAttribute("data-approval-details-chevron","true"),pe.append(Ve,_e),Dh(pe,ie,t),f.appendChild(pe);let G=w("div");if(G.setAttribute("data-approval-details","true"),G.style.display=ie?"":"none",S){let K=w("p","persona-text-sm persona-mt-1 persona-text-persona-muted");o!=null&&o.descriptionColor&&(K.style.color=o.descriptionColor),K.textContent=r.description,G.appendChild(K)}if(r.parameters){let K=w("pre","persona-mt-2 persona-text-xs persona-p-2 persona-rounded persona-overflow-x-auto persona-max-h-32 persona-bg-persona-container persona-text-persona-primary");o!=null&&o.parameterBackgroundColor&&(K.style.backgroundColor=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(K.style.color=o.parameterTextColor),K.style.fontSize="0.75rem",K.style.lineHeight="1rem",K.textContent=Sn(r.parameters),G.appendChild(K)}f.appendChild(G)}if(n){let ie=w("div","persona-flex persona-gap-2 persona-mt-2");ie.setAttribute("data-approval-buttons","true");let pe=w("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-border-none persona-cursor-pointer");pe.type="button",pe.style.backgroundColor=(me=o==null?void 0:o.approveButtonColor)!=null?me:"var(--persona-approval-approve-bg, #22c55e)",pe.style.color=(ce=o==null?void 0:o.approveButtonTextColor)!=null?ce:"#ffffff",pe.setAttribute("data-approval-action","approve");let Ve=fe("shield-check",14,(te=o==null?void 0:o.approveButtonTextColor)!=null?te:"#ffffff",2);Ve&&(Ve.style.marginRight="4px",pe.appendChild(Ve));let _e=document.createTextNode((Se=o==null?void 0:o.approveLabel)!=null?Se:"Approve");pe.appendChild(_e);let G=w("button","persona-inline-flex persona-items-center persona-px-3 persona-py-1.5 persona-rounded-md persona-text-xs persona-font-medium persona-cursor-pointer");G.type="button",G.style.backgroundColor=(We=o==null?void 0:o.denyButtonColor)!=null?We:"transparent",G.style.color=(de=o==null?void 0:o.denyButtonTextColor)!=null?de:"var(--persona-feedback-error, #dc2626)",G.style.border=`1px solid ${o!=null&&o.denyButtonTextColor?o.denyButtonTextColor:"var(--persona-palette-colors-error-200, #fca5a5)"}`,G.setAttribute("data-approval-action","deny");let K=fe("shield-x",14,(ve=o==null?void 0:o.denyButtonTextColor)!=null?ve:"var(--persona-feedback-error, #dc2626)",2);K&&(K.style.marginRight="4px",G.appendChild(K));let Me=document.createTextNode((se=o==null?void 0:o.denyLabel)!=null?se:"Deny");G.appendChild(Me),ie.append(pe,G),f.appendChild(ie)}return s.append(i,f),a.appendChild(s),a};function uv(e){var r,o;let t=(r=e.getRootNode)==null?void 0:r.call(e);return t instanceof ShadowRoot?t:((o=e.ownerDocument)!=null?o:document).body}function Nh(e){var b;let{anchor:t,content:r,placement:o="bottom-start",offset:n=6,matchAnchorWidth:a=!1,zIndex:s=2147483e3,onOpen:i,onDismiss:c}=e,l=(b=e.container)!=null?b:uv(t),p=!1,f=null,u=()=>{if(!p)return;let L=t.getBoundingClientRect();r.style.position="fixed",a&&(r.style.minWidth=`${L.width}px`);let E=o==="top-start"||o==="top-end"?L.top-n-r.getBoundingClientRect().height:L.bottom+n,A=o==="bottom-end"||o==="top-end"?L.right-r.getBoundingClientRect().width:L.left;r.style.top=`${E}px`,r.style.left=`${A}px`},m=()=>{p&&(p=!1,f&&(f(),f=null),r.remove())},x=()=>{var S,v,M;if(p)return;p=!0,s!=null&&(r.style.zIndex=String(s)),l.appendChild(r),u();let L=(v=((S=t.ownerDocument)!=null?S:document).defaultView)!=null?v:window,E=(M=t.ownerDocument)!=null?M:document,A=()=>{if(!t.isConnected){m(),c==null||c("anchor-removed");return}u()},T=W=>{let H=typeof W.composedPath=="function"?W.composedPath():[];H.includes(r)||H.includes(t)||(m(),c==null||c("outside"))},y=L.setTimeout(()=>{E.addEventListener("pointerdown",T,!0)},0);L.addEventListener("scroll",A,!0),L.addEventListener("resize",A),f=()=>{L.clearTimeout(y),E.removeEventListener("pointerdown",T,!0),L.removeEventListener("scroll",A,!0),L.removeEventListener("resize",A)},i==null||i()};return{get isOpen(){return p},open:x,close:m,toggle:()=>p?m():x(),reposition:u,destroy:m}}function Oh(e){return(typeof e.composedPath=="function"?e.composedPath():[]).some(r=>r instanceof HTMLElement&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable))}var fv=()=>({keyHandlers:new Map,popovers:new Map,pendingOrder:[],latestPendingApprovalId:null}),_h=(e,t)=>{let r=e.keyHandlers.get(t);r&&(document.removeEventListener("keydown",r),e.keyHandlers.delete(t));let o=e.popovers.get(t);o&&(o.destroy(),e.popovers.delete(t))},sa=(e,t)=>{_h(e,t);let r=e.pendingOrder.indexOf(t);r!==-1&&e.pendingOrder.splice(r,1),e.latestPendingApprovalId===t&&(e.latestPendingApprovalId=e.pendingOrder.length?e.pendingOrder[e.pendingOrder.length-1]:null)},mv=e=>(e==null?void 0:e.approval)!==!1?e==null?void 0:e.approval:void 0,gv=(e,t)=>{var o,n;let r=(o=t==null?void 0:t.detailsDisplay)!=null?o:"collapsed";return(n=aa.get(e))!=null?n:r==="expanded"},dp=e=>{let t=w("span","persona-approval-kbd");return t.textContent=e,t},hv=(e,t)=>{var l,p;let r=w("span","persona-approval-title");t!=null&&t.titleColor&&(r.style.color=t.titleColor);let n=e.toolType==="webmcp"||e.toolName.startsWith(vo)?as(e.toolName):void 0,a=(p=t==null?void 0:t.formatDescription)==null?void 0:p.call(t,{toolName:e.toolName,toolType:e.toolType,description:(l=e.description)!=null?l:"",parameters:e.parameters,...n?{displayTitle:n}:{},...e.reason?{reason:e.reason}:{}});if(a)return r.textContent=a,r;let s=n!=null?n:Qi(e.toolName),i=e.toolType&&e.toolType!=="webmcp"?e.toolType:null;r.append("The assistant wants to use ");let c=document.createElement("strong");if(c.textContent=s,r.appendChild(c),i){r.append(" from ");let f=document.createElement("strong");f.textContent=i,r.appendChild(f)}return r},xv=e=>{let t=w("div","persona-approval-resolved"),r=fe("ban",15,"currentColor",2);r&&t.appendChild(r);let o=w("span","persona-approval-resolved-name");return o.textContent=e.toolName?Qi(e.toolName):"Tool",t.append(o,document.createTextNode(e.status==="timeout"?" timed out":" denied")),t},yv=(e,t,r,o,n,a,s)=>{var W,H,I,D,O,J,me;let i=w("div","persona-approval-card persona-shadow-sm");i.id=`bubble-${t.id}`,i.setAttribute("data-message-id",t.id),i.setAttribute("data-bubble-type","approval"),o!=null&&o.backgroundColor&&(i.style.background=o.backgroundColor),o!=null&&o.borderColor&&(i.style.borderColor=o.borderColor),(o==null?void 0:o.shadow)!==void 0&&(i.style.boxShadow=o.shadow.trim()===""?"none":o.shadow);let c=(W=o==null?void 0:o.detailsDisplay)!=null?W:"collapsed",l=!!r.description&&c!=="hidden",p=r.parameters!=null&&c!=="hidden",f=l||p,u=f&&gv(t.id,o),m=(H=o==null?void 0:o.showDetailsLabel)!=null?H:"Show details",x=(I=o==null?void 0:o.hideDetailsLabel)!=null?I:"Hide details",b=w("button","persona-approval-head");b.type="button",f?(b.setAttribute("data-action","toggle-params"),b.setAttribute("aria-expanded",u?"true":"false"),b.setAttribute("aria-label",u?x:m)):b.setAttribute("data-static","true");let L=w("span","persona-approval-logo"),E=fe("shield-check",16,"currentColor",2);E&&L.appendChild(E),b.appendChild(L);let A=hv(r,o);if(f){let ce=w("span","persona-approval-toggle");ce.setAttribute("aria-hidden","true");let te=fe("chevron-down",14,"currentColor",2);te&&ce.appendChild(te),A.append(" "),A.appendChild(ce)}b.appendChild(A),i.appendChild(b);let T=w("div","persona-approval-body");if(f){let ce=w("div","persona-approval-details");if(ce.setAttribute("data-role","params"),ce.hidden=!u,l){let te=w("p","persona-approval-desc");o!=null&&o.descriptionColor&&(te.style.color=o.descriptionColor),te.textContent=r.description,ce.appendChild(te)}if(p){let te=w("pre","persona-approval-params");o!=null&&o.parameterBackgroundColor&&(te.style.background=o.parameterBackgroundColor),o!=null&&o.parameterTextColor&&(te.style.color=o.parameterTextColor),te.textContent=Sn(r.parameters),ce.appendChild(te)}T.appendChild(ce)}if(r.reason){let ce=w("p","persona-approval-reason");o!=null&&o.reasonColor?ce.style.color=o.reasonColor:o!=null&&o.descriptionColor&&(ce.style.color=o.descriptionColor);let te=w("span","persona-approval-reason-label");te.textContent=`${(D=o==null?void 0:o.reasonLabel)!=null?D:"Agent's stated reason:"} `,ce.append(te,document.createTextNode(r.reason)),T.appendChild(ce)}let y=w("div","persona-approval-actions"),S=null,v=ce=>{o!=null&&o.approveButtonColor&&(ce.style.background=o.approveButtonColor),o!=null&&o.approveButtonTextColor&&(ce.style.color=o.approveButtonTextColor)},M=w("button","persona-approval-deny");if(M.type="button",M.setAttribute("data-action","deny"),o!=null&&o.denyButtonColor&&(M.style.background=o.denyButtonColor),o!=null&&o.denyButtonTextColor&&(M.style.color=o.denyButtonTextColor),M.append((O=o==null?void 0:o.denyLabel)!=null?O:"Deny"),s){let ce=w("div","persona-approval-split"),te=w("button","persona-approval-primary");te.type="button",te.setAttribute("data-action","always"),v(te),te.append((J=o==null?void 0:o.approveLabel)!=null?J:"Always allow",dp("\u23CE"));let Se=w("button","persona-approval-caret");Se.type="button",Se.setAttribute("data-action","toggle-menu"),Se.setAttribute("aria-label","More options"),v(Se);let We=fe("chevron-down",15,"currentColor",2);We&&Se.appendChild(We),ce.append(te,Se),y.append(ce,M),M.append(dp("Esc"));let de=w("div","persona-approval-menu"),ve=w("button","persona-approval-menu-item");ve.type="button",ve.append("Allow once",dp("\u2318\u23CE")),de.appendChild(ve),S=Nh({anchor:ce,content:de,placement:"bottom-start",matchAnchorWidth:!0}),e.popovers.set(t.id,S),ve.addEventListener("click",()=>{sa(e,t.id),n()})}else{let ce=w("button","persona-approval-primary persona-approval-primary--solo");ce.type="button",ce.setAttribute("data-action","allow"),v(ce),ce.append((me=o==null?void 0:o.approveLabel)!=null?me:"Allow"),y.append(ce,M)}return T.appendChild(y),i.appendChild(T),i.addEventListener("click",ce=>{let te=ce.target instanceof Element?ce.target.closest("[data-action]"):null;if(!te)return;let Se=te.getAttribute("data-action");if(Se==="toggle-params"){let We=i.querySelector('[data-role="params"]');if(We){let de=We.hidden;We.hidden=!de,b.setAttribute("aria-expanded",de?"true":"false"),b.setAttribute("aria-label",de?x:m),aa.set(t.id,de)}return}if(Se==="toggle-menu"){S==null||S.toggle();return}if(Se==="always"){sa(e,t.id),n({remember:!0});return}if(Se==="allow"){sa(e,t.id),n();return}if(Se==="deny"){sa(e,t.id),a();return}}),i},Uh=()=>{let e=fv();return{plugin:{id:"persona-built-in-approval",renderApproval:({message:o,approve:n,deny:a,config:s})=>{let i=o==null?void 0:o.approval;if(!i)return null;let c=mv(s);if(i.status!=="pending"){if(sa(e,o.id),i.status==="approved"){let f=document.createElement("div");return f.style.display="none",f}return xv(i)}_h(e,o.id);let l=(c==null?void 0:c.enableAlwaysAllow)===!0,p=yv(e,o,i,c,n,a,l);if(l){e.pendingOrder.includes(o.id)||e.pendingOrder.push(o.id),e.latestPendingApprovalId=e.pendingOrder[e.pendingOrder.length-1];let f=u=>{Oh(u)||o.id===e.latestPendingApprovalId&&(u.key!=="Escape"&&u.key!=="Enter"||(u.preventDefault(),u.stopImmediatePropagation(),sa(e,o.id),u.key==="Escape"?a():u.metaKey||u.ctrlKey?n():n({remember:!0})))};e.keyHandlers.set(o.id,f),document.addEventListener("keydown",f)}return p}},teardown:()=>{for(let o of[...e.keyHandlers.keys(),...e.popovers.keys()])sa(e,o);e.latestPendingApprovalId=null}}};var qh=e=>{let t=[],r=null;return{buttons:t,render:(n,a,s,i,c,l)=>{e.innerHTML="",t.length=0;let p=(l==null?void 0:l.agentPushed)===!0;if(p||(r=null),!n||!n.length||!p&&(i!=null?i:a?a.getMessages():[]).some(L=>L.role==="user"))return;let f=document.createDocumentFragment(),u=a?a.isStreaming():!1,m=x=>{switch(x){case"serif":return'Georgia, "Times New Roman", Times, serif';case"mono":return'"Courier New", Courier, "Lucida Console", Monaco, monospace';default:return'-apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif'}};if(n.forEach(x=>{let b=w("button","persona-rounded-button persona-bg-persona-surface persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium persona-text-persona-primary hover:persona-opacity-80 persona-cursor-pointer persona-border persona-border-persona-border");b.type="button",b.textContent=x,b.disabled=u,c!=null&&c.fontFamily&&(b.style.fontFamily=m(c.fontFamily)),c!=null&&c.fontWeight&&(b.style.fontWeight=c.fontWeight),c!=null&&c.paddingX&&(b.style.paddingLeft=c.paddingX,b.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(b.style.paddingTop=c.paddingY,b.style.paddingBottom=c.paddingY),b.addEventListener("click",()=>{!a||a.isStreaming()||(s.value="",p&&e.dispatchEvent(new CustomEvent("persona:suggestReplies:selected",{detail:{suggestion:x},bubbles:!0,composed:!0})),a.sendMessage(x))}),f.appendChild(b),t.push(b)}),e.appendChild(f),p){let x=JSON.stringify(n);x!==r&&(r=x,e.dispatchEvent(new CustomEvent("persona:suggestReplies:shown",{detail:{suggestions:[...n]},bubbles:!0,composed:!0})))}}}};var Ls=class{constructor(t=2e3,r=null){this.head=0;this.count=0;this.totalCaptured=0;this.eventTypesSet=new Set;this.maxSize=t,this.buffer=new Array(t),this.store=r}push(t){var r;this.buffer[this.head]=t,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.totalCaptured++,this.eventTypesSet.add(t.type),(r=this.store)==null||r.put(t)}getAll(){return this.count===0?[]:this.count<this.maxSize?this.buffer.slice(0,this.count):[...this.buffer.slice(this.head,this.maxSize),...this.buffer.slice(0,this.head)]}async restore(){if(!this.store)return 0;let t=await this.store.getAll();if(t.length===0)return 0;let r=t.length>this.maxSize?t.slice(t.length-this.maxSize):t;for(let o of r)this.buffer[this.head]=o,this.head=(this.head+1)%this.maxSize,this.count<this.maxSize&&this.count++,this.eventTypesSet.add(o.type);return this.totalCaptured=t.length,r.length}getAllFromStore(){return this.store?this.store.getAll():Promise.resolve(this.getAll())}getRecent(t){let r=this.getAll();return t>=r.length?r:r.slice(r.length-t)}getSize(){return this.count}getTotalCaptured(){return this.totalCaptured}getEvictedCount(){return this.totalCaptured-this.count}clear(){var t;this.buffer=new Array(this.maxSize),this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.clear()}destroy(){var t;this.buffer=[],this.head=0,this.count=0,this.totalCaptured=0,this.eventTypesSet.clear(),(t=this.store)==null||t.destroy()}getEventTypes(){return Array.from(this.eventTypesSet)}};var Ps=class{constructor(t="persona-event-stream",r="events"){this.db=null;this.pendingWrites=[];this.flushScheduled=!1;this.isDestroyed=!1;this.dbName=t,this.storeName=r}open(){return new Promise((t,r)=>{try{let o=indexedDB.open(this.dbName,1);o.onupgradeneeded=()=>{let n=o.result;n.objectStoreNames.contains(this.storeName)||n.createObjectStore(this.storeName,{keyPath:"id"}).createIndex("timestamp","timestamp",{unique:!1})},o.onsuccess=()=>{this.db=o.result,t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}put(t){!this.db||this.isDestroyed||(this.pendingWrites.push(t),this.flushScheduled||(this.flushScheduled=!0,queueMicrotask(()=>this.flushWrites())))}putBatch(t){if(!(!this.db||this.isDestroyed||t.length===0))try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}getAll(){return new Promise((t,r)=>{if(!this.db){t([]);return}try{let s=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).index("timestamp").getAll();s.onsuccess=()=>{t(s.result)},s.onerror=()=>{r(s.error)}}catch(o){r(o)}})}getCount(){return new Promise((t,r)=>{if(!this.db){t(0);return}try{let a=this.db.transaction(this.storeName,"readonly").objectStore(this.storeName).count();a.onsuccess=()=>{t(a.result)},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}clear(){return new Promise((t,r)=>{if(!this.db){t();return}this.pendingWrites=[];try{let a=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName).clear();a.onsuccess=()=>{t()},a.onerror=()=>{r(a.error)}}catch(o){r(o)}})}close(){this.db&&(this.db.close(),this.db=null)}destroy(){return this.isDestroyed=!0,this.pendingWrites=[],this.close(),new Promise((t,r)=>{try{let o=indexedDB.deleteDatabase(this.dbName);o.onsuccess=()=>{t()},o.onerror=()=>{r(o.error)}}catch(o){r(o)}})}flushWrites(){if(this.flushScheduled=!1,!this.db||this.isDestroyed||this.pendingWrites.length===0)return;let t=this.pendingWrites;this.pendingWrites=[];try{let o=this.db.transaction(this.storeName,"readwrite").objectStore(this.storeName);for(let n of t)o.put(n)}catch{}}};var bv=new Set(["flow_start","flow_run_start","agent_start","dispatch_start","run_start"]),vv=new Set(["step_start","execution_start"]),wv=new Set(["step_delta","step_chunk","chunk","agent_turn_delta"]),Cv=new Set(["step_complete","agent_turn_complete"]),Sv=new Set(["flow_complete","agent_complete"]),Vh=new Set(["step_error","flow_error","agent_error","dispatch_error","error"]),$h=e=>typeof e=="object"&&e!==null&&!Array.isArray(e),eo=e=>typeof e=="number"&&Number.isFinite(e)?e:void 0,ia=(e,t)=>{let r=e[t];return $h(r)?r:void 0};function cp(e){return e>0?Math.max(1,Math.ceil(e/4)):0}function Zi(e,t){if(!(e<=0||t===void 0||t<250))return e/(t/1e3)}function Av(e,t){return typeof t.type=="string"?t.type:e}function Mv(e){return typeof e.text=="string"?e.text:typeof e.delta=="string"?e.delta:typeof e.content=="string"?e.content:typeof e.chunk=="string"?e.chunk:""}function Tv(e,t){return e==="step_delta"||e==="step_chunk"?t.stepType!=="tool"&&t.executionType!=="context":e!=="agent_turn_delta"?!0:(typeof t.contentType=="string"?t.contentType:typeof t.content_type=="string"?t.content_type:void 0)==="text"}function zh(e){var o,n,a,s,i;let t=ia(e,"result"),r=[ia(e,"tokens"),ia(e,"totalTokens"),t?ia(t,"tokens"):void 0,ia(e,"usage"),t?ia(t,"usage"):void 0];for(let c of r){if(!c)continue;let l=(n=(o=eo(c.output))!=null?o:eo(c.outputTokens))!=null?n:eo(c.completionTokens);if(l!==void 0)return l}return(i=(a=eo(e.outputTokens))!=null?a:eo(e.completionTokens))!=null?i:t?(s=eo(t.outputTokens))!=null?s:eo(t.completionTokens):void 0}function Ev(e){var r,o,n,a,s;let t=ia(e,"result");return(s=(n=(o=(r=eo(e.executionTime))!=null?r:eo(e.executionTimeMs))!=null?o:eo(e.execution_time))!=null?n:eo(e.duration))!=null?s:t?(a=eo(t.executionTime))!=null?a:eo(t.executionTimeMs):void 0}function kv(){return typeof performance!="undefined"&&typeof performance.now=="function"?performance.now():Date.now()}var Rs=class{constructor(t=kv){this.metric={status:"idle"};this.run=null;this.now=t}getMetric(){let t=this.run;if(t&&this.metric.status==="running"&&t.firstDeltaAt!==void 0&&this.metric.outputTokens!==void 0){let r=this.now()-t.firstDeltaAt;return{...this.metric,durationMs:r,tokensPerSecond:Zi(this.metric.outputTokens,r)}}return this.metric}reset(){this.run=null,this.metric={status:"idle"}}startRun(t){this.run={startedAt:t,visibleCharCount:0,exactOutputTokens:0},this.metric={status:"running"}}processEvent(t,r){var a;if(!$h(r)){Vh.has(t)&&this.run&&(this.run=null,this.metric={status:"error"});return}let o=Av(t,r),n=this.now();if(bv.has(o)){this.startRun(n);return}if(vv.has(o)){this.run||this.startRun(n);return}if(wv.has(o)){if(!Tv(o,r))return;let s=Mv(r);if(!s)return;this.run||this.startRun(n);let i=this.run;(a=i.firstDeltaAt)!=null||(i.firstDeltaAt=n),i.visibleCharCount+=s.length;let c=i.exactOutputTokens+cp(i.visibleCharCount),l=n-i.firstDeltaAt;this.metric={status:"running",tokensPerSecond:Zi(c,l),outputTokens:c,durationMs:l,source:i.exactOutputTokens>0?"usage":"estimate"};return}if(Cv.has(o)){if(!this.run)return;let s=this.run,i=zh(r);i!==void 0&&(s.exactOutputTokens+=i,s.visibleCharCount=0);let c=s.exactOutputTokens>0,l=s.exactOutputTokens+cp(s.visibleCharCount),p=this.resolveDuration(s,r,n);this.metric={status:"running",tokensPerSecond:Zi(l,p),outputTokens:l,durationMs:p,source:c?"usage":"estimate"};return}if(Sv.has(o)){if(!this.run)return;let s=this.run,i=zh(r),c=i!=null?i:s.exactOutputTokens+cp(s.visibleCharCount),l=i!==void 0||s.exactOutputTokens>0?"usage":"estimate",p=this.resolveDuration(s,r,n);this.metric={status:"complete",tokensPerSecond:Zi(c,p),outputTokens:c,durationMs:p,source:l},this.run=null;return}if(Vh.has(o)){if(!this.run)return;this.run=null,this.metric={status:"error"}}}resolveDuration(t,r,o){let n=t.firstDeltaAt!==void 0?o-t.firstDeltaAt:void 0;if(n!==void 0&&n>=250)return n;let a=Ev(r);return a!=null?a:o-t.startedAt}};function Ua(e,t){t&&t.split(/\s+/).forEach(r=>r&&e.classList.add(r))}var Lv={flow_:{bg:"var(--persona-palette-colors-success-100, #dcfce7)",text:"var(--persona-palette-colors-success-700, #166534)"},step_:{bg:"var(--persona-palette-colors-primary-100, #f5f5f5)",text:"var(--persona-palette-colors-primary-700, #0a0a0a)"},reason_:{bg:"var(--persona-palette-colors-warning-100, #ffedd5)",text:"var(--persona-palette-colors-warning-700, #9a3412)"},tool_:{bg:"var(--persona-palette-colors-purple-100, #f3e8ff)",text:"var(--persona-palette-colors-purple-700, #6b21a8)"},agent_:{bg:"var(--persona-palette-colors-teal-100, #ccfbf1)",text:"var(--persona-palette-colors-teal-700, #115e59)"},error:{bg:"var(--persona-palette-colors-error-100, #fecaca)",text:"var(--persona-palette-colors-error-700, #991b1b)"}},Pv={bg:"var(--persona-palette-colors-gray-100, #f3f4f6)",text:"var(--persona-palette-colors-gray-600, #4b5563)"},Rv=["flowName","stepName","reasoningText","text","name","tool","toolName"],Iv=100;function Wv(e,t){let r={...Lv,...t};if(r[e])return r[e];for(let o of Object.keys(r))if(o.endsWith("_")&&e.startsWith(o))return r[o];return Pv}function Hv(e,t){return`+${((e-t)/1e3).toFixed(3)}s`}function Bv(e){let t=new Date(e),r=String(t.getHours()).padStart(2,"0"),o=String(t.getMinutes()).padStart(2,"0"),n=String(t.getSeconds()).padStart(2,"0"),a=String(t.getMilliseconds()).padStart(3,"0");return`${r}:${o}:${n}.${a}`}function Dv(e,t){try{let r=JSON.parse(e);if(typeof r!="object"||r===null)return null;for(let o of t){let n=o.split("."),a=r;for(let s of n)if(a&&typeof a=="object"&&a!==null)a=a[s];else{a=void 0;break}if(typeof a=="string"&&a.trim())return a.trim()}}catch{}return null}function Fv(e){var t;return(t=navigator.clipboard)!=null&&t.writeText?navigator.clipboard.writeText(e):new Promise(r=>{let o=document.createElement("textarea");o.value=e,o.style.position="fixed",o.style.opacity="0",document.body.appendChild(o),o.select(),document.execCommand("copy"),document.body.removeChild(o),r()})}function Nv(e){let t;try{t=JSON.parse(e.payload)}catch{t=e.payload}return JSON.stringify({type:e.type,timestamp:new Date(e.timestamp).toISOString(),payload:t},null,2)}function Ov(e){return e.tokensPerSecond===void 0||!Number.isFinite(e.tokensPerSecond)?"-- tok/s":`${e.tokensPerSecond.toFixed(1)} tok/s`}function _v(e){let t=[];return e.outputTokens!==void 0&&t.push(`${e.outputTokens.toLocaleString()} tok`),e.durationMs!==void 0&&t.push(`${(e.durationMs/1e3).toFixed(2)}s`),e.source&&t.push(e.source),t.join(" \xB7 ")}function Uv(e,t,r){let o,n;try{n=JSON.parse(e.payload),o=JSON.stringify(n,null,2)}catch{n=e.payload,o=e.payload}let a=t.find(i=>i.renderEventStreamPayload);if(a!=null&&a.renderEventStreamPayload&&r){let i=a.renderEventStreamPayload({event:e,config:r,defaultRenderer:()=>s(),parsedPayload:n});if(i)return i}return s();function s(){let i=w("div","persona-bg-persona-container persona-border-t persona-border-persona-divider persona-px-3 persona-py-2 persona-ml-4 persona-mr-3 persona-mb-1 persona-rounded-b persona-overflow-auto persona-max-h-[300px]"),c=w("pre","persona-m-0 persona-whitespace-pre-wrap persona-break-all persona-text-[11px] persona-text-persona-secondary persona-font-mono");return c.textContent=o,i.appendChild(c),i}}function pp(e,t,r,o,n,a,s,i){var u;let c=n.has(e.id),l=w("div","persona-border-b persona-border-persona-divider persona-text-xs");Ua(l,(u=o.classNames)==null?void 0:u.eventRow);let p=s.find(m=>m.renderEventStreamRow);if(p!=null&&p.renderEventStreamRow&&i){let m=p.renderEventStreamRow({event:e,index:t,config:i,defaultRenderer:()=>f(),isExpanded:c,onToggleExpand:()=>a(e.id)});if(m)return l.appendChild(m),l}return l.appendChild(f()),l;function f(){var O,J;let m=w("div",""),x=w("div","persona-flex persona-items-center persona-gap-2 persona-px-3 persona-py-3 hover:persona-bg-persona-container persona-cursor-pointer persona-group");x.setAttribute("data-event-id",e.id);let b=w("span","persona-flex-shrink-0 persona-text-persona-muted persona-w-4 persona-text-center persona-flex persona-items-center persona-justify-center"),L=fe(c?"chevron-down":"chevron-right","14px","currentColor",2);L&&b.appendChild(L);let E=w("span","persona-text-[11px] persona-text-persona-muted persona-whitespace-nowrap persona-flex-shrink-0 persona-font-mono persona-w-[70px]"),A=(O=o.timestampFormat)!=null?O:"relative";E.textContent=A==="relative"?Hv(e.timestamp,r):Bv(e.timestamp);let T=null;o.showSequenceNumbers!==!1&&(T=w("span","persona-text-[11px] persona-text-persona-muted persona-font-mono persona-flex-shrink-0 persona-w-[28px] persona-text-right"),T.textContent=String(t+1));let y=Wv(e.type,o.badgeColors),S=w("span","persona-inline-flex persona-items-center persona-px-2 persona-py-0.5 persona-rounded persona-text-[11px] persona-font-mono persona-font-medium persona-whitespace-nowrap persona-flex-shrink-0 persona-border");S.style.backgroundColor=y.bg,S.style.color=y.text,S.style.borderColor=y.text+"50",S.textContent=e.type;let v=(J=o.descriptionFields)!=null?J:Rv,M=Dv(e.payload,v),W=null;M&&(W=w("span","persona-text-[11px] persona-text-persona-secondary persona-truncate persona-min-w-0"),W.textContent=M);let H=w("div","persona-flex-1 persona-min-w-0"),I=w("button","persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-flex-shrink-0 persona-border-none persona-bg-transparent persona-p-0"),D=fe("clipboard","12px","currentColor",1.5);return D&&I.appendChild(D),I.addEventListener("click",async me=>{me.stopPropagation(),await Fv(Nv(e)),I.innerHTML="";let ce=fe("check","12px","currentColor",1.5);ce&&I.appendChild(ce),setTimeout(()=>{I.innerHTML="";let te=fe("clipboard","12px","currentColor",1.5);te&&I.appendChild(te)},1500)}),x.appendChild(b),x.appendChild(E),T&&x.appendChild(T),x.appendChild(S),W&&x.appendChild(W),x.appendChild(H),x.appendChild(I),m.appendChild(x),c&&m.appendChild(Uv(e,s,i)),m}}function jh(e){var x,b,L,E,A;let{buffer:t,getFullHistory:r,onClose:o,config:n,plugins:a=[],getThroughput:s}=e,i=(x=n==null?void 0:n.features)==null?void 0:x.scrollToBottom,c=(i==null?void 0:i.enabled)!==!1,l=(b=i==null?void 0:i.iconName)!=null?b:"arrow-down",p=(L=i==null?void 0:i.label)!=null?L:"",f=(A=(E=n==null?void 0:n.features)==null?void 0:E.eventStream)!=null?A:{},u=a.find(T=>T.renderEventStreamView);if(u!=null&&u.renderEventStreamView&&n){let T=u.renderEventStreamView({config:n,events:t.getAll(),defaultRenderer:()=>m().element,onClose:o});if(T)return{element:T,update:()=>{},destroy:()=>{}}}return m();function m(){let T=f.classNames,y=w("div","persona-event-stream-view persona-flex persona-flex-col persona-flex-1 persona-min-h-0");Ua(y,T==null?void 0:T.panel);let S=[],v="",M="",W=null,H=[],I={},D=0,O=Bi(),J=0,me=0,ce=!1,te=null,Se=!1,We=0,de=new Set,ve=new Map,se="",ie="",pe=null,Ve,_e,G,K,Me,Q=null,le=null,Re=null;function rt(){let F=w("div","persona-relative persona-flex persona-flex-col persona-flex-shrink-0"),Y=w("div","persona-flex persona-items-center persona-gap-2 persona-px-4 persona-py-3 persona-pb-0 persona-border-persona-divider persona-bg-persona-surface persona-overflow-hidden");Ua(Y,T==null?void 0:T.headerBar);let Ce=w("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");if(Ce.textContent="Events",Ve=w("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border"),Ve.textContent="0",s){le=w("div","persona-relative persona-flex persona-items-center persona-gap-1.5 persona-whitespace-nowrap persona-ml-1"),le.style.cursor="help";let Ot=w("span","persona-text-sm persona-font-medium persona-text-persona-primary persona-whitespace-nowrap");Ot.textContent="Throughput",Q=w("span","persona-text-[11px] persona-font-mono persona-bg-persona-container persona-text-persona-muted persona-px-2 persona-py-0.5 persona-rounded persona-border persona-border-persona-border persona-tabular-nums"),Q.textContent="-- tok/s",Re=w("div","persona-absolute persona-z-50 persona-whitespace-nowrap persona-rounded persona-border persona-border-persona-border persona-bg-persona-container persona-text-persona-primary persona-text-[11px] persona-font-mono persona-px-2 persona-py-1 persona-shadow"),Re.style.display="none",Re.style.pointerEvents="none";let _r=le,Tr=Re,Er=()=>{if(!Tr.textContent)return;let kr=_r.getBoundingClientRect(),uo=F.getBoundingClientRect();Tr.style.left=`${kr.left-uo.left}px`,Tr.style.top=`${kr.bottom-uo.top+4}px`,Tr.style.display="block"},wr=()=>{Tr.style.display="none"};le.addEventListener("mouseenter",Er),le.addEventListener("mouseleave",wr),le.appendChild(Ot),le.appendChild(Q)}let it=w("div","persona-flex-1");_e=w("select","persona-text-xs persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded persona-px-2.5 persona-py-1 persona-text-persona-primary persona-cursor-pointer");let Je=w("option","");Je.value="",Je.textContent="All events",_e.appendChild(Je),G=w("button","persona-inline-flex persona-items-center persona-gap-1.5 persona-rounded persona-text-xs persona-text-persona-muted hover:persona-bg-persona-container hover:persona-text-persona-primary persona-cursor-pointer persona-border persona-border-persona-border persona-bg-persona-surface persona-flex-shrink-0 persona-px-2.5 persona-py-1"),G.type="button",G.title="Copy All";let yr=fe("clipboard-copy","12px","currentColor",1.5);yr&&G.appendChild(yr);let yt=w("span","persona-text-xs");yt.textContent="Copy All",G.appendChild(yt),Y.appendChild(Ce),Y.appendChild(Ve),le&&Y.appendChild(le),Y.appendChild(it),Y.appendChild(_e),Y.appendChild(G);let bt=w("div","persona-relative persona-px-4 persona-py-2.5 persona-border-b persona-border-persona-divider persona-bg-persona-surface");Ua(bt,T==null?void 0:T.searchBar);let Pt=fe("search","14px","var(--persona-muted, #9ca3af)",1.5),wt=w("span","persona-absolute persona-left-6 persona-top-1/2 persona--translate-y-1/2 persona-pointer-events-none persona-flex persona-items-center");Pt&&wt.appendChild(Pt),K=w("input","persona-text-sm persona-bg-persona-surface persona-border persona-border-persona-border persona-rounded-md persona-pl-8 persona-pr-3 persona-py-1 persona-w-full persona-text-persona-primary"),Ua(K,T==null?void 0:T.searchInput),K.type="text",K.placeholder="Search event payloads...",Me=w("button","persona-absolute persona-right-5 persona-top-1/2 persona--translate-y-1/2 persona-text-persona-muted hover:persona-text-persona-primary persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-0 persona-leading-none"),Me.type="button",Me.style.display="none";let pr=fe("x","12px","currentColor",2);return pr&&Me.appendChild(pr),bt.appendChild(wt),bt.appendChild(K),bt.appendChild(Me),F.appendChild(Y),F.appendChild(bt),Re&&F.appendChild(Re),F}let vt,Ut=a.find(F=>F.renderEventStreamToolbar);if(Ut!=null&&Ut.renderEventStreamToolbar&&n){let F=Ut.renderEventStreamToolbar({config:n,defaultRenderer:()=>rt(),eventCount:t.getSize(),filteredCount:0,onFilterChange:Y=>{v=Y,Oe(),Qt()},onSearchChange:Y=>{M=Y,Oe(),Qt()}});vt=F!=null?F:rt()}else vt=rt();let jt=w("div","persona-text-xs persona-text-persona-muted persona-text-center persona-py-0.5 persona-px-4 persona-bg-persona-container persona-border-b persona-border-persona-divider persona-italic persona-flex-shrink-0");jt.style.display="none";function at(){if(!s||!Q||!le)return;let F=s();Q.textContent=Ov(F);let Y=_v(F);Re&&(Re.textContent=Y,Y||(Re.style.display="none")),Y?le.setAttribute("aria-label",Y):le.removeAttribute("aria-label")}let Ne=w("div","persona-flex-1 persona-min-h-0 persona-relative"),j=w("div","persona-event-stream-list persona-overflow-y-auto persona-min-h-0");j.style.height="100%";let $e=w("div","persona-scroll-to-bottom-indicator persona-absolute persona-bottom-3 persona-left-1/2 persona-transform persona--translate-x-1/2 persona-cursor-pointer persona-z-10 persona-text-xs");Ua($e,T==null?void 0:T.scrollIndicator),$e.style.display="none",$e.setAttribute("data-persona-scroll-to-bottom-has-label",p?"true":"false");let ze=fe(l,"14px","currentColor",2);ze&&$e.appendChild(ze);let ye=w("span","");ye.textContent=p,$e.appendChild(ye);let we=w("div","persona-flex persona-items-center persona-justify-center persona-h-full persona-text-sm persona-text-persona-muted");we.style.display="none",Ne.appendChild(j),Ne.appendChild(we),Ne.appendChild($e),y.setAttribute("tabindex","0"),y.appendChild(vt),y.appendChild(jt),y.appendChild(Ne);function Ze(){let F=t.getAll(),Y={};for(let yt of F)Y[yt.type]=(Y[yt.type]||0)+1;let Ce=Object.keys(Y).sort(),it=Ce.length!==H.length||!Ce.every((yt,bt)=>yt===H[bt]),Je=!it&&Ce.some(yt=>Y[yt]!==I[yt]),qt=F.length!==Object.values(I).reduce((yt,bt)=>yt+bt,0);if(!it&&!Je&&!qt||(H=Ce,I=Y,!_e))return;let yr=_e.value;if(_e.options[0].textContent="All events",it){for(;_e.options.length>1;)_e.remove(1);for(let yt of Ce){let bt=w("option","");bt.value=yt,bt.textContent=`${yt} (${Y[yt]||0})`,_e.appendChild(bt)}yr&&Ce.includes(yr)?_e.value=yr:yr&&(_e.value="",v="")}else for(let yt=1;yt<_e.options.length;yt++){let bt=_e.options[yt];bt.textContent=`${bt.value} (${Y[bt.value]||0})`}}function Nt(){let F=t.getAll();if(v&&(F=F.filter(Y=>Y.type===v)),M){let Y=M.toLowerCase();F=F.filter(Ce=>Ce.type.toLowerCase().includes(Y)||Ce.payload.toLowerCase().includes(Y))}return F}function re(){return v!==""||M!==""}function Oe(){D=0,J=0,O.resume(),$e.style.display="none"}function xr(F){de.has(F)?de.delete(F):de.add(F),pe=F;let Y=j.scrollTop,Ce=O.isFollowing();Se=!0,O.pause(),Qt(),j.scrollTop=Y,Ce&&O.resume(),Se=!1}function Ht(){return ta(j,50)}function Qt(){me=Date.now(),ce=!1,at(),Ze();let F=t.getEvictedCount();F>0?(jt.textContent=`${F.toLocaleString()} older events truncated`,jt.style.display=""):jt.style.display="none",S=Nt();let Y=S.length,Ce=t.getSize()>0;Ve&&(Ve.textContent=String(t.getSize())),Y===0&&Ce&&re()?(we.textContent=M?`No events matching '${M}'`:"No events matching filter",we.style.display="",j.style.display="none"):(we.style.display="none",j.style.display=""),G&&(G.title=re()?`Copy Filtered (${Y})`:"Copy All"),c&&!O.isFollowing()&&Y>D&&(J+=Y-D,ye.textContent=p?`${p}${J>0?` (${J})`:""}`:"",$e.style.display=""),D=Y;let it=t.getAll(),Je=it.length>0?it[0].timestamp:0,qt=new Set(S.map(bt=>bt.id));for(let bt of de)qt.has(bt)||de.delete(bt);let yr=v!==se||M!==ie,yt=ve.size===0&&S.length>0;if(yr||yt||S.length===0){j.innerHTML="",ve.clear();let bt=document.createDocumentFragment();for(let Pt=0;Pt<S.length;Pt++){let wt=pp(S[Pt],Pt,Je,f,de,xr,a,n);ve.set(S[Pt].id,wt),bt.appendChild(wt)}j.appendChild(bt),se=v,ie=M,pe=null}else{if(pe!==null){let Pt=ve.get(pe);if(Pt&&Pt.parentNode===j){let wt=S.findIndex(pr=>pr.id===pe);if(wt>=0){let pr=pp(S[wt],wt,Je,f,de,xr,a,n);j.insertBefore(pr,Pt),Pt.remove(),ve.set(pe,pr)}}pe=null}let bt=new Set(S.map(Pt=>Pt.id));for(let[Pt,wt]of ve)bt.has(Pt)||(wt.remove(),ve.delete(Pt));for(let Pt=0;Pt<S.length;Pt++){let wt=S[Pt];if(!ve.has(wt.id)){let pr=pp(wt,Pt,Je,f,de,xr,a,n);ve.set(wt.id,pr),j.appendChild(pr)}}}O.isFollowing()&&(j.scrollTop=j.scrollHeight)}function _o(){if(Date.now()-me>=Iv){te!==null&&(cancelAnimationFrame(te),te=null),Qt();return}ce||(ce=!0,te=requestAnimationFrame(()=>{te=null,Qt()}))}let So=(F,Y)=>{if(!G)return;G.innerHTML="";let Ce=fe(F,"12px","currentColor",1.5);Ce&&G.appendChild(Ce);let it=w("span","persona-text-xs");it.textContent="Copy All",G.appendChild(it),setTimeout(()=>{G.innerHTML="";let Je=fe("clipboard-copy","12px","currentColor",1.5);Je&&G.appendChild(Je);let qt=w("span","persona-text-xs");qt.textContent="Copy All",G.appendChild(qt),G.disabled=!1},Y)},P=async()=>{if(G){G.disabled=!0;try{let F;re()?F=S:r?(F=await r(),F.length===0&&(F=t.getAll())):F=t.getAll();let Y=F.map(Ce=>{try{return JSON.parse(Ce.payload)}catch{return Ce.payload}});await navigator.clipboard.writeText(JSON.stringify(Y,null,2)),So("check",1500)}catch{So("x",1500)}}},ee=()=>{_e&&(v=_e.value,Oe(),Qt())},Ae=()=>{!K||!Me||(Me.style.display=K.value?"":"none",W&&clearTimeout(W),W=setTimeout(()=>{M=K.value,Oe(),Qt()},150))},Ie=()=>{!K||!Me||(K.value="",M="",Me.style.display="none",W&&clearTimeout(W),Oe(),Qt())},Ee=()=>{if(Se)return;let F=j.scrollTop,{action:Y,nextLastScrollTop:Ce}=Di({following:O.isFollowing(),currentScrollTop:F,lastScrollTop:We,nearBottom:Ht(),userScrollThreshold:1,resumeRequiresDownwardScroll:!0});We=Ce,Y==="resume"?(O.resume(),J=0,$e.style.display="none"):Y==="pause"&&(O.pause(),c&&(ye.textContent=p,$e.style.display=""))},He=F=>{let Y=Fi({following:O.isFollowing(),deltaY:F.deltaY,nearBottom:Ht(),resumeWhenNearBottom:!0});Y==="pause"?(O.pause(),c&&(ye.textContent=p,$e.style.display="")):Y==="resume"&&(O.resume(),J=0,$e.style.display="none")},Ge=()=>{c&&(j.scrollTop=j.scrollHeight,O.resume(),J=0,$e.style.display="none")},st=F=>{let Y=F.target;if(!Y||Y.closest("button"))return;let Ce=Y.closest("[data-event-id]");if(!Ce)return;let it=Ce.getAttribute("data-event-id");it&&xr(it)},Lt=F=>{if((F.metaKey||F.ctrlKey)&&F.key==="f"){F.preventDefault(),K==null||K.focus(),K==null||K.select();return}F.key==="Escape"&&(K&&document.activeElement===K?(Ie(),K.blur(),y.focus()):o&&o())};G&&G.addEventListener("click",P),_e&&_e.addEventListener("change",ee),K&&K.addEventListener("input",Ae),Me&&Me.addEventListener("click",Ie),j.addEventListener("scroll",Ee),j.addEventListener("wheel",He,{passive:!0}),j.addEventListener("click",st),$e.addEventListener("click",Ge),y.addEventListener("keydown",Lt);function xt(){W&&clearTimeout(W),te!==null&&(cancelAnimationFrame(te),te=null),ce=!1,ve.clear(),G&&G.removeEventListener("click",P),_e&&_e.removeEventListener("change",ee),K&&K.removeEventListener("input",Ae),Me&&Me.removeEventListener("click",Ie),j.removeEventListener("scroll",Ee),j.removeEventListener("wheel",He),j.removeEventListener("click",st),$e.removeEventListener("click",Ge),y.removeEventListener("keydown",Lt)}return{element:y,update:_o,destroy:xt}}}function Gh(e,t){let r=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",o=typeof e.artifactId=="string"?e.artifactId:"",n=e.status==="streaming"?"streaming":"complete",s=(typeof e.artifactType=="string"?e.artifactType:"markdown")==="component"?"Component":"Document",i=document.createElement("div");i.className="persona-flex persona-w-full persona-max-w-full persona-items-center persona-gap-3 persona-rounded-xl persona-px-4 persona-py-3",i.style.border="1px solid var(--persona-border, #e5e7eb)",i.style.backgroundColor="var(--persona-surface, #ffffff)",i.style.cursor="pointer",i.tabIndex=0,i.setAttribute("role","button"),i.setAttribute("aria-label",`Open ${r} in artifact panel`),o&&i.setAttribute("data-open-artifact",o);let c=document.createElement("div");c.className="persona-flex persona-h-10 persona-w-10 persona-flex-shrink-0 persona-items-center persona-justify-center persona-rounded-lg",c.style.border="1px solid var(--persona-border, #e5e7eb)",c.style.color="var(--persona-muted, #9ca3af)",c.innerHTML='<svg xmlns="http://www.w3.org/2000/svg" width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M14.5 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7.5L14.5 2z"/><polyline points="14 2 14 8 20 8"/></svg>';let l=document.createElement("div");l.className="persona-min-w-0 persona-flex-1 persona-flex persona-flex-col persona-gap-0.5";let p=document.createElement("div");p.className="persona-truncate persona-text-sm persona-font-medium",p.style.color="var(--persona-text, #1f2937)",p.textContent=r;let f=document.createElement("div");if(f.className="persona-text-xs persona-flex persona-items-center persona-gap-1.5",f.style.color="var(--persona-muted, #9ca3af)",n==="streaming"){let u=document.createElement("span");u.className="persona-inline-block persona-w-1.5 persona-h-1.5 persona-rounded-full",u.style.backgroundColor="var(--persona-primary, #171717)",u.style.animation="persona-pulse 1.5s ease-in-out infinite",f.appendChild(u);let m=document.createElement("span");m.textContent=`Generating ${s.toLowerCase()}...`,f.appendChild(m)}else f.textContent=s;if(l.append(p,f),i.append(c,l),n==="complete"){let u=document.createElement("button");u.type="button",u.textContent="Download",u.title=`Download ${r}`,u.className="persona-flex-shrink-0 persona-rounded-md persona-px-3 persona-py-1.5 persona-text-xs persona-font-medium",u.style.border="1px solid var(--persona-border, #e5e7eb)",u.style.color="var(--persona-text, #1f2937)",u.style.backgroundColor="transparent",u.style.cursor="pointer",u.setAttribute("data-download-artifact",o),i.append(u)}return i}var Kh=(e,t)=>{var o,n,a;let r=(a=(n=(o=t==null?void 0:t.config)==null?void 0:o.features)==null?void 0:n.artifacts)==null?void 0:a.renderCard;if(r){let s=typeof e.title=="string"&&e.title?e.title:"Untitled artifact",i=typeof e.artifactId=="string"?e.artifactId:"",c=e.status==="streaming"?"streaming":"complete",l=typeof e.artifactType=="string"?e.artifactType:"markdown",p=r({artifact:{artifactId:i,title:s,artifactType:l,status:c},config:t.config,defaultRenderer:()=>Gh(e,t)});if(p)return p}return Gh(e,t)};var up=class{constructor(){this.components=new Map}register(t,r){this.components.has(t)&&console.warn(`[ComponentRegistry] Component "${t}" is already registered. Overwriting.`),this.components.set(t,r)}unregister(t){this.components.delete(t)}get(t){return this.components.get(t)}has(t){return this.components.has(t)}getAllNames(){return Array.from(this.components.keys())}clear(){this.components.clear()}registerAll(t){Object.entries(t).forEach(([r,o])=>{this.register(r,o)})}},on=new up;on.register("PersonaArtifactCard",Kh);function qv(e){var n;let t=w("div","persona-rounded-lg persona-border persona-border-persona-border persona-p-3 persona-text-persona-primary"),r=w("div","persona-font-semibold persona-text-sm persona-mb-2");r.textContent=e.component?`Component: ${e.component}`:"Component";let o=w("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-overflow-x-auto");return o.textContent=JSON.stringify((n=e.props)!=null?n:{},null,2),t.appendChild(r),t.appendChild(o),t}function Xh(e,t){var _e,G,K,Me;let r=(G=(_e=e.features)==null?void 0:_e.artifacts)==null?void 0:G.layout,n=((K=r==null?void 0:r.toolbarPreset)!=null?K:"default")==="document",a=(Me=r==null?void 0:r.panePadding)==null?void 0:Me.trim(),s=e.markdown?Gn(e.markdown):null,i=Ma(e.sanitize),c=Q=>{let le=s?s(Q):Fo(Q);return i?i(le):le},l=typeof document!="undefined"?w("div","persona-artifact-backdrop persona-fixed persona-inset-0 persona-z-[55] persona-bg-black/30 persona-hidden md:persona-hidden"):null,p=()=>{l==null||l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"),D==null||D.hide()};l&&l.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let f=w("aside","persona-artifact-pane persona-flex persona-flex-col persona-min-h-0 persona-min-w-0 persona-bg-persona-surface persona-text-persona-primary persona-border-l persona-border-persona-border");f.setAttribute("data-persona-theme-zone","artifact-pane"),n&&f.classList.add("persona-artifact-pane-document");let u=w("div","persona-artifact-toolbar persona-flex persona-items-center persona-justify-between persona-gap-2 persona-px-2 persona-py-2 persona-border-b persona-border-persona-border persona-shrink-0");u.setAttribute("data-persona-theme-zone","artifact-toolbar"),n&&u.classList.add("persona-artifact-toolbar-document");let m=w("span","persona-text-xs persona-font-medium persona-truncate");m.textContent="Artifacts";let x=w("button","persona-rounded-md persona-border persona-border-persona-border persona-px-2 persona-py-1 persona-text-xs persona-bg-persona-surface");x.type="button",x.textContent="Close",x.setAttribute("aria-label","Close artifacts panel"),x.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let b="rendered",L=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0 persona-artifact-toggle-group"),E=n?cr({icon:"eye",label:"Rendered view",className:"persona-artifact-doc-icon-btn persona-artifact-view-btn"}):cr({icon:"eye",label:"Rendered view"}),A=n?cr({icon:"code-2",label:"Source",className:"persona-artifact-doc-icon-btn persona-artifact-code-btn"}):cr({icon:"code-2",label:"Source"}),T=w("div","persona-flex persona-items-center persona-gap-1 persona-shrink-0"),y=(r==null?void 0:r.documentToolbarShowCopyLabel)===!0,S=(r==null?void 0:r.documentToolbarShowCopyChevron)===!0,v=r==null?void 0:r.documentToolbarCopyMenuItems,M=!!(S&&v&&v.length>0),W=null,H,I=null,D=null;if(n&&(y||S)&&!M){if(H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),S){let Q=fe("chevron-down",14,"currentColor",2);Q&&H.appendChild(Q)}}else n&&M?(W=w("div","persona-relative persona-inline-flex persona-items-center persona-gap-0 persona-rounded-md"),H=y?ks({icon:"copy",label:"Copy",iconSize:14,className:"persona-artifact-doc-copy-btn"}):cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-copy-btn"}),I=cr({icon:"chevron-down",label:"More copy options",size:14,className:"persona-artifact-doc-copy-menu-chevron persona-artifact-doc-icon-btn",aria:{"aria-haspopup":"true","aria-expanded":"false"}}),W.append(H,I)):n?H=cr({icon:"copy",label:"Copy",className:"persona-artifact-doc-icon-btn"}):H=cr({icon:"copy",label:"Copy"});let O=n?cr({icon:"refresh-cw",label:"Refresh",className:"persona-artifact-doc-icon-btn"}):cr({icon:"refresh-cw",label:"Refresh"}),J=n?cr({icon:"x",label:"Close",className:"persona-artifact-doc-icon-btn"}):cr({icon:"x",label:"Close"}),me=()=>{var vt,Ut,jt;let Q=(vt=ve.find(at=>at.id===se))!=null?vt:ve[ve.length-1],le=(Ut=Q==null?void 0:Q.id)!=null?Ut:null,Re=(Q==null?void 0:Q.artifactType)==="markdown"&&(jt=Q.markdown)!=null?jt:"",rt=Q?JSON.stringify({component:Q.component,props:Q.props},null,2):"";return{markdown:Re,jsonPayload:rt,id:le}},ce=async()=>{var vt;let{markdown:Q,jsonPayload:le}=me(),Re=(vt=ve.find(Ut=>Ut.id===se))!=null?vt:ve[ve.length-1],rt=(Re==null?void 0:Re.artifactType)==="markdown"?Q:Re?le:"";try{await navigator.clipboard.writeText(rt)}catch{}};if(H.addEventListener("click",async()=>{let Q=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;if(Q&&M){let{markdown:le,jsonPayload:Re,id:rt}=me();try{await Q({actionId:"primary",artifactId:rt,markdown:le,jsonPayload:Re})}catch{}return}await ce()}),I&&(v!=null&&v.length)){let Q=()=>{var Re;return(Re=f.closest("[data-persona-root]"))!=null?Re:document.body},le=()=>{D=Pn({items:v.map(Re=>({id:Re.id,label:Re.label})),onSelect:async Re=>{let{markdown:rt,jsonPayload:vt,id:Ut}=me(),jt=r==null?void 0:r.onDocumentToolbarCopyMenuSelect;try{jt?await jt({actionId:Re,artifactId:Ut,markdown:rt,jsonPayload:vt}):Re==="markdown"||Re==="md"?await navigator.clipboard.writeText(rt):Re==="json"||Re==="source"?await navigator.clipboard.writeText(vt):await navigator.clipboard.writeText(rt||vt)}catch{}},anchor:W!=null?W:I,position:"bottom-right",portal:Q()})};f.isConnected?le():requestAnimationFrame(le),I.addEventListener("click",Re=>{Re.stopPropagation(),D==null||D.toggle()})}O.addEventListener("click",async()=>{var Q;try{await((Q=r==null?void 0:r.onDocumentToolbarRefresh)==null?void 0:Q.call(r))}catch{}pe()}),J.addEventListener("click",()=>{var Q;p(),(Q=t.onDismiss)==null||Q.call(t)});let te=()=>{n&&(E.setAttribute("aria-pressed",b==="rendered"?"true":"false"),A.setAttribute("aria-pressed",b==="source"?"true":"false"))};E.addEventListener("click",()=>{b="rendered",te(),pe()}),A.addEventListener("click",()=>{b="source",te(),pe()});let Se=w("span","persona-min-w-0 persona-flex-1 persona-text-xs persona-font-medium persona-text-persona-primary persona-truncate persona-text-center md:persona-text-left");n?(u.replaceChildren(),L.append(E,A),W?T.append(W,O,J):T.append(H,O,J),u.append(L,Se,T),te()):(u.appendChild(m),u.appendChild(x)),a&&(u.style.paddingLeft=a,u.style.paddingRight=a);let We=w("div","persona-artifact-list persona-shrink-0 persona-flex persona-gap-1 persona-overflow-x-auto persona-p-2 persona-border-b persona-border-persona-border"),de=w("div","persona-artifact-content persona-flex-1 persona-min-h-0 persona-overflow-y-auto persona-p-3");a&&(We.style.paddingLeft=a,We.style.paddingRight=a,de.style.padding=a),f.appendChild(u),f.appendChild(We),f.appendChild(de);let ve=[],se=null,ie=!1,pe=()=>{var rt,vt,Ut,jt;let Q=n&&ve.length<=1;We.classList.toggle("persona-hidden",Q),We.replaceChildren();for(let at of ve){let Ne=w("button","persona-artifact-tab persona-shrink-0 persona-rounded-lg persona-px-2 persona-py-1 persona-text-xs persona-border persona-border-transparent persona-text-persona-primary");Ne.type="button",Ne.textContent=at.title||at.id.slice(0,8),at.id===se&&Ne.classList.add("persona-bg-persona-container","persona-border-persona-border"),Ne.addEventListener("click",()=>t.onSelect(at.id)),We.appendChild(Ne)}de.replaceChildren();let le=se&&ve.find(at=>at.id===se)||ve[ve.length-1];if(!le)return;if(n){let at=le.artifactType==="markdown"?"MD":(rt=le.component)!=null?rt:"Component",j=(le.title||"Document").trim().replace(/\s*·\s*MD\s*$/i,"").trim()||"Document";Se.textContent=`${j} \xB7 ${at}`}else m.textContent="Artifacts";if(le.artifactType==="markdown"){if(n&&b==="source"){let Ne=w("pre","persona-font-mono persona-text-xs persona-whitespace-pre-wrap persona-break-words persona-text-persona-primary");Ne.textContent=(vt=le.markdown)!=null?vt:"",de.appendChild(Ne);return}let at=w("div","persona-text-sm persona-leading-relaxed persona-markdown-bubble");at.innerHTML=c((Ut=le.markdown)!=null?Ut:""),de.appendChild(at);return}let Re=le.component?on.get(le.component):void 0;if(Re){let Ne={message:{id:le.id,role:"assistant",content:"",createdAt:new Date().toISOString()},config:e,updateProps:()=>{}};try{let j=Re((jt=le.props)!=null?jt:{},Ne);if(j){de.appendChild(j);return}}catch{}}de.appendChild(qv(le))},Ve=()=>{var le;let Q=ve.length>0;if(f.classList.toggle("persona-hidden",!Q),l){let Re=typeof f.closest=="function"?f.closest("[data-persona-root]"):null,vt=((le=Re==null?void 0:Re.classList.contains("persona-artifact-narrow-host"))!=null?le:!1)||typeof window!="undefined"&&window.matchMedia("(max-width: 640px)").matches;Q&&vt&&ie?(l.classList.remove("persona-hidden"),f.classList.add("persona-artifact-drawer-open")):(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open"))}};return{element:f,backdrop:l,update(Q){var le,Re,rt;ve=Q.artifacts,se=(rt=(Re=Q.selectedId)!=null?Re:(le=Q.artifacts[Q.artifacts.length-1])==null?void 0:le.id)!=null?rt:null,ve.length>0&&(ie=!0),pe(),Ve()},setMobileOpen(Q){ie=Q,!Q&&l?(l.classList.add("persona-hidden"),f.classList.remove("persona-artifact-drawer-open")):Ve()}}}function po(e){var t,r;return((r=(t=e==null?void 0:e.features)==null?void 0:t.artifacts)==null?void 0:r.enabled)===!0}function Jh(e,t){var a,s,i,c;if(e.classList.remove("persona-artifact-border-full","persona-artifact-border-left"),e.style.removeProperty("--persona-artifact-pane-border"),e.style.removeProperty("--persona-artifact-pane-border-left"),!po(t))return;let r=(s=(a=t.features)==null?void 0:a.artifacts)==null?void 0:s.layout,o=(i=r==null?void 0:r.paneBorder)==null?void 0:i.trim(),n=(c=r==null?void 0:r.paneBorderLeft)==null?void 0:c.trim();o?(e.classList.add("persona-artifact-border-full"),e.style.setProperty("--persona-artifact-pane-border",o)):n&&(e.classList.add("persona-artifact-border-left"),e.style.setProperty("--persona-artifact-pane-border-left",n))}function Vv(e){e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color"),e.style.removeProperty("--persona-artifact-doc-toggle-active-bg"),e.style.removeProperty("--persona-artifact-doc-toggle-active-border")}function el(e,t){var c,l,p,f,u,m,x,b,L,E;if(!po(t)){e.style.removeProperty("--persona-artifact-split-gap"),e.style.removeProperty("--persona-artifact-pane-width"),e.style.removeProperty("--persona-artifact-pane-max-width"),e.style.removeProperty("--persona-artifact-pane-min-width"),e.style.removeProperty("--persona-artifact-pane-bg"),e.style.removeProperty("--persona-artifact-pane-padding"),Vv(e),Jh(e,t);return}let r=(l=(c=t.features)==null?void 0:c.artifacts)==null?void 0:l.layout;e.style.setProperty("--persona-artifact-split-gap",(p=r==null?void 0:r.splitGap)!=null?p:"0.5rem"),e.style.setProperty("--persona-artifact-pane-width",(f=r==null?void 0:r.paneWidth)!=null?f:"40%"),e.style.setProperty("--persona-artifact-pane-max-width",(u=r==null?void 0:r.paneMaxWidth)!=null?u:"28rem"),r!=null&&r.paneMinWidth?e.style.setProperty("--persona-artifact-pane-min-width",r.paneMinWidth):e.style.removeProperty("--persona-artifact-pane-min-width");let o=(m=r==null?void 0:r.paneBackground)==null?void 0:m.trim();o?e.style.setProperty("--persona-artifact-pane-bg",o):e.style.removeProperty("--persona-artifact-pane-bg");let n=(x=r==null?void 0:r.panePadding)==null?void 0:x.trim();n?e.style.setProperty("--persona-artifact-pane-padding",n):e.style.removeProperty("--persona-artifact-pane-padding");let a=(b=r==null?void 0:r.documentToolbarIconColor)==null?void 0:b.trim();a?e.style.setProperty("--persona-artifact-doc-toolbar-icon-color",a):e.style.removeProperty("--persona-artifact-doc-toolbar-icon-color");let s=(L=r==null?void 0:r.documentToolbarToggleActiveBackground)==null?void 0:L.trim();s?e.style.setProperty("--persona-artifact-doc-toggle-active-bg",s):e.style.removeProperty("--persona-artifact-doc-toggle-active-bg");let i=(E=r==null?void 0:r.documentToolbarToggleActiveBorderColor)==null?void 0:E.trim();i?e.style.setProperty("--persona-artifact-doc-toggle-active-border",i):e.style.removeProperty("--persona-artifact-doc-toggle-active-border"),Jh(e,t)}var Qh=["panel","seamless"];function tl(e,t){var i,c,l,p,f,u;for(let m of Qh)e.classList.remove(`persona-artifact-appearance-${m}`);if(e.classList.remove("persona-artifact-unified-split"),e.style.removeProperty("--persona-artifact-pane-radius"),e.style.removeProperty("--persona-artifact-pane-shadow"),e.style.removeProperty("--persona-artifact-unified-outer-radius"),!po(t))return;let r=(c=(i=t.features)==null?void 0:i.artifacts)==null?void 0:c.layout,o=(l=r==null?void 0:r.paneAppearance)!=null?l:"panel",n=Qh.includes(o)?o:"panel";e.classList.add(`persona-artifact-appearance-${n}`);let a=(p=r==null?void 0:r.paneBorderRadius)==null?void 0:p.trim();a&&e.style.setProperty("--persona-artifact-pane-radius",a);let s=(f=r==null?void 0:r.paneShadow)==null?void 0:f.trim();if(s&&e.style.setProperty("--persona-artifact-pane-shadow",s),(r==null?void 0:r.unifiedSplitChrome)===!0){e.classList.add("persona-artifact-unified-split");let m=((u=r.unifiedSplitOuterRadius)==null?void 0:u.trim())||a;m&&e.style.setProperty("--persona-artifact-unified-outer-radius",m)}}function Yh(e,t){var r,o,n;return!t||!po(e)?!1:((n=(o=(r=e.features)==null?void 0:r.artifacts)==null?void 0:o.layout)==null?void 0:n.expandLauncherPanelWhenOpen)!==!1}function zv(e,t){if(!(e!=null&&e.trim()))return t;let r=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return r?Math.max(0,Number(r[1])):t}function $v(e){if(!(e!=null&&e.trim()))return null;let t=/^(\d+(?:\.\d+)?)px\s*$/i.exec(e.trim());return t?Math.max(0,Number(t[1])):null}function jv(e,t,r){return r<t?t:Math.min(r,Math.max(t,e))}function Gv(e,t,r,o){let n=e-o-2*t-r;return Math.max(0,n)}function Zh(e,t){var s;let o=(s=(t.getComputedStyle(e).gap||"0px").trim().split(/\s+/)[0])!=null?s:"0px",n=/^([\d.]+)px$/i.exec(o);if(n)return Number(n[1]);let a=/^([\d.]+)/.exec(o);return a?Number(a[1]):8}function ex(e,t,r,o,n,a){let s=zv(n,200),i=Gv(t,r,o,200);i=Math.max(s,i);let c=$v(a);return c!==null&&(i=Math.min(i,c)),jv(e,s,i)}var tx={init:{title:"Schedule a Demo",description:"Share the basics and we'll follow up with a confirmation.",fields:[{name:"name",label:"Full name",placeholder:"Jane Doe",required:!0},{name:"email",label:"Work email",placeholder:"jane@example.com",type:"email",required:!0},{name:"notes",label:"What would you like to cover?",type:"textarea"}],submitLabel:"Submit details"},followup:{title:"Additional Information",description:"Provide any extra details to tailor the next steps.",fields:[{name:"company",label:"Company",placeholder:"Acme Inc."},{name:"context",label:"Context",type:"textarea",placeholder:"Share more about your use case"}],submitLabel:"Send"}},fp=(e,t,r,o)=>{let n=e.querySelectorAll("[data-tv-form]");n.length&&n.forEach(a=>{var x,b,L;if(a.dataset.enhanced==="true")return;let s=(x=a.dataset.tvForm)!=null?x:"init";a.dataset.enhanced="true";let i=(b=tx[s])!=null?b:tx.init;a.classList.add("persona-form-card","persona-space-y-4");let c=w("div","persona-space-y-1"),l=w("h3","persona-text-base persona-font-semibold persona-text-persona-primary");if(l.textContent=i.title,c.appendChild(l),i.description){let E=w("p","persona-text-sm persona-text-persona-muted");E.textContent=i.description,c.appendChild(E)}let p=document.createElement("form");p.className="persona-form-grid persona-space-y-3",i.fields.forEach(E=>{var v,M;let A=w("label","persona-form-field persona-flex persona-flex-col persona-gap-1");A.htmlFor=`${t.id}-${s}-${E.name}`;let T=w("span","persona-text-xs persona-font-medium persona-text-persona-muted");T.textContent=E.label,A.appendChild(T);let y=(v=E.type)!=null?v:"text",S;y==="textarea"?(S=document.createElement("textarea"),S.rows=3):(S=document.createElement("input"),S.type=y),S.className="persona-rounded-xl persona-border persona-border-gray-200 persona-bg-white persona-px-3 persona-py-2 persona-text-sm persona-text-persona-primary focus:persona-outline-none focus:persona-border-persona-primary",S.id=`${t.id}-${s}-${E.name}`,S.name=E.name,S.placeholder=(M=E.placeholder)!=null?M:"",E.required&&(S.required=!0),A.appendChild(S),p.appendChild(A)});let f=w("div","persona-flex persona-items-center persona-justify-between persona-gap-2"),u=w("div","persona-text-xs persona-text-persona-muted persona-min-h-[1.5rem]"),m=w("button","persona-inline-flex persona-items-center persona-rounded-full persona-bg-persona-primary persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-60 persona-cursor-pointer");m.type="submit",m.textContent=(L=i.submitLabel)!=null?L:"Submit",f.appendChild(u),f.appendChild(m),p.appendChild(f),a.replaceChildren(c,p),p.addEventListener("submit",async E=>{var S,v;E.preventDefault();let A=(S=r.formEndpoint)!=null?S:"/form",T=new FormData(p),y={};T.forEach((M,W)=>{y[W]=M}),y.type=s,m.disabled=!0,u.textContent="Submitting\u2026";try{let M=await fetch(A,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(y)});if(!M.ok)throw new Error(`Form submission failed (${M.status})`);let W=await M.json();u.textContent=(v=W.message)!=null?v:"Thanks! We'll be in touch soon.",W.success&&W.nextPrompt&&await o.sendMessage(String(W.nextPrompt))}catch(M){u.textContent=M instanceof Error?M.message:"Something went wrong. Please try again."}finally{m.disabled=!1}})})};var mp=class{constructor(){this.plugins=new Map}register(t){var r;this.plugins.has(t.id)&&console.warn(`Plugin "${t.id}" is already registered. Overwriting.`),this.plugins.set(t.id,t),(r=t.onRegister)==null||r.call(t)}unregister(t){var o;let r=this.plugins.get(t);r&&((o=r.onUnregister)==null||o.call(r),this.plugins.delete(t))}getAll(){return Array.from(this.plugins.values()).sort((t,r)=>{var o,n;return((o=r.priority)!=null?o:0)-((n=t.priority)!=null?n:0)})}getForInstance(t){let r=this.getAll();if(!t||t.length===0)return r;let o=new Set(t.map(a=>a.id));return[...r.filter(a=>!o.has(a.id)),...t].sort((a,s)=>{var i,c;return((i=s.priority)!=null?i:0)-((c=a.priority)!=null?c:0)})}clear(){this.plugins.forEach(t=>{var r;return(r=t.onUnregister)==null?void 0:r.call(t)}),this.plugins.clear()}},Is=new mp;var rx=()=>{let e=new Map,t=(n,a)=>(e.has(n)||e.set(n,new Set),e.get(n).add(a),()=>r(n,a)),r=(n,a)=>{var s;(s=e.get(n))==null||s.delete(a)};return{on:t,off:r,emit:(n,a)=>{var s;(s=e.get(n))==null||s.forEach(i=>{try{i(a)}catch(c){typeof console!="undefined"&&console.error("[AgentWidget] Event handler error:",c)}})}}};var Kv=e=>{let t=e.match(/```(?:json)?\s*([\s\S]*?)```/i);return t?t[1]:e},Xv=e=>{let t=e.trim(),r=t.indexOf("{");if(r===-1)return null;let o=0;for(let n=r;n<t.length;n+=1){let a=t[n];if(a==="{"&&(o+=1),a==="}"&&(o-=1,o===0))return t.slice(r,n+1)}return null},Ws=({text:e})=>{if(!e||!e.includes("{"))return null;try{let t=Kv(e),r=Xv(t);if(!r)return null;let o=JSON.parse(r);if(!o||typeof o!="object"||!o.action)return null;let{action:n,...a}=o;return{type:String(n),payload:a,raw:o}}catch{return null}},gp=e=>typeof e=="string"?e:e==null?"":String(e),la={message:e=>e.type!=="message"?void 0:{handled:!0,displayText:gp(e.payload.text)},messageAndClick:(e,t)=>{var n;if(e.type!=="message_and_click")return;let r=e.payload,o=gp(r.element);if(o&&((n=t.document)!=null&&n.querySelector)){let a=t.document.querySelector(o);a?setTimeout(()=>{a.click()},400):typeof console!="undefined"&&console.warn("[AgentWidget] Element not found for selector:",o)}return{handled:!0,displayText:gp(r.text)}}},ox=e=>Array.isArray(e)?e.map(t=>String(t)):[],Hs=e=>{let t=new Set(ox(e.getSessionMetadata().processedActionMessageIds)),r=()=>{t=new Set(ox(e.getSessionMetadata().processedActionMessageIds))},o=()=>{let a=Array.from(t);e.updateSessionMetadata(s=>({...s,processedActionMessageIds:a}))};return{process:a=>{if(a.streaming||a.message.role!=="assistant"||!a.text||t.has(a.message.id))return null;let s=typeof a.raw=="string"&&a.raw||typeof a.message.rawContent=="string"&&a.message.rawContent||typeof a.text=="string"&&a.text||null;!s&&typeof a.text=="string"&&a.text.trim().startsWith("{")&&typeof console!="undefined"&&console.warn("[AgentWidget] Structured response detected but no raw payload was provided. Ensure your stream parser returns { text, raw }.");let i=s?e.parsers.reduce((l,p)=>l||(p==null?void 0:p({text:s,message:a.message}))||null,null):null;if(!i)return null;t.add(a.message.id),o();let c={action:i,message:a.message};e.emit("action:detected",c);for(let l of e.handlers)if(l)try{let p=()=>{e.emit("action:resubmit",c)},f=l(i,{message:a.message,metadata:e.getSessionMetadata(),updateMetadata:e.updateSessionMetadata,document:e.documentRef,triggerResubmit:p});if(!f)continue;if(f.handled){let u=f.persistMessage!==!1;return{text:f.displayText!==void 0?f.displayText:"",persist:u,resubmit:f.resubmit}}}catch(p){typeof console!="undefined"&&console.error("[AgentWidget] Action handler error:",p)}return{text:"",persist:!0}},syncFromMetadata:r}};var Jv=e=>{if(!e)return null;try{return JSON.parse(e)}catch(t){return typeof console!="undefined"&&console.error("[AgentWidget] Failed to parse stored state:",t),null}},Qv=e=>e.map(t=>({...t,streaming:!1})),Yv=e=>e.map(t=>({...t,status:"complete"})),rl=(e="persona-state")=>{let t=()=>typeof window=="undefined"||!window.localStorage?null:window.localStorage;return{load:()=>{let r=t();return r?Jv(r.getItem(e)):null},save:r=>{let o=t();if(o)try{let n={...r,messages:r.messages?Qv(r.messages):void 0,artifacts:r.artifacts?Yv(r.artifacts):void 0};o.setItem(e,JSON.stringify(n))}catch(n){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",n)}},clear:()=>{let r=t();if(r)try{r.removeItem(e)}catch(o){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear stored state:",o)}}}};var qa=Sa(Ys(),1);function Zv(e){if(!e||typeof e!="object"||!("component"in e))return!1;let t=e.component;return typeof t=="string"&&t.length>0}function e0(e,t){if(!Zv(e))return null;let r=e.props&&typeof e.props=="object"&&e.props!==null?e.props:{};return{component:e.component,props:r,raw:t}}function ol(){let e=null,t=0;return{getExtractedDirective:()=>e,processChunk:r=>{let o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;if(r.length<=t)return e;try{let n=(0,qa.parse)(r,qa.STR|qa.OBJ),a=e0(n,r);a&&(e=a)}catch{}return t=r.length,e},reset:()=>{e=null,t=0}}}function nx(e){return typeof e=="object"&&e!==null&&"component"in e&&typeof e.component=="string"&&"props"in e&&typeof e.props=="object"}function nl(e,t){let{config:r,message:o,onPropsUpdate:n}=t,a=on.get(e.component);if(!a)return console.warn(`[ComponentMiddleware] Component "${e.component}" not found in registry. Falling back to default rendering.`),null;let s={message:o,config:r,updateProps:i=>{n&&n(i)}};try{return a(e.props,s)}catch(i){return console.error(`[ComponentMiddleware] Error rendering component "${e.component}":`,i),null}}function ax(){let e=ol();return{processChunk:t=>e.processChunk(t),getDirective:()=>e.getExtractedDirective(),reset:()=>{e.reset()}}}function sx(e){if(typeof e.rawContent=="string"&&e.rawContent.length>0)return e.rawContent;if(typeof e.content=="string"){let t=e.content.trim();if(t.startsWith("{")||t.startsWith("["))return e.content}return null}function al(e){let t=sx(e);if(!t)return!1;try{let r=JSON.parse(t);return typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"}catch{return!1}}function sl(e){let t=sx(e);if(!t)return null;try{let r=JSON.parse(t);if(typeof r=="object"&&r!==null&&"component"in r&&typeof r.component=="string"){let o=r;return{component:o.component,props:o.props&&typeof o.props=="object"&&o.props!==null?o.props:{},raw:t}}}catch{}return null}var t0=["Very dissatisfied","Dissatisfied","Neutral","Satisfied","Very satisfied"];function il(e){let{onSubmit:t,onDismiss:r,title:o="How satisfied are you?",subtitle:n="Please rate your experience",commentPlaceholder:a="Share your thoughts (optional)...",submitText:s="Submit",skipText:i="Skip",showComment:c=!0,ratingLabels:l=t0}=e,p=document.createElement("div");p.className="persona-feedback-container persona-feedback-csat",p.setAttribute("role","dialog"),p.setAttribute("aria-label","Customer satisfaction feedback");let f=null,u=document.createElement("div");u.className="persona-feedback-content";let m=document.createElement("div");m.className="persona-feedback-header";let x=document.createElement("h3");x.className="persona-feedback-title",x.textContent=o,m.appendChild(x);let b=document.createElement("p");b.className="persona-feedback-subtitle",b.textContent=n,m.appendChild(b),u.appendChild(m);let L=document.createElement("div");L.className="persona-feedback-rating persona-feedback-rating-csat",L.setAttribute("role","radiogroup"),L.setAttribute("aria-label","Satisfaction rating from 1 to 5");let E=[];for(let v=1;v<=5;v++){let M=document.createElement("button");M.type="button",M.className="persona-feedback-rating-btn persona-feedback-star-btn",M.setAttribute("role","radio"),M.setAttribute("aria-checked","false"),M.setAttribute("aria-label",`${v} star${v>1?"s":""}: ${l[v-1]}`),M.title=l[v-1],M.dataset.rating=String(v),M.innerHTML=`