@runtypelabs/persona 3.33.0 → 3.34.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -6,7 +6,7 @@ ${t}`:"")+(e.description?`
6
6
  ${e.description}`:"");return window.confirm(n)},Vg=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)}},Kg=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Gg=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};import{parse as Jg,ARR as Qg,OBJ as Xg,STR as Yg}from"partial-json";var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Hr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var Da="ask_user_question",zs=8,ls="data-persona-ask-sheet-for",Zg="Other",ef="Other\u2026",mu="Type your own answer here",gu="Send",tf="Next",nf="Back",rf="Submit all",of="Skip",sf=3,zi="data-ask-current-index",Vi="data-ask-question-count",fu="data-ask-answers",Ki="data-ask-grouped",hu="data-ask-layout",af=e=>e.layout==="pills"?"pills":"rows",lf=e=>e.getAttribute(hu)==="pills"?"pills":"rows",uu=!1,bu=e=>e.replace(/["\\]/g,"\\$&"),mo=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===Da,Oa=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},go=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let s=r.join(""),o=Jg(s,Yg|Xg|Qg);if(o&&typeof o=="object")return{payload:o,complete:n}}catch{}return{payload:null,complete:n}},Vs=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>zs&&!uu&&(uu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${zs}.`)),t.slice(0,zs)},cf=e=>{var t;return(t=Vs(e)[0])!=null?t:null},df=(e,t)=>{var n;return(n=Vs(e)[t])!=null?n:null},yu=(e,t)=>{let n=t.styles;n&&(n.sheetBackground&&e.style.setProperty("--persona-ask-sheet-bg",n.sheetBackground),n.sheetBorder&&e.style.setProperty("--persona-ask-sheet-border",n.sheetBorder),n.sheetShadow&&e.style.setProperty("--persona-ask-sheet-shadow",n.sheetShadow),n.pillBackground&&e.style.setProperty("--persona-ask-pill-bg",n.pillBackground),n.pillBackgroundSelected&&e.style.setProperty("--persona-ask-pill-bg-selected",n.pillBackgroundSelected),n.pillTextColor&&e.style.setProperty("--persona-ask-pill-fg",n.pillTextColor),n.pillTextColorSelected&&e.style.setProperty("--persona-ask-pill-fg-selected",n.pillTextColorSelected),n.pillBorderRadius&&e.style.setProperty("--persona-ask-pill-radius",n.pillBorderRadius),n.customInputBackground&&e.style.setProperty("--persona-ask-input-bg",n.customInputBackground))},xu=(e,t,n)=>{if(e!=="rows")return null;let r=h("span","persona-ask-row-affordance");if(r.setAttribute("aria-hidden","true"),t){let s=h("span","persona-ask-row-check");r.appendChild(s)}else{let s=h("span","persona-ask-row-badge");s.textContent=String(n+1),r.appendChild(s)}return r},pf=(e,t,n,r)=>{let o=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(o.type="button",o.setAttribute("role",r?"checkbox":"button"),o.setAttribute("aria-pressed","false"),o.setAttribute("data-ask-user-action","pick"),o.setAttribute("data-option-index",String(t)),o.setAttribute("data-option-label",e.label),n==="rows"){let a=h("span","persona-ask-row-content"),i=h("span","persona-ask-row-label");if(i.textContent=e.label,a.appendChild(i),e.description){let l=h("span","persona-ask-row-description");l.textContent=e.description,a.appendChild(l)}o.appendChild(a);let d=xu(n,r,t);d&&o.appendChild(d)}else o.textContent=e.label,e.description&&(o.title=e.description);return o},uf=e=>{let n=h("span",e==="rows"?"persona-ask-pill persona-ask-row persona-ask-pill-skeleton persona-pointer-events-none":"persona-ask-pill persona-ask-pill-skeleton persona-pointer-events-none");return n.setAttribute("aria-hidden","true"),n},mf=(e,t,n,r)=>{var p,u,f;let o=h("div",r==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");o.setAttribute("role","group"),o.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<sf;g++)o.appendChild(uf(r));return o}if(d.forEach((g,v)=>{o.appendChild(pf(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Zg:ef;if(r==="rows"){let v=h("div","persona-ask-pill persona-ask-row persona-ask-row--other persona-ask-pill-custom persona-pointer-events-auto");v.setAttribute("data-ask-user-action","focus-free-text"),v.setAttribute("data-option-index",String(d.length)),v.setAttribute("data-ask-other-row","true");let y=h("span","persona-ask-row-content"),w=document.createElement("input");w.type="text",w.className="persona-ask-row-input persona-flex-1 persona-pointer-events-auto",w.placeholder=(p=t.freeTextPlaceholder)!=null?p:mu,w.setAttribute("data-ask-free-text-input","true"),w.setAttribute("aria-label",(u=t.freeTextLabel)!=null?u:g),y.appendChild(w),v.appendChild(y);let A=xu(r,a,d.length);A&&v.appendChild(A),o.appendChild(v)}else{let v=h("button","persona-ask-pill persona-ask-pill-custom persona-pointer-events-auto");v.type="button",v.setAttribute("data-ask-user-action","open-free-text"),v.textContent=(f=t.freeTextLabel)!=null?f:g,o.appendChild(v)}}return o},vu=(e,t)=>{var o,a;let r=h("div",t==="rows"?"persona-ask-free-text persona-ask-free-text--rows persona-flex persona-gap-2 persona-mt-2":"persona-ask-free-text persona-hidden persona-flex persona-gap-2 persona-mt-2");r.setAttribute("data-ask-free-text-row","true");let s=document.createElement("input");if(s.type="text",s.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",s.placeholder=(o=e.freeTextPlaceholder)!=null?o:mu,s.setAttribute("data-ask-free-text-input","true"),r.appendChild(s),t!=="rows"){let i=h("button","persona-ask-free-text-submit persona-pointer-events-auto");i.type="button",i.textContent=(a=e.submitLabel)!=null?a:gu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},gf=e=>{var r;let t=h("div","persona-ask-multi-actions persona-flex persona-justify-end persona-mt-2");t.setAttribute("data-ask-multi-actions","true");let n=h("button","persona-ask-multi-submit persona-pointer-events-auto");return n.type="button",n.textContent=(r=e.submitLabel)!=null?r:gu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},ff=(e,t,n)=>{var l,p,u,f;let r=h("div","persona-ask-nav persona-flex persona-justify-between persona-items-center persona-gap-2 persona-mt-2");r.setAttribute("data-ask-nav-row","true");let s=h("button","persona-ask-nav-back persona-pointer-events-auto");s.type="button",s.textContent=(l=n.backLabel)!=null?l:nf,s.setAttribute("data-ask-user-action","back"),s.disabled=e===0,r.appendChild(s);let o=h("div","persona-ask-nav-right persona-flex persona-items-center persona-gap-2"),a=h("button","persona-ask-nav-skip persona-pointer-events-auto");a.type="button",a.textContent=(p=n.skipLabel)!=null?p:of,a.setAttribute("data-ask-user-action","skip"),o.appendChild(a);let i=h("button","persona-ask-nav-next persona-pointer-events-auto");i.type="button";let d=e===t-1;return i.textContent=d?(u=n.submitAllLabel)!=null?u:rf:(f=n.nextLabel)!=null?f:tf,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,o.appendChild(i),r.appendChild(o),r},Oo=e=>{let t=e.getAttribute(fu);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},wu=(e,t)=>{e.setAttribute(fu,JSON.stringify(t))},dr=e=>{var n;let t=Number((n=e.getAttribute(zi))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},hf=(e,t)=>{e.setAttribute(zi,String(Math.max(0,Math.floor(t))))},cs=e=>{var n;let t=Number((n=e.getAttribute(Vi))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},fo=e=>e.getAttribute(Ki)==="true",bf=(e,t)=>{var s;let n=(s=e.agentMetadata)==null?void 0:s.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((o,a)=>{let i=typeof(o==null?void 0:o.question)=="string"?o.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},yf=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},Na=(e,t)=>{let{payload:n}=go(t),r=Vs(n),s=Oo(e),o={},a=new Set;return r.forEach((i,d)=>{let l=typeof(i==null?void 0:i.question)=="string"?i.question:"";l&&(a.has(l)&&typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question has duplicate question text "${l}"; later answer wins.`),a.add(l),Object.prototype.hasOwnProperty.call(s,d)&&(o[l]=s[d]))}),o},Cu=e=>{let t=Oo(e),n=dr(e),r=t[n],s=new Set;typeof r=="string"?s.add(r):Array.isArray(r)&&r.forEach(d=>s.add(d));let o=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');o.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=s.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(o).map(d=>{var l;return(l=d.getAttribute("data-option-label"))!=null?l:""})),i=e.querySelector('[data-ask-free-text-input="true"]');if(i)if(typeof r=="string"&&r.length>0&&!a.has(r)){i.value=r;let d=i.closest('[data-ask-free-text-row="true"]');d==null||d.classList.remove("persona-hidden")}else i.value=""},Au=e=>{if(!fo(e))return;let t=Oo(e),n=dr(e),r=t[n],s=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,o=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');o&&(o.disabled=!s);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Gi=(e,t,n)=>{let r=Oa(n),s=lf(e),{payload:o,complete:a}=go(t),i=fo(e),d=dr(e),l=cs(e),p=i?df(o,d):cf(o),u=!!(p!=null&&p.multiSelect),f=e.querySelector('[data-ask-step-inline="true"]');f&&(f.textContent=i?`${d+1}/${l}`:"");let g=e.querySelector('[data-ask-stepper="true"]');g&&g.remove();let v=e.querySelector('[data-ask-question="true"]');if(v){let D=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=D,v.classList.toggle("persona-ask-question-skeleton",!D&&!a)}let y=e.querySelector('[data-ask-pill-list="true"]');if(y){let D=mf(p,r,a,s);y.replaceWith(D)}if(s!=="rows"){let D=e.querySelector('[data-ask-free-text-row="true"]');D&&D.replaceWith(vu(r,s))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(gf(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let A=e.querySelector('[data-ask-nav-row="true"]');if(i){let D=ff(d,l,r);A?A.replaceWith(D):e.appendChild(D)}else A&&A.remove();Cu(e),Au(e)},xf=(e,t,n)=>{let r=Oa(t),s=af(r),o=e.toolCall.id,a=Vs(n),i=Math.max(1,a.length),d=i>1,l=bf(e,a),p=d?yf(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${s}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ls,o),u.setAttribute("data-tool-call-id",o),u.setAttribute("data-message-id",e.id),u.setAttribute(Vi,String(i)),u.setAttribute(zi,String(p)),u.setAttribute(Ki,d?"true":"false"),u.setAttribute(hu,s),wu(u,l),u.setAttribute("role","group"),u.setAttribute("aria-label","Suggested answers"),r.slideInMs!==void 0&&u.style.setProperty("--persona-ask-sheet-duration",`${r.slideInMs}ms`),yu(u,r);let f=h("div","persona-ask-sheet-header persona-flex persona-items-center persona-gap-3"),g=h("div","persona-ask-sheet-question persona-flex-1");g.setAttribute("data-ask-question","true"),g.textContent="",f.appendChild(g);let v=h("span","persona-ask-sheet-step-inline");v.setAttribute("data-ask-step-inline","true"),v.textContent="",f.appendChild(v),u.appendChild(f);let w=h("div",s==="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 w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),s!=="rows"&&u.appendChild(vu(r,s)),Gi(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},vf=(e,t,n)=>{let{payload:r}=go(t),s=Math.max(1,Vs(r).length);s>cs(e)&&(e.setAttribute(Vi,String(s)),s>1&&!fo(e)&&e.setAttribute(Ki,"true")),Gi(e,t,n)},wf=(e,t)=>{let n=h("div","persona-ask-stub persona-inline-flex persona-items-center persona-gap-2");n.id=`bubble-${e.id}`,n.setAttribute("data-message-id",e.id),n.setAttribute("data-bubble-type","ask-user-question");let r=Oa(t);yu(n,r);let s=h("span","persona-ask-stub-label"),{complete:o}=go(e);return s.textContent=o?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(s),n},Ks=(e,t,n)=>{if(!n||!mo(e)||Oa(t).enabled===!1)return;let s=e.toolCall.id;n.querySelectorAll(`[${ls}]`).forEach(l=>{l.getAttribute(ls)!==s&&l.remove()});let a=n.querySelector(`[${ls}="${bu(s)}"]`);if(a){vf(a,e,t);return}let{payload:i}=go(e),d=xf(e,t,i);n.appendChild(d)},No=(e,t)=>{if(!e)return;let n=t?`[${ls}="${bu(t)}"]`:`[${ls}]`;e.querySelectorAll(n).forEach(s=>{s.classList.add("persona-ask-sheet-leave");let o=Number.parseInt(getComputedStyle(s).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>s.remove(),Number.isFinite(o)?o:180)})},Ji=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),ho=(e,t)=>{let n=Oo(e),r=dr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,wu(e,n),Cu(e),Au(e)},Fa=(e,t,n,r)=>{let s=cs(e),o=Math.max(0,Math.min(s-1,r));hf(e,o),Gi(e,t,n)};var Br="suggest_replies";var Su={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},Qi={name:Br,description:`Offer the user tappable quick-reply suggestions for their next message. Call at most once per turn, as the LAST action after your reply text is complete. Each suggestion is sent verbatim as the user's next message, so phrase suggestions in the user's voice (e.g. "Tell me more about pricing"). Keep them short and distinct. The result only confirms the suggestions were shown \u2014 do not add further commentary after calling this tool; end your turn.`,parametersSchema:Su,origin:"sdk",annotations:{readOnlyHint:!0}},Xi=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),_a=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Br},Tu=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(s=>typeof s=="string").map(s=>s.trim()).filter(s=>s.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},Yi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!_a(r))continue;let s=Tu((t=r.toolCall)==null?void 0:t.args);return s.length>0?s:null}return null},Eu=e=>{var n;let t=(n=e==null?void 0:e.features)==null?void 0:n.suggestReplies;return(t==null?void 0:t.expose)===!0&&t.enabled!==!1};var Mu={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:zs,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 \u2014 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},ku={name:Da,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 \u2014 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:Mu,origin:"sdk",annotations:{readOnlyHint:!0}},$a=e=>{var r;let t=[],n=(r=e==null?void 0:e.features)==null?void 0:r.askUserQuestion;return(n==null?void 0:n.expose)===!0&&n.enabled!==!1&&t.push(ku),Eu(e)&&t.push(Qi),t};import{parse as Lu,STR as Pu,OBJ as Iu}from"partial-json";var Ua=e=>e.replace(/\\n/g,`
7
7
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),ds=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)}},Cf=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,s=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return s<.1?"Thought for <0.1 seconds":`Thought for ${s>=10?Math.round(s).toString():s.toFixed(1).replace(/\.0$/,"")} seconds`},Ru=e=>e.status==="complete"?Cf(e):e.status==="pending"?"Waiting":"",Af=e=>{var s,o,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((s=e.completedAt)!=null?s:Date.now())-((a=(o=e.startedAt)!=null?o:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var Wu=e=>e.status==="complete"?Af(e):"Using tool...",ja=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},Js=e=>{var n,r,s;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ja(t)},qa=e=>{var n,r,s;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((s=(r=e.startedAt)!=null?r:e.completedAt)!=null?s:Date.now()));return ja(t)},Zi=(e,t,n)=>{var o;if(!t)return n;let r=((o=e.name)==null?void 0:o.trim())||"tool",s=Js(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,s)},za=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],s=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,o=0,a;for(;(a=s.exec(n))!==null;)a.index>o&&Gs(r,n.slice(o,a.index),[]),a[1]!==void 0?Gs(r,a[1],["bold"]):a[2]!==void 0?Gs(r,a[2],["italic"]):a[3]!==void 0&&Gs(r,a[3],["dim"]),o=a.index+a[0].length;return o<n.length&&Gs(r,n.slice(o),[]),r},Gs=(e,t,n)=>{let r=t.split("{duration}");for(let s=0;s<r.length;s++)r[s]&&e.push({text:r[s],styles:n}),s<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},Sf=()=>{let e=null,t=0,n=r=>{let s=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,o=r.match(s);if(o&&o[1])try{return o[1].replace(/\\n/g,`
8
8
  `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return o[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
9
- `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Fo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},el=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tl=()=>{var t;let e=Sf();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},nl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=Lu(n,Pu|Iu);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ua(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ua(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Tf=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ua(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ua(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Lu(o,Pu|Iu),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},rl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Va=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Ef="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Mf(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ol=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 kf(e){switch(e){case"json":return nl;case"regex-json":return tl;case"xml":return rl;default:return el}}var Hu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lf(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Hu(n);if(!Hu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Fo(e);return Fo(t)!==null&&a===null?t:e}var ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Ef,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:kf(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.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 n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/feedback`}async sendFeedback(t){var o,a;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 s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!s.ok){let i=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(a=(o=this.config).onSessionExpired)==null||a.call(o),new Error("Session expired. Please refresh to continue.")):new Error(i.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ol).map(P=>{var I,S,R;return{id:P.id,role:P.role,content:(R=(S=(I=P.contentParts)!=null?I:P.llmContent)!=null?S:P.rawContent)!=null?R:P.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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?pu(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,A=!1,D=null,M;for(let P=0;;P++){let S={...u,...g&&(A||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&P===0&&g){let R=await M.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}D=R!=null?R:{error:"Chat request failed"}}break}if(!M.ok){let P=D!=null?D:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(M.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let I=new Error(P.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!M.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=u,s(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Wt,ln,nr,Sr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=W=>{let de=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,De=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Je=W.tools?W.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...W,reasoning:de,toolCall:De,tools:Je}},u=W=>{if(W.role!=="assistant"||W.variant)return!0;let de=Array.isArray(W.contentParts)&&W.contentParts.length>0,De=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||de||De||!!W.stopReason},f=W=>{u(W)&&n({type:"message",message:p(W)})},g=null,v=null,y={current:null},w={current:null},A=!1,D=new Map,M=new Map,P=new Map,I=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},F=(W,de,De="")=>`${W}::${de}::${De}`,N=(W,de)=>`${W}::${de}::`,E=(W,de,De,Je)=>{let Fe=F(W,de,De),$e=P.get(Fe);if($e)return $e;let st=De?`-${De}`:"",Lt={id:`nested-${W}-${de}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Je,parentToolId:W,parentStepId:de}};return P.set(Fe,Lt),f(Lt),Lt},U=W=>{if(W==null)return null;try{return String(W)}catch{return null}},q=W=>{var de,De,Je,Fe,$e;return U(($e=(Fe=(Je=(De=(de=W.stepId)!=null?de:W.step_id)!=null?De:W.step)!=null?Je:W.parentId)!=null?Fe:W.flowStepId)!=null?$e:W.flow_step_id)},re=W=>{var de,De,Je,Fe,$e,st,Lt;return U((Lt=(st=($e=(Fe=(Je=(De=(de=W.callId)!=null?de:W.call_id)!=null?De:W.requestId)!=null?Je:W.request_id)!=null?Fe:W.toolCallId)!=null?$e:W.tool_call_id)!=null?st:W.stepId)!=null?Lt:W.step_id)},Me=r,qe=!1,we=()=>{if(g)return g;let W;return!qe&&Me?(W=Me,qe=!0):Me&&w.current?W=`${Me}_${w.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Ie=(W,de)=>{S.lastId=de,W&&S.byStep.set(W,de)},he=(W,de)=>{var $e;let De=($e=W.reasoningId)!=null?$e:W.id,Je=q(W);if(De){let st=String(De);return Ie(Je,st),st}if(Je){let st=S.byStep.get(Je);if(st)return S.lastId=st,st}if(S.lastId&&!de)return S.lastId;if(!de)return null;let Fe=`reason-${l()}`;return Ie(Je,Fe),Fe},ke=W=>{let de=D.get(W);if(de)return de;let De={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:W,status:"streaming",chunks:[]}};return D.set(W,De),f(De),De},Re=(W,de)=>{R.lastId=de,W&&R.byCall.set(W,de)},ce=new Set,Q=new Map,ne=new Set,le=new Map,me=W=>{if(!W)return!1;let de=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},V=(W,de)=>{var $e;let De=($e=W.toolId)!=null?$e:W.id,Je=re(W);if(De){let st=String(De);return Re(Je,st),st}if(Je){let st=R.byCall.get(Je);if(st)return R.lastId=st,st}if(R.lastId&&!de)return R.lastId;if(!de)return null;let Fe=`tool-${l()}`;return Re(Je,Fe),Fe},se=W=>{let de=M.get(W);if(de)return de;let De={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:W,status:"pending"}};return M.set(W,De),f(De),De},We=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let de=Number(W);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let De=Date.parse(W);if(!Number.isNaN(De))return De}return Date.now()},X=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Z=new Map,ae=new Map,Ce=new Map,Ye=new Map,xe=null,ge=(W,de,De)=>{var Lt;let Je=Ce.get(W);Je||(Je=[],Ce.set(W,Je));let Fe=0,$e=Je.length;for(;Fe<$e;){let zt=Fe+$e>>>1;Je[zt].seq<de?Fe=zt+1:$e=zt}((Lt=Je[Fe])==null?void 0:Lt.seq)===de?Je[Fe]={seq:de,text:De}:Je.splice(Fe,0,{seq:de,text:De});let st="";for(let zt=0;zt<Je.length;zt++)st+=Je[zt].text;return st},Ge=(W,de)=>{let De=X(de),Je=ae.get(W.id),Fe=Lf(Je,De);W.rawContent=Fe;let $e=Z.get(W.id),st=yt=>{var ve;let it=(ve=W.content)!=null?ve:"";yt.trim()!==""&&(it.trim().length===0||yt.startsWith(it)||yt.trimStart().startsWith(it.trim()))&&(W.content=yt)},Lt=()=>{var yt;if($e){let it=(yt=$e.close)==null?void 0:yt.call($e);it instanceof Promise&&it.catch(()=>{})}Z.delete(W.id),ae.delete(W.id),W.streaming=!1,f(W)};if(!$e){st(De),Lt();return}let zt=Fo(Fe);if(zt!==null&&zt.trim()!==""){st(zt),Lt();return}let Yt=yt=>{var ie;let it=typeof yt=="string"?yt:(ie=yt==null?void 0:yt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let ve=$e.getExtractedText();return ve!==null&&ve.trim()!==""?ve:De},K;try{K=$e.processChunk(Fe)}catch{st(De),Lt();return}if(K instanceof Promise){K.then(yt=>{st(Yt(yt)),Lt()}).catch(()=>{st(De),Lt()});return}st(Yt(K)),Lt()},Be=[],z=!1,pe,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,pe()}))},Tt=new Va((W,de)=>{Be.push({payloadType:W,payload:de}),rt()}),te=null,ze=new Map,On=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(pe=()=>{var W,de,De,Je,Fe,$e,st,Lt,zt,Yt,K,yt,it,ve,ie,tt,en,Vt,Ln,vn,ut,Et,Ze,jt,cn,Cn,An,bn,Tr,Ct,Un,jn,Or,gr,xt,Ao,Er,So,Nn,zo,Qr,Nr,At,qn,zn,Pn,kt,rr,or,Vn,Xr,Fr,Yr,Kn,Ht,In,sr,Zr,_r,eo,Mr,Gn,fr,gt,tn,nn,Jn,to,be,hr,ar,_,Vo,kr,$r,Ur,Lr,br,Ss,Qn,Xn,yr,xr,To,jr,Sn,Pr,Ko,Eo,Go,ya,Jo,xa,Qo,bt,Ts,ir,Fn,va,wa,Xo,qr,Es,no,Ms,ks,Ls,Ps,_n,Yo,Ir,Rr,Is,Ca,Rs,Ws,Mo,Aa,Sa,Ta,Ea,Oi,ko,ro,Ma,Hs,oo,ka,Bs,so,Ds,La,zr,Pa,ao,Bt,Zo,es;for(let Lo=0;Lo<Be.length;Lo++){let Ue=Be[Lo].payloadType,C=Be[Lo].payload;if(Ue==="reason_start"){let $=(W=he(C,!0))!=null?W:`reason-${l()}`,k=ke($);k.reasoning=(de=k.reasoning)!=null?de:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(Je=k.reasoning.startedAt)!=null?Je:We((De=C.startedAt)!=null?De:C.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",f(k)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=($e=(Fe=he(C,!1))!=null?Fe:he(C,!0))!=null?$e:`reason-${l()}`,k=ke($);k.reasoning=(st=k.reasoning)!=null?st:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(zt=k.reasoning.startedAt)!=null?zt:We((Lt=C.startedAt)!=null?Lt:C.timestamp);let Y=(yt=(K=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?K:C.delta)!=null?yt:"";if(Y&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let G=ge($,oe,String(Y));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=We((it=C.completedAt)!=null?it:C.timestamp);let oe=(ve=k.reasoning.startedAt)!=null?ve:Date.now();k.reasoning.durationMs=Math.max(0,((ie=k.reasoning.completedAt)!=null?ie:Date.now())-oe)}k.streaming=k.reasoning.status!=="complete",f(k)}else if(Ue==="reason_complete"){let $=(en=(tt=he(C,!1))!=null?tt:he(C,!0))!=null?en:`reason-${l()}`,k=D.get($);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=We((Vt=C.completedAt)!=null?Vt:C.timestamp);let oe=(Ln=k.reasoning.startedAt)!=null?Ln:Date.now();k.reasoning.durationMs=Math.max(0,((vn=k.reasoning.completedAt)!=null?vn:Date.now())-oe),k.streaming=!1,f(k)}let Y=q(C);Y&&S.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(ut=V(C,!0))!=null?ut:`tool-${l()}`,k=(Et=C.toolName)!=null?Et:C.name;if(me(k)){ce.add($);continue}let Y=se($),oe=(Ze=Y.toolCall)!=null?Ze:{id:$,status:"pending"};oe.name=k!=null?k:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:We((jt=C.startedAt)!=null?jt:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(Y.agentMetadata={executionId:(Cn=G==null?void 0:G.executionId)!=null?Cn:C.executionId,iteration:(An=G==null?void 0:G.iteration)!=null?An:C.iteration}),f(Y)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(Tr=(bn=V(C,!1))!=null?bn:V(C,!0))!=null?Tr:`tool-${l()}`;if(ce.has($))continue;let k=se($),Y=(Ct=k.toolCall)!=null?Ct:{id:$,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:We((Un=C.startedAt)!=null?Un:C.timestamp);let oe=(xt=(gr=(Or=C.text)!=null?Or:C.delta)!=null?gr:C.message)!=null?xt:"";oe&&(Y.chunks=(Ao=Y.chunks)!=null?Ao:[],Y.chunks.push(String(oe))),Y.status="running",k.toolCall=Y,k.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(Nn=k.agentMetadata)!=null?Nn:{executionId:(Er=G==null?void 0:G.executionId)!=null?Er:C.executionId,iteration:(So=G==null?void 0:G.iteration)!=null?So:C.iteration}),f(k)}else if(Ue==="tool_complete"){let $=(Qr=(zo=V(C,!1))!=null?zo:V(C,!0))!=null?Qr:`tool-${l()}`;if(ce.has($)){ce.delete($);continue}let k=se($),Y=(Nr=k.toolCall)!=null?Nr:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=We((At=C.completedAt)!=null?At:C.timestamp);let oe=(qn=C.duration)!=null?qn:C.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Ne=(zn=Y.startedAt)!=null?zn:Date.now();Y.durationMs=Math.max(0,((Pn=Y.completedAt)!=null?Pn:Date.now())-Ne)}k.toolCall=Y,k.streaming=!1;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(or=k.agentMetadata)!=null?or:{executionId:(kt=G==null?void 0:G.executionId)!=null?kt:C.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:C.iteration}),f(k);let Ee=re(C);Ee&&R.byCall.delete(Ee)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(Vn=$!=null?$:C.toolId)!=null?Vn:`local-${l()}`,Y=se(k),oe=C.toolName,G=is(oe),Ee=(Xr=Y.toolCall)!=null?Xr:{id:k,status:"pending"};Ee.name=oe,Ee.args=C.parameters,Ee.status=G?"running":"complete",Ee.chunks=(Fr=Ee.chunks)!=null?Fr:[],Ee.startedAt=(Kn=Ee.startedAt)!=null?Kn:We((Yr=C.startedAt)!=null?Yr:C.timestamp),G?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(Ht=Ee.completedAt)!=null?Ht:Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=C.executionId)!=null?sr:(In=Y.agentMetadata)==null?void 0:In.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(Y)}else if(Ue==="text_start"){if((Zr=C.toolContext)!=null&&Zr.toolId)continue;let $=C.partId;if($!==void 0&&w.current!==null&&$!==w.current){let k=g;k&&(k.streaming=!1,f(k),xe=k,g=null,A=!0)}$!==void 0&&(w.current=$)}else if(Ue==="text_end"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=g;$&&($.streaming=!1,f($),xe=$,g=null,A=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((Mr=(eo=C.id)!=null?eo:Y.stepId)!=null?Mr:`step-${l()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",et=`${Y.toolId}::${Ne}`,Rt=I.get(et);if(lt!==""&&Rt!==void 0&&Rt!==""&&Rt!==lt){let at=P.get(F(Y.toolId,Ne,Rt));at&&at.streaming!==!1&&(at.streaming=!1,f(at))}lt!==""&&I.set(et,lt);let _t=E(Y.toolId,Ne,lt,Y.executionId),un=(tn=(gt=(fr=(Gn=C.text)!=null?Gn:C.delta)!=null?fr:C.content)!=null?gt:C.chunk)!=null?tn:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),C.isComplete&&(_t.streaming=!1,f(_t));continue}let oe=C.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Ne=g;Ne&&(Ne.streaming=!1,f(Ne),xe=Ne,g=null,A=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(nn=Ye.get(oe))!=null?nn:we();oe!==void 0&&(G.partId||(G.partId=oe),Ye.set(oe,G));let Ee=(hr=(be=(to=(Jn=C.text)!=null?Jn:C.delta)!=null?to:C.content)!=null?be:C.chunk)!=null?hr:"";if(Ee){let Ne=typeof C.seq=="number"?C.seq:void 0,lt=oe!=null?oe:G.id,et=Ne!==void 0?ge(lt,Ne,String(Ee)):((ar=ae.get(G.id))!=null?ar:"")+Ee;G.rawContent=et,Z.has(G.id)||Z.set(G.id,this.createStreamParser());let Rt=Z.get(G.id),_t=et.trim().startsWith("{")||et.trim().startsWith("[");if(_t&&ae.set(G.id,et),Rt.__isPlainTextParser===!0){G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G);continue}let at=Rt.processChunk(et);if(at instanceof Promise)at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")G.content=Zt,f(G);else if(!_t&&!et.trim().startsWith("<")){let wn=g,Jt=wn&&wn.id===G.id?wn:G;Jt.id===G.id&&(Jt.content=Ne!==void 0?et:Jt.content+Ee,ae.delete(Jt.id),Z.delete(Jt.id),Jt.rawContent=void 0,f(Jt))}}).catch(()=>{G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G)});else{let ft=typeof at=="string"?at:(_=at==null?void 0:at.text)!=null?_:null;ft!==null&&ft.trim()!==""?(G.content=ft,f(G)):!_t&&!et.trim().startsWith("<")&&(G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G))}}if(C.isComplete){let Ne=(kr=(Vo=C.result)==null?void 0:Vo.response)!=null?kr:G.content;if(Ne){let lt=ae.get(G.id),et=lt!=null?lt:X(Ne);G.rawContent=et;let Rt=Z.get(G.id),_t=null,un=!1;if(Rt&&(_t=Rt.getExtractedText(),_t===null&&(_t=Fo(et)),_t===null)){let at=Rt.processChunk(et);at instanceof Promise?(un=!0,at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null){let wn=g;wn&&wn.id===G.id&&(wn.content=Zt,wn.streaming=!1,Z.delete(wn.id),ae.delete(wn.id),f(wn))}})):_t=typeof at=="string"?at:($r=at==null?void 0:at.text)!=null?$r:null}if(!un){_t!==null&&_t.trim()!==""?G.content=_t:ae.has(G.id)||(G.content=X(Ne));let at=Z.get(G.id);if(at){let ft=(Ur=at.close)==null?void 0:Ur.call(at);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Ue==="step_complete"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((br=(Lr=C.id)!=null?Lr:Y.stepId)!=null?br:"");if(Ne){let lt=N(Y.toolId,Ne);for(let[et,Rt]of P)et.startsWith(lt)&&Rt.streaming!==!1&&(Rt.streaming=!1,f(Rt));I.delete(`${Y.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(A){if(g!==null){let et=g;oe&&(et.stopReason=oe),Z.delete(et.id),ae.delete(et.id),et.streaming!==!1&&(et.streaming=!1,f(et))}let Ne=(Ss=C.result)==null?void 0:Ss.response,lt=xe;lt&&(oe&&(lt.stopReason=oe),Ne!=null?Ge(lt,Ne):(Z.delete(lt.id),ae.delete(lt.id))),xe=null;continue}let G=(Qn=C.result)==null?void 0:Qn.response,Ee=we();if(oe&&(Ee.stopReason=oe),G!=null){let Ne=Z.get(Ee.id),lt=!1,et=!1;if(Ne){let Rt=Ne.getExtractedText(),_t=ae.get(Ee.id),un=_t!=null?_t:X(G);if(Ee.rawContent=un,Rt!==null&&Rt.trim()!=="")Ee.content=Rt,lt=!0;else{let at=Fo(un);if(at!==null)Ee.content=at,lt=!0;else{let ft=Ne.processChunk(un);if(ft instanceof Promise)et=!0,ft.then(Zt=>{var wn;let Ke=typeof Zt=="string"?Zt:(wn=Zt==null?void 0:Zt.text)!=null?wn:null;if(Ke!==null&&Ke.trim()!==""){let Jt=g;Jt&&Jt.id===Ee.id&&(Jt.content=Ke,Jt.streaming=!1,Z.delete(Jt.id),ae.delete(Jt.id),f(Jt))}else{let Jt=Ne.getExtractedText(),yn=g;yn&&yn.id===Ee.id&&(Jt!==null&&Jt.trim()!==""?yn.content=Jt:ae.has(yn.id)||(yn.content=X(G)),yn.streaming=!1,Z.delete(yn.id),ae.delete(yn.id),f(yn))}});else{let Zt=typeof ft=="string"?ft:(Xn=ft==null?void 0:ft.text)!=null?Xn:null;if(Zt!==null&&Zt.trim()!=="")Ee.content=Zt,lt=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Ee.content=Ke,lt=!0)}}}}}if(!et){if(!Ee.rawContent){let Rt=ae.get(Ee.id);Ee.rawContent=Rt!=null?Rt:X(G)}if(!lt&&!ae.has(Ee.id)&&(Ee.content=X(G)),Ne){let Rt=(yr=Ne.close)==null?void 0:yr.call(Ne);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}}else Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}else if(Ue==="flow_complete"){let $=(xr=C.result)==null?void 0:xr.response;if(A){if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}}else if($!=null){let k=we(),Y=ae.get(k.id),oe=Y!=null?Y:X($);k.rawContent=oe;let G=X($),Ee=Z.get(k.id);if(Ee){let et=Fo(oe);if(et!==null)G=et;else{let Rt=Ee.processChunk(oe);Rt instanceof Promise&&Rt.then(un=>{var ft;let at=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;at!==null&&(k.content=at,k.streaming=!1,f(k))});let _t=Ee.getExtractedText();_t!==null&&(G=_t)}}Z.delete(k.id),ae.delete(k.id);let Ne=G!==k.content,lt=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||lt)&&f(k)}else if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")te={executionId:C.executionId,agentId:(To=C.agentId)!=null?To:"virtual",agentName:(jr=C.agentName)!=null?jr:"",status:"running",currentIteration:0,maxTurns:(Sn=C.maxTurns)!=null?Sn:1,startedAt:We(C.startedAt)};else if(Ue==="agent_iteration_start"){if(te&&(te.currentIteration=C.iteration),On==="separate"&&C.iteration>1){let $=g;$&&($.streaming=!1,f($),ze.set(C.iteration-1,$),g=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=we();$.content+=(Pr=C.delta)!=null?Pr:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:te==null?void 0:te.agentName},v=$,f($)}else if(C.contentType==="thinking"){let $=(Ko=C.turnId)!=null?Ko:`agent-think-${C.iteration}`,k=ke($);k.reasoning=(Eo=k.reasoning)!=null?Eo:{id:$,status:"streaming",chunks:[]},k.reasoning.chunks.push((Go=C.delta)!=null?Go:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(k)}else if(C.contentType==="tool_input"){let $=(ya=C.toolCallId)!=null?ya:R.lastId;if($){let k=M.get($);k!=null&&k.toolCall&&(k.toolCall.chunks=(Jo=k.toolCall.chunks)!=null?Jo:[],k.toolCall.chunks.push((xa=C.delta)!=null?xa:""),f(k))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let oe=D.get($);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=We(C.completedAt);let G=(Qo=oe.reasoning.startedAt)!=null?Qo:Date.now();oe.reasoning.durationMs=Math.max(0,((bt=oe.reasoning.completedAt)!=null?bt:Date.now())-G),oe.streaming=!1,f(oe)}}let k=C.stopReason,Y=g!=null?g:v;if(k&&Y!==null){let oe=C.turnId;(!oe||((Ts=Y.agentMetadata)==null?void 0:Ts.turnId)===oe)&&(Y.stopReason=k,f(Y))}}else if(Ue==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let $=(ir=C.toolCallId)!=null?ir:`agent-tool-${l()}`;Re(re(C),$);let k=se($),Y=(Fn=k.toolCall)!=null?Fn:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(wa=(va=C.toolName)!=null?va:C.name)!=null?wa:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=We((Xo=C.startedAt)!=null?Xo:C.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(k)}else if(Ue==="agent_tool_delta"){let $=(qr=C.toolCallId)!=null?qr:R.lastId;if($){let k=(Es=M.get($))!=null?Es:se($);k.toolCall&&(k.toolCall.chunks=(no=k.toolCall.chunks)!=null?no:[],k.toolCall.chunks.push((Ms=C.delta)!=null?Ms:""),k.toolCall.status="running",k.streaming=!0,f(k))}}else if(Ue==="agent_tool_complete"){let $=(ks=C.toolCallId)!=null?ks:R.lastId;if($){let k=(Ls=M.get($))!=null?Ls:se($);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=We((Ps=C.completedAt)!=null?Ps:C.timestamp),k.streaming=!1,f(k);let Y=re(C);Y&&R.byCall.delete(Y)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],k=[];for(let Y of $){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Ee=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,lt="";if(G==="media"){let et=typeof oe.data=="string"?oe.data:void 0;if(!et)continue;lt=Ee.length>0?Ee:"application/octet-stream",Ne=`data:${lt};base64,${et}`}else if(G==="image-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else if(G==="file-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else continue;if(Ne)if(G==="image-url"||lt.startsWith("image/"))k.push({type:"image",image:Ne,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:lt});else if(lt.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:lt});else{let et=lt||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:et,filename:Mf(et)})}}if(k.length>0){let Y=l(),oe=C.toolCallId,Ee={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Ee);let Ne=g;Ne&&(Ne.streaming=!1,f(Ne)),g=null,y.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:$,role:"assistant",content:(_n=C.reflection)!=null?_n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Yo=C.reflection)!=null?Yo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(k)}else if(Ue==="agent_complete"){te&&(te.status=C.success?"complete":"error",te.completedAt=We(C.completedAt),te.stopReason=C.stopReason);let $=g;$&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(Rr=(Ir=C.error)==null?void 0:Ir.message)!=null?Rr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ca=te==null?void 0:te.agentId)!=null?Ca:"virtual",executionId:(Ws=(Rs=C.executionId)!=null?Rs:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Mo=C.toolName)!=null?Mo:"",toolType:C.toolType,description:(Sa=C.description)!=null?Sa:`Execute ${(Aa=C.toolName)!=null?Aa:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(Ta=C.approvalId)!=null?Ta:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ea=te==null?void 0:te.agentId)!=null?Ea:"virtual",executionId:(ko=(Oi=C.executionId)!=null?Oi:te==null?void 0:te.executionId)!=null?ko:"",toolName:(ro=C.toolName)!=null?ro:"",toolType:C.toolType,description:(Hs=C.description)!=null?Hs:`Execute ${(Ma=C.toolName)!=null?Ma:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(oo=C.decision)!=null?oo:"approved",agentId:(ka=te==null?void 0:te.agentId)!=null?ka:"virtual",executionId:(so=(Bs=C.executionId)!=null?Bs:te==null?void 0:te.executionId)!=null?so:"",toolName:(Ds=C.toolName)!=null?Ds:"",description:(La=C.description)!=null?La:"",resolvedAt:Date.now()}};f(Y)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,k=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:k,artifactType:$,title:Y,component:typeof C.component=="string"?C.component:void 0}),le.set(k,{markdown:"",title:Y}),!ne.has(k)){ne.add(k);let oe={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:$,status:"streaming"}})};Q.set(k,oe),f(oe)}}else if(Ue==="artifact_delta"){let $=String(C.id),k=typeof C.delta=="string"?C.delta:String((zr=C.delta)!=null?zr:"");n({type:"artifact_delta",id:$,artDelta:k});let Y=le.get($);Y&&(Y.markdown+=k)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let k=Q.get($);if(k){k.streaming=!1;try{let Y=JSON.parse((Pa=k.rawContent)!=null?Pa:"{}");if(Y.props){Y.props.status="complete";let oe=le.get($);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete($),f(k),Q.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let k=String((ao=$.id)!=null?ao:`msg-${l()}`),Y=$.role,G={id:k,role:Y==="user"?"user":Y==="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(f(G),G.rawContent)try{let Ee=JSON.parse(G.rawContent),Ne=(Bt=Ee==null?void 0:Ee.props)==null?void 0:Bt.artifactId;typeof Ne=="string"&&ne.add(Ne)}catch{}g=null,y.current=null,Z.delete(k),ae.delete(k)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let k=(Zo=C.message)!=null?Zo:C.error;k!=null&&k!==""&&($=new Error(String(k)))}else if(Ue==="step_error"||Ue==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?$=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&($=new Error(String((es=k.message)!=null?es:k)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let k=g;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:W,value:de}=await s.read();if(W)break;a+=o.decode(de,{stream:!0});let De=a.split(`
9
+ `).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return i[1]}return null};return{getExtractedText:()=>e,processChunk:async r=>{if(r.length<=t)return e!==null?{text:e,raw:r}:null;let s=r.trim();if(!s.startsWith("{")&&!s.startsWith("["))return null;let o=n(r);return o!==null&&(e=o),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Fo=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},el=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},tl=()=>{var t;let e=Sf();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},nl=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let s=Lu(n,Pu|Iu);s&&typeof s=="object"&&(s.component&&typeof s.component=="string"?e=typeof s.text=="string"?Ua(s.text):"":s.type==="init"&&s.form?e="":typeof s.text=="string"&&(e=Ua(s.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},Tf=e=>{let t=null,n=0,s=e||(o=>{if(!o||typeof o!="object")return null;let a=i=>typeof i=="string"?Ua(i):null;if(o.component&&typeof o.component=="string")return typeof o.text=="string"?Ua(o.text):"";if(o.type==="init"&&o.form)return"";if(o.action)switch(o.action){case"nav_then_click":return a(o.on_load_text)||a(o.text)||null;case"message":case"message_and_click":case"checkout":return a(o.text)||null;default:return a(o.text)||a(o.display_text)||a(o.message)||null}return a(o.text)||a(o.display_text)||a(o.message)||a(o.content)||null});return{getExtractedText:()=>t,processChunk:o=>{let a=o.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(o.length<=n)return t!==null?{text:t,raw:o}:null;try{let i=Lu(o,Pu|Iu),d=s(i);d!==null&&(t=d)}catch{}return n=o.length,{text:t||"",raw:o}},close:()=>{}}},rl=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var Va=class{constructor(t,n=50){this.nextExpectedSeq=null;this.buffer=new Map;this.flushTimer=null;this.emitter=t,this.gapTimeoutMs=n}push(t,n){var o,a,i;let r=(i=(o=n==null?void 0:n.seq)!=null?o:n==null?void 0:n.sequenceIndex)!=null?i:(a=n==null?void 0:n.agentContext)==null?void 0:a.seq;if(r==null){this.buffer.size>0&&this.flushAll(),this.emitter(t,n);return}if(this.nextExpectedSeq===null&&(this.nextExpectedSeq=1),r===this.nextExpectedSeq){this.emitter(t,n),this.nextExpectedSeq=r+1,this.drainConsecutive();return}if(r<this.nextExpectedSeq){this.emitter(t,n);return}let s=this.buffer.get(r);s!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${s.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(s.payloadType,s.payload)),this.buffer.set(r,{payloadType:t,payload:n,seq:r}),this.startGapTimer()}drainConsecutive(){for(;this.buffer.has(this.nextExpectedSeq);){let t=this.buffer.get(this.nextExpectedSeq);this.buffer.delete(this.nextExpectedSeq),this.emitter(t.payloadType,t.payload),this.nextExpectedSeq++}this.buffer.size===0&&this.clearGapTimer()}startGapTimer(){this.flushTimer===null&&(this.flushTimer=setTimeout(()=>{this.flushAll()},this.gapTimeoutMs))}clearGapTimer(){this.flushTimer!==null&&(clearTimeout(this.flushTimer),this.flushTimer=null)}flushAll(){if(this.clearGapTimer(),this.buffer.size===0)return;let t=[...this.buffer.entries()].sort((n,r)=>n[0]-r[0]);for(let[n,r]of t)this.buffer.delete(n),this.emitter(r.payloadType,r.payload);t.length>0&&(this.nextExpectedSeq=t[t.length-1][0]+1)}destroy(){this.clearGapTimer(),this.buffer.clear()}flushPending(){this.flushAll()}};var Ef="https://api.runtype.com/v1/dispatch",Ka="https://api.runtype.com";function Mf(e){var o,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let s=t.indexOf("/");if(s>0){let i=(a=(o=t.slice(s+1).split(";")[0])==null?void 0:o.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var ol=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 kf(e){switch(e){case"json":return nl;case"regex-json":return tl;case"xml":return rl;default:return el}}var Hu=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function Lf(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let s=Hu(n);if(!Hu(r))return e;if(!s||r===n||r.startsWith(n))return t;let a=Fo(e);return Fo(t)!==null&&a===null?t:e}var ps=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,s,o;this.apiUrl=(n=t.apiUrl)!=null?n:Ef,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:kf(t.parserType),this.contextProviders=(s=t.contextProviders)!=null?s:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((o=t.webmcp)==null?void 0:o.enabled)===!0?new qs(t.webmcp):null}updateConfig(t){this.config=t}setSSEEventCallback(t){this.onSSEEvent=t}setWebMcpConfirmHandler(t){var n;(n=this.webMcpBridge)==null||n.setConfirmHandler(t)}isWebMcpOperational(){var t;return((t=this.webMcpBridge)==null?void 0:t.isOperational())===!0}executeWebMcpToolCall(t,n,r){return this.webMcpBridge?this.webMcpBridge.executeToolCall(t,n,r):null}getSSEEventCallback(){return this.onSSEEvent}isClientTokenMode(){return!!this.config.clientToken}isAgentMode(){return!!this.config.agent}getClientApiUrl(t){var r;return`${((r=this.config.apiUrl)==null?void 0:r.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/${t}`}getClientSession(){return this.clientSession}async initSession(){var t,n;if(!this.isClientTokenMode())throw new Error("initSession() only available in client token mode");if(this.clientSession&&new Date<this.clientSession.expiresAt)return this.clientSession;if(this.sessionInitPromise)return this.sessionInitPromise;this.sessionInitPromise=this._doInitSession();try{let r=await this.sessionInitPromise;return this.clientSession=r,this.resetClientToolsFingerprint(),(n=(t=this.config).onSessionInit)==null||n.call(t,r),r}finally{this.sessionInitPromise=null}}async _doInitSession(){var o,a;let t=((a=(o=this.config).getStoredSessionId)==null?void 0:a.call(o))||null,n={token:this.config.clientToken,...this.config.flowId&&{flowId:this.config.flowId},...t&&{sessionId:t}},r=await fetch(this.getClientApiUrl("init"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){let i=await r.json().catch(()=>({error:"Session initialization failed"}));throw r.status===401?new Error(`Invalid client token: ${i.hint||i.error}`):r.status===403?new Error(`Origin not allowed: ${i.hint||i.error}`):new Error(i.error||"Failed to initialize session")}let s=await r.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 n;return`${((n=this.config.apiUrl)==null?void 0:n.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let s={...t,...this.config.clientToken&&{token:this.config.clientToken}},o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(s)});if(!o.ok){let d=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var s,o,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(o=(s=this.config).onSessionExpired)==null||o.call(s);let P=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:P}),P}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([P])=>P!=="sessionId"&&P!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(ol).map(P=>{var I,S,R;return{id:P.id,role:P.role,content:(R=(S=(I=P.contentParts)!=null?I:P.llmContent)!=null?S:P.rawContent)!=null?R:P.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}},f=l.clientTools,g=!!(f&&f.length>0),v=g?pu(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,A=!1,D=null,M;for(let P=0;;P++){let S={...u,...g&&(A||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",S),M=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(S),signal:r.signal}),M.status===409&&P===0&&g){let R=await M.json().catch(()=>null);if((R==null?void 0:R.error)==="client_tools_resend_required"){A=!0,this.lastSentClientToolsFingerprint=null;continue}D=R!=null?R:{error:"Chat request failed"}}break}if(!M.ok){let P=D!=null?D:await M.json().catch(()=>({error:"Chat request failed"}));if(M.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let S=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:S}),S}if(M.status===429){let S=new Error(P.hint||"Message limit reached for this session.");throw n({type:"error",error:S}),S}let I=new Error(P.error||"Failed to send message");throw n({type:"error",error:I}),I}if(!M.body){let P=new Error("No response body received");throw n({type:"error",error:P}),P}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(M.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}catch(d){let l=d instanceof Error?d:new Error(String(d));throw!l.message.includes("Session expired")&&!l.message.includes("Message limit")&&n({type:"error",error:l}),l}}async dispatchProxy(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let s=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",s);let o={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();o={...o,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal},s)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:o,body:JSON.stringify(s),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){n({type:"status",status:"connected"});try{await this.streamResponse(t,n,r)}finally{n({type:"status",status:"idle"})}}async resolveApproval(t,n){var a;let s=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||Ka}/v1/agents/${t.agentId}/approve`,o={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(o,await this.getHeaders()),fetch(s,{method:"POST",headers:o,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let s=this.isClientTokenMode(),o=s?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||Ka}/resume`,a;s&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(o,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var o,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(ol).filter(i=>i.role==="user"||i.role==="assistant"||i.role==="system").filter(i=>!i.variant||i.variant==="assistant").sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),r={agent:this.config.agent,messages:n,options:{streamResponse:!0,recordMode:"virtual",...this.config.agentOptions}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}return r}async buildPayload(t){var o,a;let r={messages:t.slice().filter(ol).sort((i,d)=>{let l=new Date(i.createdAt).getTime(),p=new Date(d.createdAt).getTime();return l-p}).map(i=>{var d,l,p;return{role:i.role,content:(p=(l=(d=i.contentParts)!=null?d:i.llmContent)!=null?l:i.rawContent)!=null?p:i.content,createdAt:i.createdAt}}),...this.config.flowId&&{flowId:this.config.flowId}},s=[...$a(this.config),...(a=await((o=this.webMcpBridge)==null?void 0:o.snapshotForDispatch()))!=null?a:[]];if(s.length>0&&(r.clientTools=s),this.contextProviders.length){let i={};await Promise.all(this.contextProviders.map(async d=>{try{let l=await d({messages:t,config:this.config});l&&typeof l=="object"&&Object.assign(i,l)}catch(l){typeof console!="undefined"&&console.warn("[AgentWidget] Context provider failed:",l)}})),Object.keys(i).length&&(r.context=i)}if(this.requestMiddleware)try{let i=await this.requestMiddleware({payload:{...r},config:this.config});if(i&&typeof i=="object"){let d=i;return r.clientTools!==void 0&&!("clientTools"in d)&&(d.clientTools=r.clientTools),d}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] Request middleware error:",i)}return r}async handleCustomSSEEvent(t,n,r,s,o,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:o(),...p!==void 0&&{partId:p}};return r.current=u,s(u),u},l=p=>r.current?r.current:d(p);if(i.text!==void 0){i.partId!==void 0&&a.current!==null&&i.partId!==a.current&&(r.current&&(r.current.streaming=!1,s(r.current)),d(i.partId)),i.partId!==void 0&&(a.current=i.partId);let p=l(i.partId);i.partId!==void 0&&!p.partId&&(p.partId=i.partId),p.content+=i.text,s(p)}return i.done&&(r.current&&(r.current.streaming=!1,s(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Wt,ln,nr,Sr;let s=t.getReader(),o=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=W=>{let de=W.reasoning?{...W.reasoning,chunks:[...W.reasoning.chunks]}:void 0,De=W.toolCall?{...W.toolCall,chunks:W.toolCall.chunks?[...W.toolCall.chunks]:void 0}:void 0,Je=W.tools?W.tools.map(Fe=>({...Fe,chunks:Fe.chunks?[...Fe.chunks]:void 0})):void 0;return{...W,reasoning:de,toolCall:De,tools:Je}},u=W=>{if(W.role!=="assistant"||W.variant)return!0;let de=Array.isArray(W.contentParts)&&W.contentParts.length>0,De=typeof W.rawContent=="string"&&W.rawContent.trim()!=="";return typeof W.content=="string"&&W.content.trim()!==""||de||De||!!W.stopReason},f=W=>{u(W)&&n({type:"message",message:p(W)})},g=null,v=null,y={current:null},w={current:null},A=!1,D=new Map,M=new Map,P=new Map,I=new Map,S={lastId:null,byStep:new Map},R={lastId:null,byCall:new Map},F=(W,de,De="")=>`${W}::${de}::${De}`,N=(W,de)=>`${W}::${de}::`,E=(W,de,De,Je)=>{let Fe=F(W,de,De),$e=P.get(Fe);if($e)return $e;let st=De?`-${De}`:"",Lt={id:`nested-${W}-${de}${st}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...De?{partId:De}:{},agentMetadata:{executionId:Je,parentToolId:W,parentStepId:de}};return P.set(Fe,Lt),f(Lt),Lt},U=W=>{if(W==null)return null;try{return String(W)}catch{return null}},q=W=>{var de,De,Je,Fe,$e;return U(($e=(Fe=(Je=(De=(de=W.stepId)!=null?de:W.step_id)!=null?De:W.step)!=null?Je:W.parentId)!=null?Fe:W.flowStepId)!=null?$e:W.flow_step_id)},re=W=>{var de,De,Je,Fe,$e,st,Lt;return U((Lt=(st=($e=(Fe=(Je=(De=(de=W.callId)!=null?de:W.call_id)!=null?De:W.requestId)!=null?Je:W.request_id)!=null?Fe:W.toolCallId)!=null?$e:W.tool_call_id)!=null?st:W.stepId)!=null?Lt:W.step_id)},Me=r,qe=!1,we=()=>{if(g)return g;let W;return!qe&&Me?(W=Me,qe=!0):Me&&w.current?W=`${Me}_${w.current}`:W=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:W,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Ie=(W,de)=>{S.lastId=de,W&&S.byStep.set(W,de)},he=(W,de)=>{var $e;let De=($e=W.reasoningId)!=null?$e:W.id,Je=q(W);if(De){let st=String(De);return Ie(Je,st),st}if(Je){let st=S.byStep.get(Je);if(st)return S.lastId=st,st}if(S.lastId&&!de)return S.lastId;if(!de)return null;let Fe=`reason-${l()}`;return Ie(Je,Fe),Fe},ke=W=>{let de=D.get(W);if(de)return de;let De={id:`reason-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:W,status:"streaming",chunks:[]}};return D.set(W,De),f(De),De},Re=(W,de)=>{R.lastId=de,W&&R.byCall.set(W,de)},ce=new Set,Q=new Map,ne=new Set,le=new Map,me=W=>{if(!W)return!1;let de=W.replace(/_+/g,"_").replace(/^_|_$/g,"");return de==="emit_artifact_markdown"||de==="emit_artifact_component"},V=(W,de)=>{var $e;let De=($e=W.toolId)!=null?$e:W.id,Je=re(W);if(De){let st=String(De);return Re(Je,st),st}if(Je){let st=R.byCall.get(Je);if(st)return R.lastId=st,st}if(R.lastId&&!de)return R.lastId;if(!de)return null;let Fe=`tool-${l()}`;return Re(Je,Fe),Fe},se=W=>{let de=M.get(W);if(de)return de;let De={id:`tool-${W}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:W,status:"pending"}};return M.set(W,De),f(De),De},We=W=>{if(typeof W=="number"&&Number.isFinite(W))return W;if(typeof W=="string"){let de=Number(W);if(!Number.isNaN(de)&&Number.isFinite(de))return de;let De=Date.parse(W);if(!Number.isNaN(De))return De}return Date.now()},X=W=>{if(typeof W=="string")return W;if(W==null)return"";try{return JSON.stringify(W)}catch{return String(W)}},Z=new Map,ae=new Map,Ce=new Map,Ye=new Map,xe=null,ge=(W,de,De)=>{var Lt;let Je=Ce.get(W);Je||(Je=[],Ce.set(W,Je));let Fe=0,$e=Je.length;for(;Fe<$e;){let zt=Fe+$e>>>1;Je[zt].seq<de?Fe=zt+1:$e=zt}((Lt=Je[Fe])==null?void 0:Lt.seq)===de?Je[Fe]={seq:de,text:De}:Je.splice(Fe,0,{seq:de,text:De});let st="";for(let zt=0;zt<Je.length;zt++)st+=Je[zt].text;return st},Ge=(W,de)=>{let De=X(de),Je=ae.get(W.id),Fe=Lf(Je,De);W.rawContent=Fe;let $e=Z.get(W.id),st=yt=>{var ve;let it=(ve=W.content)!=null?ve:"";yt.trim()!==""&&(it.trim().length===0||yt.startsWith(it)||yt.trimStart().startsWith(it.trim()))&&(W.content=yt)},Lt=()=>{var yt;if($e){let it=(yt=$e.close)==null?void 0:yt.call($e);it instanceof Promise&&it.catch(()=>{})}Z.delete(W.id),ae.delete(W.id),W.streaming=!1,f(W)};if(!$e){st(De),Lt();return}let zt=Fo(Fe);if(zt!==null&&zt.trim()!==""){st(zt),Lt();return}let Yt=yt=>{var ie;let it=typeof yt=="string"?yt:(ie=yt==null?void 0:yt.text)!=null?ie:null;if(it!==null&&it.trim()!=="")return it;let ve=$e.getExtractedText();return ve!==null&&ve.trim()!==""?ve:De},K;try{K=$e.processChunk(Fe)}catch{st(De),Lt();return}if(K instanceof Promise){K.then(yt=>{st(Yt(yt)),Lt()}).catch(()=>{st(De),Lt()});return}st(Yt(K)),Lt()},Be=[],z=!1,pe,rt=()=>{z||(z=!0,queueMicrotask(()=>{z=!1,pe()}))},Tt=new Va((W,de)=>{Be.push({payloadType:W,payload:de}),rt()}),te=null,ze=new Map,On=(Wt=this.config.iterationDisplay)!=null?Wt:"separate";for(pe=()=>{var W,de,De,Je,Fe,$e,st,Lt,zt,Yt,K,yt,it,ve,ie,tt,en,Vt,Ln,vn,ut,Et,Ze,jt,cn,Cn,An,bn,Tr,Ct,Un,jn,Or,gr,xt,Ao,Er,So,Nn,zo,Qr,Nr,At,qn,zn,Pn,kt,rr,or,Vn,Xr,Fr,Yr,Kn,Ht,In,sr,Zr,_r,eo,Mr,Gn,fr,gt,tn,nn,Jn,to,be,hr,ar,_,Vo,kr,$r,Ur,Lr,br,Ss,Qn,Xn,yr,xr,To,jr,Sn,Pr,Ko,Eo,Go,ya,Jo,xa,Qo,bt,Ts,ir,Fn,va,wa,Xo,qr,Es,no,Ms,ks,Ls,Ps,_n,Yo,Ir,Rr,Is,Ca,Rs,Ws,Mo,Aa,Sa,Ta,Ea,Oi,ko,ro,Ma,Hs,oo,ka,Bs,so,Ds,La,zr,Pa,ao,Bt,Zo,es;for(let Lo=0;Lo<Be.length;Lo++){let Ue=Be[Lo].payloadType,C=Be[Lo].payload;if(Ue==="reason_start"){let $=(W=he(C,!0))!=null?W:`reason-${l()}`,k=ke($);k.reasoning=(de=k.reasoning)!=null?de:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(Je=k.reasoning.startedAt)!=null?Je:We((De=C.startedAt)!=null?De:C.timestamp),k.reasoning.completedAt=void 0,k.reasoning.durationMs=void 0,k.streaming=!0,k.reasoning.status="streaming",f(k)}else if(Ue==="reason_delta"||Ue==="reason_chunk"){let $=($e=(Fe=he(C,!1))!=null?Fe:he(C,!0))!=null?$e:`reason-${l()}`,k=ke($);k.reasoning=(st=k.reasoning)!=null?st:{id:$,status:"streaming",chunks:[]},k.reasoning.startedAt=(zt=k.reasoning.startedAt)!=null?zt:We((Lt=C.startedAt)!=null?Lt:C.timestamp);let Y=(yt=(K=(Yt=C.reasoningText)!=null?Yt:C.text)!=null?K:C.delta)!=null?yt:"";if(Y&&C.hidden!==!0){let oe=typeof C.sequenceIndex=="number"?C.sequenceIndex:void 0;if(oe!==void 0){let G=ge($,oe,String(Y));k.reasoning.chunks=[G]}else k.reasoning.chunks.push(String(Y))}if(k.reasoning.status=C.done?"complete":"streaming",C.done){k.reasoning.completedAt=We((it=C.completedAt)!=null?it:C.timestamp);let oe=(ve=k.reasoning.startedAt)!=null?ve:Date.now();k.reasoning.durationMs=Math.max(0,((ie=k.reasoning.completedAt)!=null?ie:Date.now())-oe)}k.streaming=k.reasoning.status!=="complete",f(k)}else if(Ue==="reason_complete"){let $=(en=(tt=he(C,!1))!=null?tt:he(C,!0))!=null?en:`reason-${l()}`,k=D.get($);if(k!=null&&k.reasoning){k.reasoning.status="complete",k.reasoning.completedAt=We((Vt=C.completedAt)!=null?Vt:C.timestamp);let oe=(Ln=k.reasoning.startedAt)!=null?Ln:Date.now();k.reasoning.durationMs=Math.max(0,((vn=k.reasoning.completedAt)!=null?vn:Date.now())-oe),k.streaming=!1,f(k)}let Y=q(C);Y&&S.byStep.delete(Y)}else if(Ue==="tool_start"){let $=(ut=V(C,!0))!=null?ut:`tool-${l()}`,k=(Et=C.toolName)!=null?Et:C.name;if(me(k)){ce.add($);continue}let Y=se($),oe=(Ze=Y.toolCall)!=null?Ze:{id:$,status:"pending"};oe.name=k!=null?k:oe.name,oe.status="running",C.args!==void 0?oe.args=C.args:C.parameters!==void 0&&(oe.args=C.parameters),oe.startedAt=(cn=oe.startedAt)!=null?cn:We((jt=C.startedAt)!=null?jt:C.timestamp),oe.completedAt=void 0,oe.durationMs=void 0,Y.toolCall=oe,Y.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(Y.agentMetadata={executionId:(Cn=G==null?void 0:G.executionId)!=null?Cn:C.executionId,iteration:(An=G==null?void 0:G.iteration)!=null?An:C.iteration}),f(Y)}else if(Ue==="tool_chunk"||Ue==="tool_delta"){let $=(Tr=(bn=V(C,!1))!=null?bn:V(C,!0))!=null?Tr:`tool-${l()}`;if(ce.has($))continue;let k=se($),Y=(Ct=k.toolCall)!=null?Ct:{id:$,status:"running"};Y.startedAt=(jn=Y.startedAt)!=null?jn:We((Un=C.startedAt)!=null?Un:C.timestamp);let oe=(xt=(gr=(Or=C.text)!=null?Or:C.delta)!=null?gr:C.message)!=null?xt:"";oe&&(Y.chunks=(Ao=Y.chunks)!=null?Ao:[],Y.chunks.push(String(oe))),Y.status="running",k.toolCall=Y,k.streaming=!0;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(Nn=k.agentMetadata)!=null?Nn:{executionId:(Er=G==null?void 0:G.executionId)!=null?Er:C.executionId,iteration:(So=G==null?void 0:G.iteration)!=null?So:C.iteration}),f(k)}else if(Ue==="tool_complete"){let $=(Qr=(zo=V(C,!1))!=null?zo:V(C,!0))!=null?Qr:`tool-${l()}`;if(ce.has($)){ce.delete($);continue}let k=se($),Y=(Nr=k.toolCall)!=null?Nr:{id:$,status:"running"};Y.status="complete",C.result!==void 0&&(Y.result=C.result),typeof C.duration=="number"&&(Y.duration=C.duration),Y.completedAt=We((At=C.completedAt)!=null?At:C.timestamp);let oe=(qn=C.duration)!=null?qn:C.executionTime;if(typeof oe=="number")Y.durationMs=oe;else{let Ne=(zn=Y.startedAt)!=null?zn:Date.now();Y.durationMs=Math.max(0,((Pn=Y.completedAt)!=null?Pn:Date.now())-Ne)}k.toolCall=Y,k.streaming=!1;let G=C.agentContext;(G||C.executionId)&&(k.agentMetadata=(or=k.agentMetadata)!=null?or:{executionId:(kt=G==null?void 0:G.executionId)!=null?kt:C.executionId,iteration:(rr=G==null?void 0:G.iteration)!=null?rr:C.iteration}),f(k);let Ee=re(C);Ee&&R.byCall.delete(Ee)}else if(Ue==="step_await"&&C.awaitReason==="local_tool_required"&&C.toolName){let $=typeof C.toolCallId=="string"&&C.toolCallId.length>0?C.toolCallId:void 0,k=(Vn=$!=null?$:C.toolId)!=null?Vn:`local-${l()}`,Y=se(k),oe=C.toolName,G=is(oe),Ee=(Xr=Y.toolCall)!=null?Xr:{id:k,status:"pending"};Ee.name=oe,Ee.args=C.parameters,Ee.status=G?"running":"complete",Ee.chunks=(Fr=Ee.chunks)!=null?Fr:[],Ee.startedAt=(Kn=Ee.startedAt)!=null?Kn:We((Yr=C.startedAt)!=null?Yr:C.timestamp),G?(Ee.completedAt=void 0,Ee.duration=void 0,Ee.durationMs=void 0):Ee.completedAt=(Ht=Ee.completedAt)!=null?Ht:Ee.startedAt,Y.toolCall=Ee,Y.streaming=!1,Y.agentMetadata={...Y.agentMetadata,executionId:(sr=C.executionId)!=null?sr:(In=Y.agentMetadata)==null?void 0:In.executionId,awaitingLocalTool:!0,...$?{webMcpToolCallId:$}:{}},f(Y)}else if(Ue==="text_start"){if((Zr=C.toolContext)!=null&&Zr.toolId)continue;let $=C.partId;if($!==void 0&&w.current!==null&&$!==w.current){let k=g;k&&(k.streaming=!1,f(k),xe=k,g=null,A=!0)}$!==void 0&&(w.current=$)}else if(Ue==="text_end"){if((_r=C.toolContext)!=null&&_r.toolId)continue;let $=g;$&&($.streaming=!1,f($),xe=$,g=null,A=!0)}else if(Ue==="step_chunk"||Ue==="step_delta"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((Mr=(eo=C.id)!=null?eo:Y.stepId)!=null?Mr:`step-${l()}`),lt=C.partId!==void 0&&C.partId!==null?String(C.partId):"",et=`${Y.toolId}::${Ne}`,Rt=I.get(et);if(lt!==""&&Rt!==void 0&&Rt!==""&&Rt!==lt){let at=P.get(F(Y.toolId,Ne,Rt));at&&at.streaming!==!1&&(at.streaming=!1,f(at))}lt!==""&&I.set(et,lt);let _t=E(Y.toolId,Ne,lt,Y.executionId),un=(tn=(gt=(fr=(Gn=C.text)!=null?Gn:C.delta)!=null?fr:C.content)!=null?gt:C.chunk)!=null?tn:"";un&&(_t.content+=String(un),_t.streaming=!0,f(_t)),C.isComplete&&(_t.streaming=!1,f(_t));continue}let oe=C.partId;if(oe!==void 0&&w.current!==null&&oe!==w.current){let Ne=g;Ne&&(Ne.streaming=!1,f(Ne),xe=Ne,g=null,A=!0)}oe!==void 0&&(w.current=oe);let G=oe!==void 0&&(nn=Ye.get(oe))!=null?nn:we();oe!==void 0&&(G.partId||(G.partId=oe),Ye.set(oe,G));let Ee=(hr=(be=(to=(Jn=C.text)!=null?Jn:C.delta)!=null?to:C.content)!=null?be:C.chunk)!=null?hr:"";if(Ee){let Ne=typeof C.seq=="number"?C.seq:void 0,lt=oe!=null?oe:G.id,et=Ne!==void 0?ge(lt,Ne,String(Ee)):((ar=ae.get(G.id))!=null?ar:"")+Ee;G.rawContent=et,Z.has(G.id)||Z.set(G.id,this.createStreamParser());let Rt=Z.get(G.id),_t=et.trim().startsWith("{")||et.trim().startsWith("[");if(_t&&ae.set(G.id,et),Rt.__isPlainTextParser===!0){G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G);continue}let at=Rt.processChunk(et);if(at instanceof Promise)at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null&&Zt.trim()!=="")G.content=Zt,f(G);else if(!_t&&!et.trim().startsWith("<")){let wn=g,Jt=wn&&wn.id===G.id?wn:G;Jt.id===G.id&&(Jt.content=Ne!==void 0?et:Jt.content+Ee,ae.delete(Jt.id),Z.delete(Jt.id),Jt.rawContent=void 0,f(Jt))}}).catch(()=>{G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G)});else{let ft=typeof at=="string"?at:(_=at==null?void 0:at.text)!=null?_:null;ft!==null&&ft.trim()!==""?(G.content=ft,f(G)):!_t&&!et.trim().startsWith("<")&&(G.content=Ne!==void 0?et:G.content+Ee,ae.delete(G.id),Z.delete(G.id),G.rawContent=void 0,f(G))}}if(C.isComplete){let Ne=(kr=(Vo=C.result)==null?void 0:Vo.response)!=null?kr:G.content;if(Ne){let lt=ae.get(G.id),et=lt!=null?lt:X(Ne);G.rawContent=et;let Rt=Z.get(G.id),_t=null,un=!1;if(Rt&&(_t=Rt.getExtractedText(),_t===null&&(_t=Fo(et)),_t===null)){let at=Rt.processChunk(et);at instanceof Promise?(un=!0,at.then(ft=>{var Ke;let Zt=typeof ft=="string"?ft:(Ke=ft==null?void 0:ft.text)!=null?Ke:null;if(Zt!==null){let wn=g;wn&&wn.id===G.id&&(wn.content=Zt,wn.streaming=!1,Z.delete(wn.id),ae.delete(wn.id),f(wn))}})):_t=typeof at=="string"?at:($r=at==null?void 0:at.text)!=null?$r:null}if(!un){_t!==null&&_t.trim()!==""?G.content=_t:ae.has(G.id)||(G.content=X(Ne));let at=Z.get(G.id);if(at){let ft=(Ur=at.close)==null?void 0:Ur.call(at);ft instanceof Promise&&ft.catch(()=>{}),Z.delete(G.id)}ae.delete(G.id),G.streaming=!1,f(G)}}}}else if(Ue==="step_complete"){let $=C.stepType,k=C.executionType;if($==="tool"||k==="context")continue;let Y=C.toolContext;if(Y!=null&&Y.toolId){let Ne=String((br=(Lr=C.id)!=null?Lr:Y.stepId)!=null?br:"");if(Ne){let lt=N(Y.toolId,Ne);for(let[et,Rt]of P)et.startsWith(lt)&&Rt.streaming!==!1&&(Rt.streaming=!1,f(Rt));I.delete(`${Y.toolId}::${Ne}`)}continue}let oe=C.stopReason;if(A){if(g!==null){let et=g;oe&&(et.stopReason=oe),Z.delete(et.id),ae.delete(et.id),et.streaming!==!1&&(et.streaming=!1,f(et))}let Ne=(Ss=C.result)==null?void 0:Ss.response,lt=xe;lt&&(oe&&(lt.stopReason=oe),Ne!=null?Ge(lt,Ne):(Z.delete(lt.id),ae.delete(lt.id))),xe=null;continue}let G=(Qn=C.result)==null?void 0:Qn.response,Ee=we();if(oe&&(Ee.stopReason=oe),G!=null){let Ne=Z.get(Ee.id),lt=!1,et=!1;if(Ne){let Rt=Ne.getExtractedText(),_t=ae.get(Ee.id),un=_t!=null?_t:X(G);if(Ee.rawContent=un,Rt!==null&&Rt.trim()!=="")Ee.content=Rt,lt=!0;else{let at=Fo(un);if(at!==null)Ee.content=at,lt=!0;else{let ft=Ne.processChunk(un);if(ft instanceof Promise)et=!0,ft.then(Zt=>{var wn;let Ke=typeof Zt=="string"?Zt:(wn=Zt==null?void 0:Zt.text)!=null?wn:null;if(Ke!==null&&Ke.trim()!==""){let Jt=g;Jt&&Jt.id===Ee.id&&(Jt.content=Ke,Jt.streaming=!1,Z.delete(Jt.id),ae.delete(Jt.id),f(Jt))}else{let Jt=Ne.getExtractedText(),yn=g;yn&&yn.id===Ee.id&&(Jt!==null&&Jt.trim()!==""?yn.content=Jt:ae.has(yn.id)||(yn.content=X(G)),yn.streaming=!1,Z.delete(yn.id),ae.delete(yn.id),f(yn))}});else{let Zt=typeof ft=="string"?ft:(Xn=ft==null?void 0:ft.text)!=null?Xn:null;if(Zt!==null&&Zt.trim()!=="")Ee.content=Zt,lt=!0;else{let Ke=Ne.getExtractedText();Ke!==null&&Ke.trim()!==""&&(Ee.content=Ke,lt=!0)}}}}}if(!et){if(!Ee.rawContent){let Rt=ae.get(Ee.id);Ee.rawContent=Rt!=null?Rt:X(G)}if(!lt&&!ae.has(Ee.id)&&(Ee.content=X(G)),Ne){let Rt=(yr=Ne.close)==null?void 0:yr.call(Ne);Rt instanceof Promise&&Rt.catch(()=>{})}Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}}else Z.delete(Ee.id),ae.delete(Ee.id),Ee.streaming=!1,f(Ee)}else if(Ue==="flow_complete"){let $=(xr=C.result)==null?void 0:xr.response;if(A){if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}}else if($!=null){let k=we(),Y=ae.get(k.id),oe=Y!=null?Y:X($);k.rawContent=oe;let G=X($),Ee=Z.get(k.id);if(Ee){let et=Fo(oe);if(et!==null)G=et;else{let Rt=Ee.processChunk(oe);Rt instanceof Promise&&Rt.then(un=>{var ft;let at=typeof un=="string"?un:(ft=un==null?void 0:un.text)!=null?ft:null;at!==null&&(k.content=at,k.streaming=!1,f(k))});let _t=Ee.getExtractedText();_t!==null&&(G=_t)}}Z.delete(k.id),ae.delete(k.id);let Ne=G!==k.content,lt=k.streaming!==!1;Ne&&(k.content=G),k.streaming=!1,(Ne||lt)&&f(k)}else if(g!==null){let k=g;Z.delete(k.id),ae.delete(k.id),k.streaming!==!1&&(k.streaming=!1,f(k))}n({type:"status",status:"idle"})}else if(Ue==="agent_start")te={executionId:C.executionId,agentId:(To=C.agentId)!=null?To:"virtual",agentName:(jr=C.agentName)!=null?jr:"",status:"running",currentIteration:0,maxTurns:(Sn=C.maxTurns)!=null?Sn:1,startedAt:We(C.startedAt)};else if(Ue==="agent_iteration_start"){if(te&&(te.currentIteration=C.iteration),On==="separate"&&C.iteration>1){let $=g;$&&($.streaming=!1,f($),ze.set(C.iteration-1,$),g=null)}}else if(Ue==="agent_turn_start")v=null;else if(Ue==="agent_turn_delta"){if(C.contentType==="text"){let $=we();$.content+=(Pr=C.delta)!=null?Pr:"",$.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId,agentName:te==null?void 0:te.agentName},v=$,f($)}else if(C.contentType==="thinking"){let $=(Ko=C.turnId)!=null?Ko:`agent-think-${C.iteration}`,k=ke($);k.reasoning=(Eo=k.reasoning)!=null?Eo:{id:$,status:"streaming",chunks:[]},k.reasoning.chunks.push((Go=C.delta)!=null?Go:""),k.agentMetadata={executionId:C.executionId,iteration:C.iteration,turnId:C.turnId},f(k)}else if(C.contentType==="tool_input"){let $=(ya=C.toolCallId)!=null?ya:R.lastId;if($){let k=M.get($);k!=null&&k.toolCall&&(k.toolCall.chunks=(Jo=k.toolCall.chunks)!=null?Jo:[],k.toolCall.chunks.push((xa=C.delta)!=null?xa:""),f(k))}}}else if(Ue==="agent_turn_complete"){let $=C.turnId;if($){let oe=D.get($);if(oe!=null&&oe.reasoning){oe.reasoning.status="complete",oe.reasoning.completedAt=We(C.completedAt);let G=(Qo=oe.reasoning.startedAt)!=null?Qo:Date.now();oe.reasoning.durationMs=Math.max(0,((bt=oe.reasoning.completedAt)!=null?bt:Date.now())-G),oe.streaming=!1,f(oe)}}let k=C.stopReason,Y=g!=null?g:v;if(k&&Y!==null){let oe=C.turnId;(!oe||((Ts=Y.agentMetadata)==null?void 0:Ts.turnId)===oe)&&(Y.stopReason=k,f(Y))}}else if(Ue==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let $=(ir=C.toolCallId)!=null?ir:`agent-tool-${l()}`;Re(re(C),$);let k=se($),Y=(Fn=k.toolCall)!=null?Fn:{id:$,status:"pending",name:void 0,args:void 0,chunks:void 0,result:void 0,duration:void 0,startedAt:void 0,completedAt:void 0,durationMs:void 0};Y.name=(wa=(va=C.toolName)!=null?va:C.name)!=null?wa:Y.name,Y.status="running",C.parameters!==void 0&&(Y.args=C.parameters),Y.startedAt=We((Xo=C.startedAt)!=null?Xo:C.timestamp),k.toolCall=Y,k.streaming=!0,k.agentMetadata={executionId:C.executionId,iteration:C.iteration},f(k)}else if(Ue==="agent_tool_delta"){let $=(qr=C.toolCallId)!=null?qr:R.lastId;if($){let k=(Es=M.get($))!=null?Es:se($);k.toolCall&&(k.toolCall.chunks=(no=k.toolCall.chunks)!=null?no:[],k.toolCall.chunks.push((Ms=C.delta)!=null?Ms:""),k.toolCall.status="running",k.streaming=!0,f(k))}}else if(Ue==="agent_tool_complete"){let $=(ks=C.toolCallId)!=null?ks:R.lastId;if($){let k=(Ls=M.get($))!=null?Ls:se($);if(k.toolCall){k.toolCall.status="complete",C.result!==void 0&&(k.toolCall.result=C.result),typeof C.executionTime=="number"&&(k.toolCall.durationMs=C.executionTime),k.toolCall.completedAt=We((Ps=C.completedAt)!=null?Ps:C.timestamp),k.streaming=!1,f(k);let Y=re(C);Y&&R.byCall.delete(Y)}}}else if(Ue==="agent_media"){let $=Array.isArray(C.media)?C.media:[],k=[];for(let Y of $){if(!Y||typeof Y!="object")continue;let oe=Y,G=typeof oe.type=="string"?oe.type:void 0,Ee=typeof oe.mediaType=="string"?oe.mediaType.toLowerCase():"",Ne=null,lt="";if(G==="media"){let et=typeof oe.data=="string"?oe.data:void 0;if(!et)continue;lt=Ee.length>0?Ee:"application/octet-stream",Ne=`data:${lt};base64,${et}`}else if(G==="image-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else if(G==="file-url"){let et=typeof oe.url=="string"?oe.url:void 0;if(!et)continue;lt=Ee,Ne=et}else continue;if(Ne)if(G==="image-url"||lt.startsWith("image/"))k.push({type:"image",image:Ne,...lt?{mimeType:lt}:{}});else if(lt.startsWith("audio/"))k.push({type:"audio",audio:Ne,mimeType:lt});else if(lt.startsWith("video/"))k.push({type:"video",video:Ne,mimeType:lt});else{let et=lt||"application/octet-stream";k.push({type:"file",data:Ne,mimeType:et,filename:Mf(et)})}}if(k.length>0){let Y=l(),oe=C.toolCallId,Ee={id:`agent-media-${typeof oe=="string"&&oe.length>0?`${oe}-${Y}`:String(Y)}`,role:"assistant",content:"",contentParts:k,createdAt:new Date().toISOString(),streaming:!1,sequence:Y,agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(Ee);let Ne=g;Ne&&(Ne.streaming=!1,f(Ne)),g=null,y.current=null}}else if(Ue!=="agent_iteration_complete"){if(Ue==="agent_reflection"||Ue==="agent_reflect"){let $=`agent-reflection-${C.executionId}-${C.iteration}`,k={id:$,role:"assistant",content:(_n=C.reflection)!=null?_n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:$,status:"complete",chunks:[(Yo=C.reflection)!=null?Yo:""]},agentMetadata:{executionId:C.executionId,iteration:C.iteration}};f(k)}else if(Ue==="agent_complete"){te&&(te.status=C.success?"complete":"error",te.completedAt=We(C.completedAt),te.stopReason=C.stopReason);let $=g;$&&($.streaming=!1,f($)),n({type:"status",status:"idle"})}else if(Ue==="agent_error"){let $=typeof C.error=="string"?C.error:(Rr=(Ir=C.error)==null?void 0:Ir.message)!=null?Rr:"Agent execution error";C.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",$):n({type:"error",error:new Error($)})}else if(Ue!=="agent_ping"){if(Ue==="agent_approval_start"){let $=(Is=C.approvalId)!=null?Is:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ca=te==null?void 0:te.agentId)!=null?Ca:"virtual",executionId:(Ws=(Rs=C.executionId)!=null?Rs:te==null?void 0:te.executionId)!=null?Ws:"",toolName:(Mo=C.toolName)!=null?Mo:"",toolType:C.toolType,description:(Sa=C.description)!=null?Sa:`Execute ${(Aa=C.toolName)!=null?Aa:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="step_await"&&C.awaitReason==="approval_required"){let $=(Ta=C.approvalId)!=null?Ta:`approval-${l()}`,k={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:"pending",agentId:(Ea=te==null?void 0:te.agentId)!=null?Ea:"virtual",executionId:(ko=(Oi=C.executionId)!=null?Oi:te==null?void 0:te.executionId)!=null?ko:"",toolName:(ro=C.toolName)!=null?ro:"",toolType:C.toolType,description:(Hs=C.description)!=null?Hs:`Execute ${(Ma=C.toolName)!=null?Ma:"tool"}`,...typeof C.reason=="string"&&C.reason?{reason:C.reason}:{},parameters:C.parameters}};f(k)}else if(Ue==="agent_approval_complete"){let $=C.approvalId;if($){let Y={id:`approval-${$}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:$,status:(oo=C.decision)!=null?oo:"approved",agentId:(ka=te==null?void 0:te.agentId)!=null?ka:"virtual",executionId:(so=(Bs=C.executionId)!=null?Bs:te==null?void 0:te.executionId)!=null?so:"",toolName:(Ds=C.toolName)!=null?Ds:"",description:(La=C.description)!=null?La:"",resolvedAt:Date.now()}};f(Y)}}else if(Ue==="artifact_start"||Ue==="artifact_delta"||Ue==="artifact_update"||Ue==="artifact_complete"){if(Ue==="artifact_start"){let $=C.artifactType,k=String(C.id),Y=typeof C.title=="string"?C.title:void 0;if(n({type:"artifact_start",id:k,artifactType:$,title:Y,component:typeof C.component=="string"?C.component:void 0}),le.set(k,{markdown:"",title:Y}),!ne.has(k)){ne.add(k);let oe={id:`artifact-ref-${k}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:k,title:Y,artifactType:$,status:"streaming"}})};Q.set(k,oe),f(oe)}}else if(Ue==="artifact_delta"){let $=String(C.id),k=typeof C.delta=="string"?C.delta:String((zr=C.delta)!=null?zr:"");n({type:"artifact_delta",id:$,artDelta:k});let Y=le.get($);Y&&(Y.markdown+=k)}else if(Ue==="artifact_update"){let $=C.props&&typeof C.props=="object"&&!Array.isArray(C.props)?C.props:{};n({type:"artifact_update",id:String(C.id),props:$,component:typeof C.component=="string"?C.component:void 0})}else if(Ue==="artifact_complete"){let $=String(C.id);n({type:"artifact_complete",id:$});let k=Q.get($);if(k){k.streaming=!1;try{let Y=JSON.parse((Pa=k.rawContent)!=null?Pa:"{}");if(Y.props){Y.props.status="complete";let oe=le.get($);oe!=null&&oe.markdown&&(Y.props.markdown=oe.markdown)}k.rawContent=JSON.stringify(Y)}catch{}le.delete($),f(k),Q.delete($)}}}else if(Ue==="transcript_insert"){let $=C.message;if(!$||typeof $!="object")continue;let k=String((ao=$.id)!=null?ao:`msg-${l()}`),Y=$.role,G={id:k,role:Y==="user"?"user":Y==="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(f(G),G.rawContent)try{let Ee=JSON.parse(G.rawContent),Ne=(Bt=Ee==null?void 0:Ee.props)==null?void 0:Bt.artifactId;typeof Ne=="string"&&ne.add(Ne)}catch{}g=null,y.current=null,Z.delete(k),ae.delete(k)}else if(Ue==="error"||Ue==="step_error"||Ue==="dispatch_error"||Ue==="flow_error"){let $=null;if(C.error instanceof Error)$=C.error;else if(Ue==="dispatch_error"){let k=(Zo=C.message)!=null?Zo:C.error;k!=null&&k!==""&&($=new Error(String(k)))}else if(Ue==="step_error"||Ue==="flow_error"){let k=C.error;typeof k=="string"&&k!==""?$=new Error(k):k!=null&&typeof k=="object"&&"message"in k&&($=new Error(String((es=k.message)!=null?es:k)))}else Ue==="error"&&C.error!=null&&C.error!==""&&($=new Error(String(C.error)));if($){n({type:"error",error:$});let k=g;k&&k.streaming&&(k.streaming=!1,f(k)),n({type:"status",status:"idle"})}}}}}Be.length=0};;){let{done:W,value:de}=await s.read();if(W)break;a+=o.decode(de,{stream:!0});let De=a.split(`
10
10
 
11
11
  `);a=(ln=De.pop())!=null?ln:"";for(let Je of De){let Fe=Je.split(`
12
12
  `),$e="message",st="";for(let Yt of Fe)Yt.startsWith("event:")?$e=Yt.replace("event:","").trim():Yt.startsWith("data:")&&(st+=Yt.replace("data:","").trim());if(!st)continue;let Lt;try{Lt=JSON.parse(st)}catch(Yt){n({type:"error",error:Yt instanceof Error?Yt:new Error("Failed to parse chat stream payload")});continue}let zt=$e!=="message"?$e:(nr=Lt.type)!=null?nr:"message";if((Sr=this.onSSEEvent)==null||Sr.call(this,zt,Lt),this.parseSSEEvent){y.current=g;let Yt=await this.handleCustomSSEEvent(Lt,n,y,f,l,w);if(y.current&&y.current!==g&&(g=y.current),Yt)continue}Tt.push(zt,Lt),pe()}}Tt.flushPending(),pe(),Tt.destroy()}};function Pf(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Qs(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function us(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var Ga="[Image]";function If(e){return typeof e=="string"?[{type:"text",text:e}]:e}function Rf(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Wf(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function Hf(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function Ja(e){return{type:"text",text:e}}function Bf(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 Df(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;t({type:"image",image:s,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Of(e,t=["image/png","image/jpeg","image/gif","image/webp"],n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type. Accepted types: ${t.join(", ")}`}}var Bu=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],Nf=["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"],Kr=[...Bu,...Nf];function Ff(e){return Bu.includes(e)||e.startsWith("image/")}function Qa(e){return Ff(e.type)}async function Du(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let s=r.result;Qa(e)?t({type:"image",image:s,mimeType:e.type,alt:e.name}):t({type:"file",data:s,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function Ou(e,t=Kr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function _f(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function Nu(e,t){let n=_f(t).toUpperCase();return{"application/pdf":"PDF","text/plain":"TXT","text/markdown":"MD","text/csv":"CSV","application/msword":"DOC","application/vnd.openxmlformats-officedocument.wordprocessingml.document":"DOCX","application/vnd.ms-excel":"XLS","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet":"XLSX","application/json":"JSON"}[e]||n||"FILE"}var Xa=class{constructor(t=24e3){this.ctx=null;this.nextStartTime=0;this.activeSources=[];this.finishedCallbacks=[];this.playing=!1;this.streamEnded=!1;this.pendingCount=0;this.remainder=null;this.sampleRate=t}ensureContext(){if(!this.ctx){let n=typeof window!="undefined"?window:void 0;if(!n)throw new Error("AudioPlaybackManager requires a browser environment");let r=n.AudioContext||n.webkitAudioContext;this.ctx=new r({sampleRate:this.sampleRate})}let t=this.ctx;return t.state==="suspended"&&t.resume(),t}enqueue(t){if(t.length===0)return;let n=t;if(this.remainder){let d=new Uint8Array(this.remainder.length+t.length);d.set(this.remainder),d.set(t,this.remainder.length),n=d,this.remainder=null}if(n.length%2!==0&&(this.remainder=new Uint8Array([n[n.length-1]]),n=n.subarray(0,n.length-1)),n.length===0)return;let r=this.ensureContext(),s=this.pcmToFloat32(n),o=r.createBuffer(1,s.length,this.sampleRate);o.getChannelData(0).set(s);let a=r.createBufferSource();a.buffer=o,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=o.duration,this.activeSources.push(a),this.pendingCount++,this.playing=!0,a.onended=()=>{let d=this.activeSources.indexOf(a);d!==-1&&this.activeSources.splice(d,1),this.pendingCount--,this.checkFinished()}}markStreamEnd(){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.remainder=null}isPlaying(){return this.playing}onFinished(t){this.finishedCallbacks.push(t)}async destroy(){this.flush(),this.ctx&&(await this.ctx.close(),this.ctx=null)}checkFinished(){if(this.streamEnded&&this.pendingCount<=0&&this.playing){this.playing=!1,this.streamEnded=!1;let t=this.finishedCallbacks.slice();this.finishedCallbacks=[];for(let n of t)n()}}pcmToFloat32(t){let n=Math.floor(t.length/2),r=new Float32Array(n),s=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let o=0;o<n;o++){let a=s.getInt16(o*2,!0);r[o]=a/32768}return r}};var Ya=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,s,o){this.stop(),this.fired=!1,this.conditionStart=null,this.sourceNode=t.createMediaStreamSource(n),this.analyserNode=t.createAnalyser(),this.analyserNode.fftSize=2048,this.sourceNode.connect(this.analyserNode);let a=new Float32Array(this.analyserNode.fftSize);this.interval=setInterval(()=>{if(!this.analyserNode||this.fired)return;this.analyserNode.getFloatTimeDomainData(a);let i=0;for(let p=0;p<a.length;p++)i+=a[p]*a[p];let d=Math.sqrt(i/a.length);(r==="silence"?d<s.threshold:d>=s.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=s.duration&&(this.fired=!0,o()):this.conditionStart=null},100)}stop(){this.interval&&(clearInterval(this.interval),this.interval=null),this.sourceNode&&(this.sourceNode.disconnect(),this.sourceNode=null),this.analyserNode=null,this.conditionStart=null,this.fired=!1}};var Xs=class{constructor(t){this.config=t;this.type="runtype";this.ws=null;this.audioContext=null;this.w=typeof window!="undefined"?window:void 0;this.mediaRecorder=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.processingStartCallbacks=[];this.audioChunks=[];this.isProcessing=!1;this.isSpeaking=!1;this.vad=new Ya;this.mediaStream=null;this.currentAudio=null;this.currentAudioUrl=null;this.currentRequestId=null;this.interruptionMode="none";this.playbackManager=null}getInterruptionMode(){return this.interruptionMode}isBargeInActive(){return this.interruptionMode==="barge-in"&&this.mediaStream!==null}async deactivateBargeIn(){this.vad.stop(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)}async connect(){var t,n,r;if(!(this.ws&&this.ws.readyState===WebSocket.OPEN))try{if(!this.w)throw new Error("Window object not available");let s=this.w;if(!s||!s.location)throw new Error("Window object or location not available");let o=s.location.protocol==="https:"?"wss:":"ws:",a=(t=this.config)==null?void 0:t.host,i=(n=this.config)==null?void 0:n.agentId,d=(r=this.config)==null?void 0:r.clientToken;if(!i||!d)throw new Error("agentId and clientToken are required");if(!a)throw new Error("host must be provided in Runtype voice provider configuration");let l=`${o}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${o}//${a}/ws/agents/${i}/voice?token=...`,u=" Check: API running on port 8787? Valid client token? Agent voice enabled? Token allowedOrigins includes this page?";await new Promise((f,g)=>{if(!this.ws)return g(new Error("WebSocket not created"));let v=!1,y=A=>{v||(v=!0,clearTimeout(w),g(new Error(A)))},w=setTimeout(()=>y("WebSocket connection timed out."+u),1e4);this.ws.addEventListener("open",()=>{v||(v=!0,clearTimeout(w),f())},{once:!0}),this.ws.addEventListener("error",()=>{y("WebSocket connection failed to "+p+"."+u)},{once:!0}),this.ws.addEventListener("close",A=>{if(!A.wasClean&&!v){let D=A.code!==1006?` (code ${A.code})`:"";y("WebSocket connection failed"+D+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(s){throw this.ws=null,this.errorCallbacks.forEach(o=>o(s)),this.statusCallbacks.forEach(o=>o("error")),s}}setupWebSocketHandlers(){this.ws&&(this.ws.onopen=()=>{this.statusCallbacks.forEach(t=>t("connected"))},this.ws.onclose=()=>{this.statusCallbacks.forEach(t=>t("disconnected"))},this.ws.onerror=t=>{this.errorCallbacks.forEach(n=>n(new Error("WebSocket error"))),this.statusCallbacks.forEach(n=>n("error"))},this.ws.binaryType="arraybuffer",this.ws.onmessage=t=>{if(t.data instanceof ArrayBuffer){this.handleAudioChunk(new Uint8Array(t.data));return}try{let n=JSON.parse(t.data);this.handleWebSocketMessage(n)}catch{this.errorCallbacks.forEach(r=>r(new Error("Message parsing failed")))}})}handleWebSocketMessage(t){var n,r;switch(t.type){case"session_config":t.interruptionMode&&(this.interruptionMode=t.interruptionMode);break;case"voice_response":this.isProcessing=!1,this.resultCallbacks.forEach(s=>s({text:t.response.agentResponseText||t.response.transcript,transcript:t.response.transcript,audio:t.response.audio,confidence:.95,provider:"runtype"})),(n=t.response.audio)!=null&&n.base64?(this.isSpeaking=!0,this.statusCallbacks.forEach(s=>s("speaking")),this.playAudio(t.response.audio).catch(s=>this.errorCallbacks.forEach(o=>o(s instanceof Error?s:new Error(String(s)))))):(r=t.response.audio)!=null&&r.base64;break;case"audio_end":if(t.requestId&&t.requestId!==this.currentRequestId)break;this.playbackManager?this.playbackManager.markStreamEnd():(this.isSpeaking=!1,this.isProcessing=!1,this.statusCallbacks.forEach(s=>s("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(s=>s(new Error(t.error))),this.statusCallbacks.forEach(s=>s("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new Xa(24e3),this.playbackManager.onFinished(()=>{this.isSpeaking=!1,this.playbackManager=null,this.vad.stop(),this.statusCallbacks.forEach(n=>n("idle"))})),this.isSpeaking||(this.isSpeaking=!0,this.statusCallbacks.forEach(n=>n("speaking")),this.startBargeInMonitoring().catch(()=>{})),this.playbackManager.enqueue(t))}stopPlayback(){!this.isProcessing&&!this.isSpeaking||(this.cancelCurrentPlayback(),this.statusCallbacks.forEach(t=>t("idle")))}cancelCurrentPlayback(){this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(this.playbackManager.flush(),this.playbackManager=null),this.currentRequestId&&this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"cancel",requestId:this.currentRequestId})),this.currentRequestId=null,this.isProcessing=!1,this.isSpeaking=!1}async startListening(){var t,n,r,s;try{if(this.isProcessing||this.isSpeaking)if(this.interruptionMode!=="none")this.cancelCurrentPlayback();else return;if(!this.mediaStream){let l=this.interruptionMode==="barge-in"?{audio:{echoCancellation:!0,noiseSuppression:!0}}:{audio:!0};this.mediaStream=await navigator.mediaDevices.getUserMedia(l)}let o=this.w;this.audioContext||(this.audioContext=new(o.AudioContext||o.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(s=(r=this.config)==null?void 0:r.silenceThreshold)!=null?s:.01;this.vad.start(a,this.mediaStream,"silence",{threshold:d,duration:i},()=>this.stopListening()),this.mediaRecorder=new MediaRecorder(this.mediaStream),this.audioChunks=[],this.mediaRecorder.ondataavailable=l=>{l.data.size>0&&this.audioChunks.push(l.data)},this.mediaRecorder.onstop=async()=>{var l;if(this.audioChunks.length>0){this.isProcessing=!0,this.statusCallbacks.forEach(f=>f("processing")),this.processingStartCallbacks.forEach(f=>f());let p=((l=this.mediaRecorder)==null?void 0:l.mimeType)||"audio/webm",u=new Blob(this.audioChunks,{type:p});await this.sendAudio(u),this.audioChunks=[]}},this.mediaRecorder.start(1e3),this.statusCallbacks.forEach(l=>l("listening"))}catch(o){throw this.errorCallbacks.forEach(a=>a(o)),this.statusCallbacks.forEach(a=>a("error")),o}}async stopListening(){this.vad.stop(),this.mediaRecorder&&(this.interruptionMode!=="barge-in"&&this.mediaRecorder.stream.getTracks().forEach(t=>t.stop()),this.mediaRecorder.stop(),this.mediaRecorder=null),this.interruptionMode!=="barge-in"&&(this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null)),this.statusCallbacks.forEach(t=>t("idle"))}async startBargeInMonitoring(){var o,a;if(this.interruptionMode!=="barge-in")return;let t=this.w;if(!this.mediaStream&&t&&(this.mediaStream=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0}})),!this.audioContext&&t&&(this.audioContext=new(t.AudioContext||t.webkitAudioContext)),!this.audioContext||!this.mediaStream)return;let n=this.audioContext,r=(a=(o=this.config)==null?void 0:o.silenceThreshold)!=null?a:.01;this.vad.start(n,this.mediaStream,"speech",{threshold:r,duration:200},()=>this.handleBargeIn())}handleBargeIn(){this.cancelCurrentPlayback(),this.startListening().catch(t=>{this.errorCallbacks.forEach(n=>n(t instanceof Error?t:new Error(String(t))))})}generateRequestId(){return"vreq_"+Math.random().toString(36).substring(2,10)+Date.now().toString(36)}async sendAudio(t){var n;if(!this.ws||this.ws.readyState!==WebSocket.OPEN){this.errorCallbacks.forEach(r=>r(new Error("WebSocket not connected"))),this.statusCallbacks.forEach(r=>r("error"));return}try{let r=await this.blobToBase64(t),s=this.getFormatFromMimeType(t.type),o=this.generateRequestId();this.currentRequestId=o,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:s,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:o}))}catch(r){this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let s=new FileReader;s.onload=()=>{let a=s.result.split(",")[1];n(a)},s.onerror=r,s.readAsDataURL(t)})}async playAudio(t){if(!t.base64)return;let n=atob(t.base64),r=new Uint8Array(n.length);for(let l=0;l<n.length;l++)r[l]=n.charCodeAt(l);let s=t.format||"mp3",o=s==="mp3"?"audio/mpeg":`audio/${s}`,a=new Blob([r],{type:o}),i=URL.createObjectURL(a),d=new Audio(i);this.currentAudio=d,this.currentAudioUrl=i,d.onended=()=>{URL.revokeObjectURL(i),this.currentAudio===d&&(this.currentAudio=null,this.currentAudioUrl=null,this.isSpeaking=!1,this.statusCallbacks.forEach(l=>l("idle")))},await d.play()}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}onProcessingStart(t){this.processingStartCallbacks.push(t)}async disconnect(){if(this.currentAudio&&(this.currentAudio.pause(),this.currentAudio.src="",this.currentAudio=null),this.currentAudioUrl&&(URL.revokeObjectURL(this.currentAudioUrl),this.currentAudioUrl=null),this.playbackManager&&(await this.playbackManager.destroy(),this.playbackManager=null),this.currentRequestId=null,this.isSpeaking=!1,this.vad.stop(),await this.stopListening(),this.mediaStream&&(this.mediaStream.getTracks().forEach(t=>t.stop()),this.mediaStream=null),this.audioContext&&(await this.audioContext.close(),this.audioContext=null),this.ws){try{this.ws.close()}catch{}this.ws=null}this.statusCallbacks.forEach(t=>t("disconnected"))}sendHeartbeat(){this.ws&&this.ws.readyState===WebSocket.OPEN&&this.ws.send(JSON.stringify({type:"ping"}))}};var _o=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=s=>{var i;let o=Array.from(s.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=s.results[s.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:o,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=s=>{this.errorCallbacks.forEach(o=>o(new Error(s.error))),this.statusCallbacks.forEach(o=>o("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(s=>s("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(s=>s("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(s=>s(r)),this.statusCallbacks.forEach(s=>s("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function ms(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new Xs(e.runtype);case"browser":if(!_o.isSupported())throw new Error("Browser speech recognition not supported");return new _o(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function sl(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return ms({type:"runtype",runtype:e.runtype});if(_o.isSupported())return ms({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function Za(e){try{return sl(e),!0}catch{return!1}}var $f=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function Uf(e,t){return $f.some(n=>e[n]!==t[n])}function Fu(e,t){let n=e instanceof Error?e:new Error(String(e));if(typeof t=="string")return t;if(typeof t=="function")return t(n);let r="Sorry \u2014 I couldn't reach the assistant. The chat service didn't respond. Please check that your proxy or backend is running and reachable, then try again.";return n.message?`${r}
@@ -104,7 +104,7 @@ _Details: ${n.message}_`:r}var Ys=e=>({isError:!0,content:[{type:"text",text:e}]
104
104
  flex-shrink: 0 !important;
105
105
  border-top: none !important;
106
106
  padding: 8px 16px 12px 16px !important;
107
- `}if(!x&&!c){let $t="max-height: -moz-available !important; max-height: stretch !important;",Nt=m?"":"padding-top: 1.25em !important;",ht=m?"":`z-index: ${(mn=(nt=r.launcher)==null?void 0:nt.zIndex)!=null?mn:kn} !important;`;xe.style.cssText+=$t+Nt+ht}Qe()};fr(),$o(e,r),Ai(e,r),Si(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",Yr)});let tn=null,nn=null;gt.push(()=>{tn==null||tn(),tn=null,nn==null||nn(),nn=null}),qn&&gt.push(()=>{qn==null||qn.disconnect(),qn=null}),gt.push(()=>{In==null||In(),In=null,_r(),Ht&&(Ht.remove(),Ht=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Ie&&gt.push(()=>{We!==null&&(cancelAnimationFrame(We),We=null),V==null||V.destroy(),V=null,le==null||le.destroy(),le=null,Q=null});let Jn=null,to=()=>{Jn&&(Jn(),Jn=null),r.colorScheme==="auto"&&(Jn=dl(()=>{$o(e,r)}))};to(),gt.push(()=>{Jn&&(Jn(),Jn=null)});let be=(zc=r.features)==null?void 0:zc.streamAnimation;if(be!=null&&be.type&&be.type!=="none"){let c=sa(be.type,be.plugins);c&&(ml(c,e),gt.push(()=>lm(e)))}let hr=Em(Tt),ar=null,_,Vo=c=>{var x,T;if(!_)return;let m=c!=null?c:_.getMessages(),b=((T=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:T.enabled)!==!1?Yi(m):null;b?hr.render(b,_,te,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(B=>B.role==="user")?hr.render([],_,te,m):hr.render(r.suggestionChips,_,te,m,r.suggestionChipsConfig)},kr=!1,$r=Zu(),Ur=new Map,Lr=new Map,br=new Map,Ss=0,Qn=oi(),Xn=0,yr=null,xr=!1,To=!1,jr=0,Sn=null,Pr=null,Ko=!1,Eo=!1,Go=null,ya=4,Jo=24,xa=80,Qo=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(Kc=(Vc=r.voiceRecognition)==null?void 0:Vc.autoResume)!=null?Kc:!1,ir=c=>{o.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Fn=()=>{g(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},va=()=>{var x,T;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let c=Bl(d.voiceState),m=!!c.active,b=Number((T=c.timestamp)!=null?T:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-b<Px&&setTimeout(()=>{var B,O;bt.active||(bt.manuallyDeactivated=!1,((O=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:O.type)==="runtype"?_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("restore"),_.isVoiceActive()&&Os()}):Jt("restore"))},1e3)},wa=()=>_?jm(_.getMessages()).filter(c=>!c.__skipPersist):[];function Xo(c){if(!(i!=null&&i.save))return;let b={messages:c?jm(c):_?wa():[],metadata:d,artifacts:zn.artifacts,selectedArtifactId:zn.selectedId};try{let x=i.save(b);x instanceof Promise&&x.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let qr=null,Es=()=>xe.querySelector("#persona-scroll-container")||pe,no=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),xr=!1},Ms=()=>{yr!==null&&(cancelAnimationFrame(yr),yr=null),To=!1,no()},ks=()=>{jr>0?(Cn.textContent=String(jr),Cn.style.display="",Ze.setAttribute("aria-label",`${Vt()||"Jump to latest"} (${jr} new)`)):(Cn.textContent="",Cn.style.display="none",Ze.setAttribute("aria-label",Vt()||"Jump to latest"))},Ls=()=>{jr!==0&&(jr=0,ks())},Ps=()=>ut()==="follow"?!Qn.isFollowing():!Uo(pe,Jo),_n=()=>{if(!vn()||se){Ze.parentNode&&Ze.remove(),Ze.style.display="none";return}Ze.parentNode!==z&&z.appendChild(Ze),bn();let m=Gr(pe)>0&&Ps();m||Ls(),Ze.style.display=m?"":"none"},Yo=()=>{Qn.pause()&&(Ms(),_n())},Ir=()=>{Qn.resume(),Ls(),_n()},Rr=(c=!1)=>{ut()==="follow"&&Qn.isFollowing()&&(!c&&!kr||(yr!==null&&(cancelAnimationFrame(yr),yr=null),To=!0,yr=requestAnimationFrame(()=>{yr=null,To=!1,Qn.isFollowing()&&Ca(Es(),c?220:140)})))},Is=(c,m,b,x=()=>!0)=>{let T=c.scrollTop,B=m(),O=B-T;no();let j=performance.now();xr=!0;let H=ue=>1-Math.pow(1-ue,3),ye=ue=>{if(!x()){no();return}let ee=m();ee!==B&&(B=ee,O=B-T);let Te=ue-j,_e=Math.min(Te/b,1),Ae=H(_e),ot=T+O*Ae;c.scrollTop=ot,Xn=c.scrollTop,_e<1?qr=requestAnimationFrame(ye):(c.scrollTop=B,Xn=c.scrollTop,qr=null,xr=!1)};qr=requestAnimationFrame(ye)},Ca=(c,m=500)=>{let b=Gr(c)-c.scrollTop;if(Math.abs(b)<1){Xn=c.scrollTop;return}if(Math.abs(b)>=xa){no(),xr=!0,c.scrollTop=Gr(c),Xn=c.scrollTop,xr=!1;return}Is(c,()=>Gr(c),m,()=>Qn.isFollowing())},Rs=()=>{let c=Es();xr=!0,c.scrollTop=Gr(c),Xn=c.scrollTop,xr=!1,_n()},Ws=c=>{An.style.height=`${Math.max(0,Math.round(c))}px`,Sn&&(Sn.spacerHeight=Math.max(0,c))},Mo=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),no(),Sn=null,An.style.height="0px"},Aa=c=>{Pr!==null&&cancelAnimationFrame(Pr),Pr=requestAnimationFrame(()=>{var ye;Pr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=pe.querySelector(`[data-message-id="${m}"]`);if(!b)return;let x=0,T=b;for(;T&&T!==pe;)x+=T.offsetTop,T=T.offsetParent;let B=(ye=Sn==null?void 0:Sn.spacerHeight)!=null?ye:0,O=pe.scrollHeight-B,{targetScrollTop:j,spacerHeight:H}=om({anchorOffsetTop:x,topOffset:Et(),viewportHeight:pe.clientHeight,contentHeight:O});Sn={initialSpacerHeight:H,contentHeightAtAnchor:O,spacerHeight:H},Ws(H),Is(pe,()=>j,220)})},Sa=()=>{if(ut()==="follow"){if(!Qn.isFollowing()||Uo(pe,1))return;Rr(!kr);return}if(Sn&&Sn.initialSpacerHeight>0){let c=pe.scrollHeight-Sn.spacerHeight,m=sm({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:c});m!==Sn.spacerHeight&&Ws(m)}_n()},Ta=c=>{let m=ut();m==="follow"?(Ir(),Rr(!0)):m==="anchor-top"&&Aa(c)},Ea=c=>{let m=new Map;c.forEach(b=>{let x=Qo.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(o.emit("assistant:message",b),!Eo&&ut()!=="anchor-top"&&Ps()&&(jr+=1,ks(),_n())),b.role==="assistant"&&(x!=null&&x.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Qo.clear(),m.forEach((b,x)=>{Qo.set(x,b)})},ko=(c,m,b)=>{var dt,Pe,Le,je,Qe,vt;let x=document.createElement("div"),B=(()=>{var He;let L=s.find(Oe=>Oe.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((He=r.loadingIndicator)!=null&&He.render)return r.loadingIndicator.render})(),O=(L,He)=>He==null?!1:typeof He=="string"?(L.textContent=He,!0):(L.appendChild(He),!0),j=new Set,H=new Set,ye=s.some(L=>L.renderAskUserQuestion),ue=[],ee=[],Te=r.enableComponentStreaming!==!1,_e=s.some(L=>L.renderApproval)&&r.approval!==!1,Ae=[];if(m.forEach(L=>{var Xe,Pt,pn,cr,Zn,Po,Io,rs,os,Qt,Ro,co,po,Vr,Wo,vr;j.add(L.id);let He=ye&&mo(L),Oe=_e&&L.variant==="approval"&&!!L.approval,fe=!He&&L.role==="assistant"&&!L.variant&&Te&&Il(L);if(!Oe&&br.has(L.id)){let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),br.delete(L.id)}if(!fe&&Lr.has(L.id)){let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),Lr.delete(L.id)}let Ot=mo(L)?`:${(Xe=L.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Pt=L.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=Yu(L,Ss)+Ot,Kt=He||Oe||fe?null:em($r,L.id,Dt);if(Kt){x.appendChild(Kt.cloneNode(!0)),mo(L)&&((pn=L.toolCall)!=null&&pn.id)&&((cr=L.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Zn=L.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}let wt=null,qt=s.find(nt=>!!(L.variant==="reasoning"&&nt.renderReasoning||L.variant==="tool"&&nt.renderToolCall||!L.variant&&nt.renderMessage)),Yn=(Po=r.layout)==null?void 0:Po.messages;if(mo(L)&&((Io=L.agentMetadata)==null?void 0:Io.askUserQuestionAnswered)===!0){Ur.delete(L.id);let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(_a(L)&&((os=(rs=r.features)==null?void 0:rs.suggestReplies)==null?void 0:os.enabled)!==!1)return;if(mo(L)&&((Ro=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Ro.enabled)!==!1){let nt=s.find(mn=>typeof mn.renderAskUserQuestion=="function");if(nt&&kt.current){let mn=Ur.get(L.id),$t=mn!==Dt,Nt=null;if($t){let{payload:Mt,complete:Tn}=go(L),Rn=L.id,Wr=()=>{var xn;return(xn=kt.current)==null?void 0:xn.getMessages().find(Wn=>Wn.id===Rn)};Nt=nt.renderAskUserQuestion({message:L,payload:Mt,complete:Tn,resolve:xn=>{var Hn;let Wn=Wr();Wn&&((Hn=kt.current)==null||Hn.resolveAskUserQuestion(Wn,xn))},dismiss:()=>{var Wn,Hn,Ho;let xn=Wr();(Wn=xn==null?void 0:xn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((Hn=kt.current)==null||Hn.markAskUserQuestionResolved(xn),(Ho=kt.current)==null||Ho.resolveAskUserQuestion(xn,"(dismissed)"))},config:r})}let ht=mn!=null;if($t&&Nt===null&&!ht){((co=L.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!((po=L.agentMetadata)!=null&&po.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),x.appendChild(Xt),ue.push({messageId:L.id,fingerprint:Dt,bubble:Nt});return}else{((Vr=L.agentMetadata)==null?void 0:Vr.awaitingLocalTool)===!0&&!((Wo=L.agentMetadata)!=null&&Wo.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}}else if(Oe){let nt=s.find(ht=>typeof ht.renderApproval=="function"),$t=br.get(L.id)!==Dt,Nt=null;if($t&&(nt!=null&&nt.renderApproval)){let ht=L.id,Xt=(Mt,Tn)=>{var Wr,xn,Wn;let Rn=(Wr=kt.current)==null?void 0:Wr.getMessages().find(Hn=>Hn.id===ht);Rn!=null&&Rn.approval&&(Rn.approval.toolType==="webmcp"?(xn=kt.current)==null||xn.resolveWebMcpApproval(Rn.id,Mt):(Wn=kt.current)==null||Wn.resolveApproval(Rn.approval,Mt,Tn))};Nt=nt.renderApproval({message:L,defaultRenderer:()=>wi(L,r),config:r,approve:Mt=>Xt("approved",Mt),deny:Mt=>Xt("denied",Mt)})}if($t&&Nt===null){let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),br.delete(L.id),wt=wi(L,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${L.id}`,ht.setAttribute("data-wrapper-id",L.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Ae.push({messageId:L.id,fingerprint:Dt,bubble:Nt});return}}else if(qt)if(L.variant==="reasoning"&&L.reasoning&&qt.renderReasoning){if(!qe)return;wt=qt.renderReasoning({message:L,defaultRenderer:()=>vl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&qt.renderToolCall){if(!we)return;wt=qt.renderToolCall({message:L,defaultRenderer:()=>wl(L,r),config:r})}else qt.renderMessage&&(wt=qt.renderMessage({message:L,defaultRenderer:()=>{let nt=ma(L,b,Yn,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r});return L.role!=="user"&&Tl(nt,L,r,_),nt},config:r}));if(!wt&&fe){let nt=Rl(L);if(nt){let mn=Lr.get(L.id),$t=mn!==Dt,Nt=r.wrapComponentDirectiveInBubble!==!1,ht=null;if($t){let Xt=Pl(nt,{config:r,message:L,transform:b});if(Xt)if(Nt){let Mt=document.createElement("div");if(Mt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Tn=document.createElement("div");Tn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Tn)}Mt.appendChild(Xt),ht=Mt}else{let Mt=document.createElement("div");if(Mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),Mt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Tn=document.createElement("div");Tn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Tn)}Mt.appendChild(Xt),ht=Mt}}if(ht||mn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),Nt||Xt.classList.add("persona-w-full"),x.appendChild(Xt),ee.push({messageId:L.id,fingerprint:Dt,bubble:ht});return}}}if(!wt)if(L.variant==="reasoning"&&L.reasoning){if(!qe)return;wt=vl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!we)return;wt=wl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;wt=wi(L,r)}else{let nt=(vr=r.layout)==null?void 0:vr.messages;nt!=null&&nt.renderUserMessage&&L.role==="user"?wt=nt.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):nt!=null&&nt.renderAssistantMessage&&L.role==="assistant"?wt=nt.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):wt=ma(L,b,nt,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r}),L.role!=="user"&&wt&&Tl(wt,L,r,_)}let an=document.createElement("div");an.className="persona-flex",an.id=`wrapper-${L.id}`,an.setAttribute("data-wrapper-id",L.id),L.role==="user"&&an.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&an.classList.add("persona-w-full"),an.appendChild(wt),tm($r,L.id,Dt,an),x.appendChild(an)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Oe=He.getAttribute("data-persona-ask-sheet-for");Oe&&!H.has(Oe)&&No(Be.composerOverlay,Oe)}),(Pe=(dt=r.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let L=[],He=[];m.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&we){He.push(Oe);return}He.length>1&&L.push(He),He=[]}),He.length>1&&L.push(He),L.forEach((Oe,fe)=>{var Xe,Pt;let Ot=Oe.map(pn=>Array.from(x.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(Ot.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${fe}-${Oe[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Oe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Oe.length} tools`,Yn=(Pt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Pt.call(Xe,{messages:Oe,toolCalls:Oe.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:qt,config:r});O(wt,Yn)||(wt.textContent=qt);let an=document.createElement("div");an.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,an),Dt.appendChild(Kt),Ot[0].before(Dt),Ot.forEach((pn,cr)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),cr<Ot.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(pn),an.appendChild(Zn)})})}nm($r,j);let ot=m.some(L=>L.role==="assistant"&&L.streaming),Ve=m[m.length-1],ct=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(kr&&m.some(L=>L.role==="user")&&!ot&&!ct){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:bs},He=s.find(fe=>fe.renderLoadingIndicator),Oe=null;if(He!=null&&He.renderLoadingIndicator&&(Oe=He.renderLoadingIndicator(L)),Oe===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Oe=r.loadingIndicator.render(L)),Oe===null&&(Oe=bs()),Oe){let fe=document.createElement("div"),Ot=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;fe.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Oe);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(fe),x.appendChild(Dt)}}if(!kr&&m.length>0){let L=m[m.length-1],He={config:r,lastMessage:L,messageCount:m.length},Oe=s.find(Ot=>Ot.renderIdleIndicator),fe=null;if(Oe!=null&&Oe.renderIdleIndicator&&(fe=Oe.renderIdleIndicator(He)),fe===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=r.loadingIndicator.renderIdle(He)),fe){let Ot=document.createElement("div"),Dt=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;Ot.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ot),x.appendChild(Kt)}}if(ni(c,x),ue.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of ue){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),Ur.set(L,He))}if(Ur.size>0)for(let L of Ur.keys())j.has(L)||Ur.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of ee){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),Lr.set(L,He))}if(Lr.size>0)for(let L of Lr.keys())j.has(L)||Lr.delete(L);if(Ae.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of Ae){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),br.set(L,He))}if(br.size>0)for(let L of br.keys())j.has(L)||br.delete(L)},ro=null,Ma=()=>{var b;if(ro)return;let c=x=>{let T=x.composedPath();T.includes(xe)||Ge&&T.includes(Ge)||Bt(!1,"user")};ro=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Hs=()=>{var m;if(!ro)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",ro,!0),ro=null};gt.push(()=>Hs());let oo=null,ka=()=>{var b;if(oo)return;let c=x=>{x.key==="Escape"&&(x.isComposing||Bt(!1,"user"))};oo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Bs=()=>{var m;if(!oo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",oo,!0),oo=null};gt.push(()=>Bs());let so=!1,Ds=new Set,La=()=>{var m,b,x,T;let c=(x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.peek)==null?void 0:x.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},zr=()=>{var ct,dt,Pe,Le;if(!F())return;let c=Be.peekBanner,m=Be.peekTextNode;if(!c||!m)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let b=(ct=_==null?void 0:_.getMessages())!=null?ct:[],x;for(let je=b.length-1;je>=0;je--){let Qe=b[je];if(Qe.role==="assistant"&&Qe.content){x=Qe;break}}if(!x){c.classList.remove("persona-pill-peek--visible");return}let T=x.content,B=!!x.streaming,O=La(),j=ii(O),H=j.type!=="none"?sa(j.type,O==null?void 0:O.plugins):null,ye=((dt=H==null?void 0:H.isAnimating)==null?void 0:dt.call(H,x))===!0,ue=H!==null&&(B||ye);ue&&H&&!Ds.has(H.name)&&(ml(H,e),Ds.add(H.name));let ee=ue&&(H!=null&&H.containerClass)?H.containerClass:null,Te=(Pe=m.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==ee&&(m.classList.remove(Te),delete m.dataset.personaPeekStreamClass),ee&&Te!==ee&&(m.classList.add(ee),m.dataset.personaPeekStreamClass=ee),ue?(m.style.setProperty("--persona-stream-step",`${j.speed}ms`),m.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let _e=ue?li(T,j.buffer,H,x,B):T;if(ue&&j.placeholder==="skeleton"&&B&&(!_e||!_e.trim())){let je=document.createElement("div"),Qe=ia();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),ni(m,je)}else{let je=Math.max(0,_e.length-100),Qe=_e.length>100?_e.slice(-100):_e,vt=as(Qe);if(!ue||!H){let L=_e.length>100?`\u2026${Qe}`:Qe;m.textContent!==L&&(m.textContent=L)}else{let L=vt;(H.wrap==="char"||H.wrap==="word")&&(L=aa(vt,H.wrap,`peek-${x.id}`,{skipTags:H.skipTags,startIndex:je}));let He=document.createElement("div");if(He.innerHTML=L,H.useCaret&&Qe.length>0){let Oe=ci(),fe=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=fe[fe.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(Oe,Ot.nextSibling):He.appendChild(Oe)}ni(m,He),(Le=H.onAfterRender)==null||Le.call(H,{container:m,bubble:c,messageId:x.id,message:x,speed:j.speed,duration:j.duration})}}let Ve=kr||so;c.classList.toggle("persona-pill-peek--visible",Ve)};if(F()){let c=Be.peekBanner;if(c){let x=T=>{T.preventDefault(),T.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",x),gt.push(()=>{c.removeEventListener("pointerdown",x)})}let m=()=>{so||(so=!0,zr())},b=()=>{so&&(so=!1,zr())};ge.addEventListener("pointerenter",m),ge.addEventListener("pointerleave",b),gt.push(()=>{ge.removeEventListener("pointerenter",m),ge.removeEventListener("pointerleave",b)}),Ge&&(Ge.addEventListener("pointerenter",m),Ge.addEventListener("pointerleave",b),gt.push(()=>{Ge.removeEventListener("pointerenter",m),Ge.removeEventListener("pointerleave",b)}))}let Pa=c=>{var Te,_e,Ae,ot,Ve,ct,dt,Pe;let m=(_e=(Te=r.launcher)==null?void 0:Te.composerBar)!=null?_e:{},b=(Ae=m.expandedSize)!=null?Ae:"anchored",x=(ot=m.bottomOffset)!=null?ot:"16px",T=m.collapsedMaxWidth,B=(Ve=m.expandedMaxWidth)!=null?Ve:"880px",O=(ct=m.expandedTopOffset)!=null?ct:"5vh",j=(dt=m.modalMaxWidth)!=null?dt:"880px",H=(Pe=m.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",ye="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=xe.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ge){let Le=Ge.style;Le.bottom=x,Le.width=T!=null?T:""}if(c&&b!=="fullscreen"){if(b==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=j,ee.maxWidth=ye,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${x} + ${ue})`,ee.top=O,ee.width=B,ee.maxWidth=ye}},ao=()=>{var H,ye,ue,ee,Te,_e,Ae,ot;if(!N())return;if(F()){let ct=(ue=((ye=(H=r.launcher)==null?void 0:H.composerBar)!=null?ye:{}).expandedSize)!=null?ue:"anchored",dt=E?"expanded":"collapsed";xe.dataset.state=dt,xe.dataset.expandedSize=ct,Ge&&(Ge.dataset.state=dt,Ge.dataset.expandedSize=ct),xe.style.removeProperty("display"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(E),z.style.display=E?"flex":"none",fr(),E?(Ma(),ka()):(Hs(),Bs()),zr();return}let c=hn(r),m=(ee=e.ownerDocument.defaultView)!=null?ee:window,b=(_e=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,x=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?ot:!0,T=m.innerWidth<=b,B=x&&T&&A,O=ur(r).reveal;E?(xe.style.removeProperty("display"),xe.style.display=c?"flex":"",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0"),ge.classList.add("persona-scale-100","persona-opacity-100"),rn?rn.element.style.display="none":on&&(on.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!B?(xe.style.removeProperty("display"),xe.style.display="flex",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.setProperty("display","none","important"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.display="",xe.classList.add("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100"),ge.classList.add("persona-scale-95","persona-opacity-0")),rn?rn.element.style.display=c?"none":"":on&&(on.style.display=c?"none":""))},Bt=(c,m="user")=>{var B,O;if(!N()||E===c)return;let b=E;E=c,ao();let x=(()=>{var Ae,ot,Ve,ct,dt,Pe,Le,je,Qe,vt;let j=(ot=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ot:!1,H=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,ye=(dt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,ue=(Le=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Le:640,ee=H.innerWidth<=ue,Te=hn(r)&&ye&&ee,_e=F()&&((vt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return j||ye&&ee&&A||Te||_e})();if(E&&x){if(!tn){let j=e.getRootNode(),H=j instanceof ShadowRoot?j.host:e.closest(".persona-host");H&&(tn=gl(H,(O=(B=r.launcher)==null?void 0:B.zIndex)!=null?O:kn))}nn||(nn=fl(e.ownerDocument))}else E||(tn==null||tn(),tn=null,nn==null||nn(),nn=null);E&&(Ns(),ut()==="follow"?Rr(!0):Rs());let T={open:E,source:m,timestamp:Date.now()};E&&!b?o.emit("widget:opened",T):!E&&b&&o.emit("widget:closed",T),o.emit("widget:state",{open:E,launcherEnabled:A,voiceActive:bt.active,streaming:_.isStreaming()})},Zo=c=>{Yt(c?"stop":"send"),K&&(K.disabled=c),hr.buttons.forEach(m=>{m.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},es=()=>{bt.active||te&&te.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>es(),200)});let Lo=()=>{var b,x,T,B,O,j,H,ye,ue,ee,Te;nr.textContent=(x=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?x:"Hello \u{1F44B}",Sr.textContent=(B=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",te.placeholder=(j=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?j:"How can I help...";let c=pe.querySelector("[data-persona-intro-card]");if(c){let _e=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(pe.classList.remove("persona-gap-3"),pe.classList.add("persona-gap-6")):(pe.classList.remove("persona-gap-6"),pe.classList.add("persona-gap-3"))}!((ue=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&ue)&&!(_!=null&&_.isStreaming())&&(ze.textContent=(Te=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?Te:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let Ue=null,C=()=>{Ue==null&&(Ue=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ue),Ue=null;return}let m=Date.now();c.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ja(m-x))})},100))};if(_=new Zs(r,{onMessagesChanged(c){var x;ko(rt,c,Me),C(),Vo(c),Rr(!kr),Ea(c);let m=[...c].reverse().find(T=>T.role==="user");c.length===0&&Mo(),!Ko||Eo?(Ko=!0,Go=(x=m==null?void 0:m.id)!=null?x:null):m&&m.id!==Go&&(Go=m.id,Ta(m.id));let b=bt.lastUserMessageId;m&&m.id!==b&&(bt.lastUserMessageId=m.id,o.emit("user:message",m)),bt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Xo(c),zr()},onStatusChanged(c){var x;let m=(x=r.statusIndicator)!=null?x:{};Ye(ln,(T=>{var B,O,j,H;return T==="idle"?(B=m.idleText)!=null?B:Mn.idle:T==="connecting"?(O=m.connectingText)!=null?O:Mn.connecting:T==="connected"?(j=m.connectedText)!=null?j:Mn.connected:T==="error"?(H=m.errorText)!=null?H:Mn.error:Mn[T]})(c),m,c)},onStreamingChanged(c){kr=c,Zo(c),_&&ko(rt,_.getMessages(),Me),c||Rr(!0),zr()},onVoiceStatusChanged(c){var m,b;if(((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":io(),kg();break;case"speaking":io(),Lg();break;default:c==="idle"&&_.isBargeInActive()?(io(),Os(),K==null||K.setAttribute("aria-label","End voice session")):(bt.active=!1,io(),ir("system"),Fn());break}},onArtifactsState(c){zn=c,Gn(),Xo()}}),kt.current=_,Ko=!0,((Jc=(Gc=r.voiceRecognition)==null?void 0:Gc.provider)==null?void 0:Jc.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(le||r.onSSEEvent)&&_.setSSEEventCallback((c,m)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,m),me==null||me.processEvent(c,m),le==null||le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,b,x;if(c){if(c.metadata&&(d=Bl(c.metadata),w.syncFromMetadata()),(m=c.messages)!=null&&m.length){Eo=!0;try{_.hydrateMessages(c.messages)}finally{Eo=!1}}(b=c.artifacts)!=null&&b.length&&_.hydrateArtifacts(c.artifacts,(x=c.selectedArtifactId)!=null?x:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let $=()=>{var m,b,x;!F()||E||!((x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.expandOnSubmit)==null||x)||Bt(!0,"auto")},k=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel(),me==null||me.reset(),V==null||V.update();return}let m=te.value.trim(),b=(T=Ct==null?void 0:Ct.hasAttachments())!=null?T:!1;if(!m&&!b)return;$();let x;b&&(x=[],x.push(...Ct.getContentParts()),m&&x.push(Ja(m))),te.value="",te.style.height="auto",Ee(),_.sendMessage(m,{contentParts:x}),b&&Ct.clearAttachments()},Y=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},oe={...ri},G=!1,Ee=()=>{oe={...ri}},Ne=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),lt=c=>{if(!te)return;G=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),G=!1;let m=te.value.length;te.setSelectionRange(m,m)},et=()=>{G||Ee()},Rt=c=>{if(te){if(Y()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=te.selectionStart===0&&te.selectionEnd===0,b=Xu({direction:c.key==="ArrowUp"?"up":"down",history:Ne(),currentValue:te.value,atStart:m,state:oe});if(oe=b.state,b.handled){c.preventDefault(),b.value!==void 0&&lt(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}Ee(),c.preventDefault(),ze.click()}}},_t=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(z)&&(_.cancel(),me==null||me.reset(),V==null||V.update(),Ee(),c.preventDefault(),c.stopImmediatePropagation())},un=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!Ct)return;let m=Rx(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ct.handleFiles(m))},at=null,ft=!1,Zt=null,Ke=null,wn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jt=(c="user")=>{var B,O,j,H,ye,ue,ee;if(ft||_.isStreaming())return;let m=wn();if(!m)return;at=new m;let x=(O=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?O:2e3;at.continuous=!0,at.interimResults=!0,at.lang="en-US";let T=te.value;at.onresult=Te=>{let _e="",Ae="";for(let Ve=0;Ve<Te.results.length;Ve++){let ct=Te.results[Ve],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let ot=T+_e+Ae;te.value=ot,Zt&&clearTimeout(Zt),(_e||Ae)&&(Zt=window.setTimeout(()=>{let Ve=te.value.trim();Ve&&at&&ft&&(yn(),te.value="",te.style.height="auto",_.sendMessage(Ve,{viaVoice:!0}))},x))},at.onerror=Te=>{Te.error!=="no-speech"&&yn()},at.onend=()=>{if(ft){let Te=te.value.trim();Te&&Te!==T.trim()&&(te.value="",te.style.height="auto",_.sendMessage(Te,{viaVoice:!0})),yn()}};try{if(at.start(),ft=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),ir(c),Fn(),K){let Te=(j=r.voiceRecognition)!=null?j:{};Ke={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(H=Te.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ue=Te.iconSize)!=null?ue:(ye=r.sendButton)==null?void 0:ye.size)!=null?ee:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,ot=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let Ve=K.querySelector("svg");Ve&&Ve.setAttribute("stroke",Ae)}ot&&(K.style.borderColor=ot),K.setAttribute("aria-label","Stop voice recognition")}}catch{yn("system")}},yn=(c="user")=>{if(ft){if(ft=!1,Zt&&(clearTimeout(Zt),Zt=null),at){try{at.stop()}catch{}at=null}if(bt.active=!1,ir(c),Fn(),K){if(K.classList.remove("persona-voice-recording"),Ke){K.style.backgroundColor=Ke.backgroundColor,K.style.color=Ke.color,K.style.borderColor=Ke.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",Ke.color||"currentColor"),Ke=null}K.setAttribute("aria-label","Start voice recognition")}}},Mg=(c,m)=>{var ct,dt,Pe,Le,je,Qe,vt,L;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(b||x))return null;let B=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let j=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",H=(Pe=m==null?void 0:m.size)!=null?Pe:"40px",ye=(Le=c==null?void 0:c.iconSize)!=null?Le:H,ue=parseFloat(ye)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:m==null?void 0:m.backgroundColor,Te=(Qe=c==null?void 0:c.iconColor)!=null?Qe:m==null?void 0:m.textColor;O.style.width=ye,O.style.height=ye,O.style.minWidth=ye,O.style.minHeight=ye,O.style.fontSize="18px",O.style.lineHeight="1",Te?O.style.color=Te:O.style.color="var(--persona-text, #111827)";let Ae=Se(j,ue,Te||"currentColor",1.5);Ae?O.appendChild(Ae):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),B.appendChild(O);let ot=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((L=c==null?void 0:c.showTooltip)!=null?L:!1)&&ot){let He=h("div","persona-send-button-tooltip");He.textContent=ot,B.appendChild(He)}return{micButton:O,micButtonWrapper:B}},Ni=()=>{var m,b,x,T,B;if(!K||Ke)return;let c=(m=r.voiceRecognition)!=null?m:{};Ke={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((B=(T=c.iconSize)!=null?T:(x=r.sendButton)==null?void 0:x.size)!=null?B:"40")||24}},Fi=(c,m)=>{var B,O,j,H,ye;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let x=(ye=Ke==null?void 0:Ke.iconSize)!=null?ye:parseFloat((H=(j=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?j:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,T=Se(c,x,m,1.5);T&&K.appendChild(T)},Ia=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Os=()=>{var T;if(!K)return;Ni();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,b=c.recordingIconColor,x=c.recordingBorderColor;if(Ia(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let B=K.querySelector("svg");B&&B.setAttribute("stroke",b)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},kg=()=>{var j,H,ye,ue,ee,Te,_e,Ae;if(!K)return;Ni();let c=(j=r.voiceRecognition)!=null?j:{},m=_.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",x=(ue=(ye=c.processingIconColor)!=null?ye:Ke==null?void 0:Ke.color)!=null?ue:"",T=(Te=(ee=c.processingBackgroundColor)!=null?ee:Ke==null?void 0:Ke.backgroundColor)!=null?Te:"",B=(Ae=(_e=c.processingBorderColor)!=null?_e:Ke==null?void 0:Ke.borderColor)!=null?Ae:"";Ia(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=T,K.style.borderColor=B;let O=x||"currentColor";K.style.color=O,Fi(b,O),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},Lg=()=>{var ye,ue,ee,Te,_e,Ae,ot,Ve,ct,dt,Pe,Le;if(!K)return;Ni();let c=(ye=r.voiceRecognition)!=null?ye:{},m=_.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(ue=c.speakingIconName)!=null?ue:b,T=(Ae=c.speakingIconColor)!=null?Ae:m==="barge-in"?(Te=(ee=c.recordingIconColor)!=null?ee:Ke==null?void 0:Ke.color)!=null?Te:"":(_e=Ke==null?void 0:Ke.color)!=null?_e:"",B=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(Ve=Ke==null?void 0:Ke.backgroundColor)!=null?Ve:"",O=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=Ke==null?void 0:Ke.borderColor)!=null?Pe:"";Ia(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=B,K.style.borderColor=O;let j=T||"currentColor";K.style.color=j,Fi(x,j);let H=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",H),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},io=()=>{var c,m,b;K&&(Ia(),Ke&&(K.style.backgroundColor=(c=Ke.backgroundColor)!=null?c:"",K.style.color=(m=Ke.color)!=null?m:"",K.style.borderColor=(b=Ke.borderColor)!=null?b:"",Fi(Ke.iconName,Ke.color||"currentColor"),Ke=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Ra=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let b=_.getVoiceStatus(),x=_.getVoiceInterruptionMode();if(x==="none"&&(b==="processing"||b==="speaking"))return;if(x==="cancel"&&(b==="processing"||b==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Fn(),ir("user"),io()});return}_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),bt.manuallyDeactivated=!_.isVoiceActive(),Fn(),ir("user"),_.isVoiceActive()?Os():io()});return}if(ft){let b=te.value.trim();bt.manuallyDeactivated=!0,Fn(),yn("user"),b&&(te.value="",te.style.height="auto",_.sendMessage(b))}else bt.manuallyDeactivated=!1,Fn(),Jt("user")};Un=Ra,K&&(K.addEventListener("click",Ra),gt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),io()):yn("system"),K&&K.removeEventListener("click",Ra)}));let Pg=o.on("assistant:complete",()=>{Ts&&(bt.active||bt.manuallyDeactivated||Ts==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!bt.active&&!bt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("auto"),_.isVoiceActive()&&Os()}):Jt("auto"))},600))});gt.push(Pg);let Ig=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});gt.push(Ig);let ts=()=>{Bt(!E,"user")},rn=null,on=null;if(A&&!F()){let c=s.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>da(r,ts).element,onToggle:ts});m&&(on=m)}on||(rn=da(r,ts))}rn?e.appendChild(rn.element):on&&e.appendChild(on),ao(),Vo(),Lo(),Zo(_.isStreaming()),ut()==="follow"?Rr(!0):Rs(),va(),M&&(!A||F()?setTimeout(()=>es(),0):E&&setTimeout(()=>es(),200));let Ns=()=>{var H,ye,ue,ee,Te,_e,Ae,ot,Ve,ct,dt,Pe,Le,je,Qe,vt,L,He,Oe,fe,Ot,Dt;if(F()){bn(),ao();return}let c=hn(r),m=(ye=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?ye:!1,b=c||m||((ee=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),x=(Te=e.ownerDocument.defaultView)!=null?Te:window,T=(Ae=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,B=(Ve=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?Ve:640,O=x.innerWidth<=B,j=T&&O&&A;try{if(j){fr(),$o(e,r);return}if(R&&(R=!1,fr(),$o(e,r)),!A&&!c){ge.style.height="",ge.style.width="";return}if(!m&&!c){let Kt=(dt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?dt:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:pr;ge.style.width=wt,ge.style.maxWidth=wt}if(Mr(),!b){let Kt=x.innerHeight,wt=64,qt=(Le=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?Le:0,Yn=Math.max(200,Kt-wt),an=Math.min(640,Yn),Xe=Math.max(200,an-qt);ge.style.height=`${Xe}px`}}finally{if(bn(),ao(),E&&A){let wt=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((vt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),qt=(He=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?He:!1,Yn=(fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?fe:!0,an=hn(r)&&Yn&&wt,Xe=qt||Yn&&wt&&A||an;if(Xe&&!nn){let Pt=e.getRootNode(),pn=Pt instanceof ShadowRoot?Pt.host:e.closest(".persona-host");pn&&!tn&&(tn=gl(pn,(Dt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Dt:kn)),nn=fl(e.ownerDocument)}else Xe||(tn==null||tn(),tn=null,nn==null||nn(),nn=null)}}};Ns();let Kl=(Qc=e.ownerDocument.defaultView)!=null?Qc:window;if(Kl.addEventListener("resize",Ns),gt.push(()=>Kl.removeEventListener("resize",Ns)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe($e),gt.push(()=>c.disconnect())}Xn=pe.scrollTop;let Gl=Gr(pe),Rg=()=>{let c=pe.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:pe.ownerDocument.getSelection()},_i=()=>rm(Rg(),pe),Jl=()=>{let c=pe.scrollTop,m=Gr(pe),b=m<Gl;if(Gl=m,ut()!=="follow"){Xn=c,_n();return}let{action:x,nextLastScrollTop:T}=si({following:Qn.isFollowing(),currentScrollTop:c,lastScrollTop:Xn,nearBottom:Uo(pe,Jo),userScrollThreshold:ya,isAutoScrolling:xr||To||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=T,x==="resume"){_i()||Ir();return}x==="pause"&&Yo()};if(pe.addEventListener("scroll",Jl,{passive:!0}),gt.push(()=>pe.removeEventListener("scroll",Jl)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Sa()});c.observe(rt),c.observe(pe),gt.push(()=>c.disconnect())}let Ql=()=>{ut()==="follow"&&Qn.isFollowing()&&_i()&&Yo()},Xl=pe.ownerDocument;Xl.addEventListener("selectionchange",Ql),gt.push(()=>{Xl.removeEventListener("selectionchange",Ql)});let Yl=c=>{if(ut()!=="follow")return;let m=ai({following:Qn.isFollowing(),deltaY:c.deltaY,nearBottom:Uo(pe,Jo),resumeWhenNearBottom:!0});m==="pause"?Yo():m==="resume"&&!_i()&&Ir()};pe.addEventListener("wheel",Yl,{passive:!0}),gt.push(()=>pe.removeEventListener("wheel",Yl)),Ze.addEventListener("click",()=>{Mo(),pe.scrollTop=pe.scrollHeight,Xn=pe.scrollTop,Ir(),Rr(!0),_n()}),gt.push(()=>Ze.remove()),gt.push(()=>{Ms(),Mo()});let Zl=()=>{W&&(ar&&(W.removeEventListener("click",ar),ar=null),N()?(W.style.display="",ar=()=>{Bt(!1,"user")},W.addEventListener("click",ar)):W.style.display="none")};Zl(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{_.clearMessages(),$r.clear(),Ir(),No(Be.composerOverlay);try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},w.syncFromMetadata(),le==null||le.clear(),me==null||me.reset(),V==null||V.update()})})(),Wt&&Wt.addEventListener("submit",k),te==null||te.addEventListener("keydown",Rt),te==null||te.addEventListener("input",et),te==null||te.addEventListener("paste",un);let ec=(Xc=e.ownerDocument)!=null?Xc:document;ec.addEventListener("keydown",_t,!0);let tc="persona-attachment-drop-active",Fs=0,$i=()=>{Fs=0,z.classList.remove(tc)},ns=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},nc=c=>{!ki(c.dataTransfer)||!ns()||(Fs++,Fs===1&&z.classList.add(tc))},rc=c=>{!ki(c.dataTransfer)||!ns()||(Fs--,Fs<=0&&$i())},oc=c=>{!ki(c.dataTransfer)||!ns()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},sc=c=>{var b;if(!ki(c.dataTransfer)||!ns())return;c.preventDefault(),c.stopPropagation(),$i();let m=Array.from((b=c.dataTransfer.files)!=null?b:[]);m.length!==0&&Ct.handleFiles(m)},lo=!0;z.addEventListener("dragenter",nc,lo),z.addEventListener("dragleave",rc,lo),e.addEventListener("dragover",oc,lo),e.addEventListener("drop",sc,lo);let Wa=e.ownerDocument,ac=c=>{ns()&&c.preventDefault()},ic=c=>{ns()&&c.preventDefault()};Wa.addEventListener("dragover",ac),Wa.addEventListener("drop",ic),gt.push(()=>{Wt&&Wt.removeEventListener("submit",k),te==null||te.removeEventListener("keydown",Rt),te==null||te.removeEventListener("input",et),te==null||te.removeEventListener("paste",un),ec.removeEventListener("keydown",_t,!0)}),gt.push(()=>{z.removeEventListener("dragenter",nc,lo),z.removeEventListener("dragleave",rc,lo),e.removeEventListener("dragover",oc,lo),e.removeEventListener("drop",sc,lo),Wa.removeEventListener("dragover",ac),Wa.removeEventListener("drop",ic),$i()}),gt.push(()=>{_.cancel()}),rn?gt.push(()=>{rn==null||rn.destroy()}):on&&gt.push(()=>{on==null||on.remove()});let dn={update(c){var Tn,Rn,Wr,xn,Wn,Hn,Ho,_s,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Od,Nd,Fd,_d,$d,Ud,jd,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Op,Np,Fp,_p,$p,Up,jp,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu;let m=r.toolCall,b=r.messageActions,x=(Tn=r.layout)==null?void 0:Tn.messages,T=r.colorScheme,B=r.loadingIndicator,O=r.iterationDisplay,j=(Rn=r.features)==null?void 0:Rn.showReasoning,H=(Wr=r.features)==null?void 0:Wr.showToolCalls,ye=(xn=r.features)==null?void 0:xn.toolCallDisplay,ue=(Wn=r.features)==null?void 0:Wn.reasoningDisplay;r={...r,...c},fr(),$o(e,r),Ai(e,r),Si(e,r),Gn(),r.colorScheme!==T&&to();let ee=Ti.getForInstance(r.plugins);s.length=0,s.push(...ee),A=(Ho=(Hn=r.launcher)==null?void 0:Hn.enabled)!=null?Ho:!0,D=(od=(_s=r.launcher)==null?void 0:_s.autoExpand)!=null?od:!1,qe=(ad=(sd=r.features)==null?void 0:sd.showReasoning)!=null?ad:!0,we=(ld=(id=r.features)==null?void 0:id.showToolCalls)!=null?ld:!0,he=(dd=(cd=r.features)==null?void 0:cd.scrollToBottom)!=null?dd:{};let Te=ut();ke=(ud=(pd=r.features)==null?void 0:pd.scrollBehavior)!=null?ud:{},Te!==ut()&&(Mo(),Ir()),Tr(),_n();let _e=Ie;if(Ie=(gd=(md=r.features)==null?void 0:md.showEventStreamToggle)!=null?gd:!1,Ie&&!_e){if(le||(Q=new fa(ce),le=new ga(ne,Q),me=me!=null?me:new ha,Q.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),_.setSSEEventCallback((J,St)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,J,St),me==null||me.processEvent(J,St),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(St)})})),!xt&&Fe){let J=(hd=(fd=r.features)==null?void 0:fd.eventStream)==null?void 0:hd.classNames,St="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");xt=h("button",St),xt.style.width="28px",xt.style.height="28px",xt.style.color=Dn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Ut=Se("activity","18px","currentColor",1.5);Ut&&xt.appendChild(Ut);let pt=Be.clearChatButtonWrapper,It=Be.closeButtonWrapper,gn=pt||It;gn&&gn.parentNode===Fe?Fe.insertBefore(xt,gn):Fe.appendChild(xt),xt.addEventListener("click",()=>{se?gr():Or()})}}else!Ie&&_e&&(gr(),xt&&(xt.remove(),xt=null),le==null||le.clear(),Q==null||Q.destroy(),le=null,Q=null,me==null||me.reset(),me=null);if(((bd=r.launcher)==null?void 0:bd.enabled)===!1&&rn&&(rn.destroy(),rn=null),((yd=r.launcher)==null?void 0:yd.enabled)===!1&&on&&(on.remove(),on=null),((xd=r.launcher)==null?void 0:xd.enabled)!==!1&&!rn&&!on){let J=s.find(St=>St.renderLauncher);if(J!=null&&J.renderLauncher){let St=J.renderLauncher({config:r,defaultRenderer:()=>da(r,ts).element,onToggle:ts});St&&(on=St,e.appendChild(on))}on||(rn=da(r,ts),e.appendChild(rn.element))}rn&&rn.update(r),De&&((vd=r.launcher)==null?void 0:vd.title)!==void 0&&(De.textContent=r.launcher.title),Je&&((wd=r.launcher)==null?void 0:wd.subtitle)!==void 0&&(Je.textContent=r.launcher.subtitle);let Ae=(Cd=r.layout)==null?void 0:Cd.header;if((Ae==null?void 0:Ae.layout)!==S&&Fe){let J=Ae?pa(r,Ae,{showClose:N(),onClose:()=>Bt(!1,"user")}):vo({config:r,showClose:N(),onClose:()=>Bt(!1,"user")});Fe.replaceWith(J.header),Fe=J.header,de=J.iconHolder,De=J.headerTitle,Je=J.headerSubtitle,W=J.closeButton,S=Ae==null?void 0:Ae.layout}else if(Ae&&(de&&(de.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),Je&&(Je.style.display=Ae.showSubtitle===!1?"none":""),W&&(W.style.display=Ae.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let J=Ae.showClearChat;if(J!==void 0){Be.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:St}=Be;St&&!St.classList.contains("persona-absolute")&&(J?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let Ve=((Ad=r.layout)==null?void 0:Ad.showHeader)!==!1;Fe&&(Fe.style.display=Ve?"":"none");let ct=((Sd=r.layout)==null?void 0:Sd.showFooter)!==!1;$e&&($e.style.display=ct?"":"none"),bn(),_n(),A!==I?A?Bt(D,"auto"):(E=!0,ao()):D!==P&&Bt(D,"auto"),P=D,I=A,Ns(),Zl();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(m),je=JSON.stringify(r.messageActions)!==JSON.stringify(b),Qe=JSON.stringify((Td=r.layout)==null?void 0:Td.messages)!==JSON.stringify(x),vt=((Ed=r.loadingIndicator)==null?void 0:Ed.render)!==(B==null?void 0:B.render)||((Md=r.loadingIndicator)==null?void 0:Md.renderIdle)!==(B==null?void 0:B.renderIdle)||((kd=r.loadingIndicator)==null?void 0:kd.showBubble)!==(B==null?void 0:B.showBubble),L=r.iterationDisplay!==O,He=((Pd=(Ld=r.features)==null?void 0:Ld.showReasoning)!=null?Pd:!0)!==(j!=null?j:!0)||((Rd=(Id=r.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0)!==(H!=null?H:!0)||JSON.stringify((Wd=r.features)==null?void 0:Wd.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((Hd=r.features)==null?void 0:Hd.reasoningDisplay)!==JSON.stringify(ue);(Le||je||Qe||vt||L||He)&&_&&(Ss++,ko(rt,_.getMessages(),Me));let fe=(Bd=r.launcher)!=null?Bd:{},Ot=(Dd=fe.headerIconHidden)!=null?Dd:!1,Dt=(Nd=(Od=r.layout)==null?void 0:Od.header)==null?void 0:Nd.showIcon,Kt=Ot||Dt===!1,wt=fe.headerIconName,qt=(Fd=fe.headerIconSize)!=null?Fd:"48px";if(de){let J=z.querySelector(".persona-border-b-persona-divider"),St=J==null?void 0:J.querySelector(".persona-flex-col");if(Kt)de.style.display="none",J&&St&&!J.contains(St)&&J.insertBefore(St,J.firstChild);else{if(de.style.display="",de.style.height=qt,de.style.width=qt,J&&St&&(J.contains(de)?de.nextSibling!==St&&(de.remove(),J.insertBefore(de,St)):J.insertBefore(de,St)),wt){let pt=parseFloat(qt)||24,It=Se(wt,pt*.6,"#ffffff",2);It?de.replaceChildren(It):de.textContent=(_d=fe.agentIconText)!=null?_d:"\u{1F4AC}"}else if(fe.iconUrl){let pt=de.querySelector("img");if(pt)pt.src=fe.iconUrl,pt.style.height=qt,pt.style.width=qt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=qt,It.style.width=qt,de.replaceChildren(It)}}else{let pt=de.querySelector("svg"),It=de.querySelector("img");(pt||It)&&de.replaceChildren(),de.textContent=($d=fe.agentIconText)!=null?$d:"\u{1F4AC}"}let Ut=de.querySelector("img");Ut&&(Ut.style.height=qt,Ut.style.width=qt)}}let Yn=(jd=(Ud=r.layout)==null?void 0:Ud.header)==null?void 0:jd.showTitle,an=(zd=(qd=r.layout)==null?void 0:qd.header)==null?void 0:zd.showSubtitle;if(De&&(De.style.display=Yn===!1?"none":""),Je&&(Je.style.display=an===!1?"none":""),W){((Kd=(Vd=r.layout)==null?void 0:Vd.header)==null?void 0:Kd.showCloseButton)===!1?W.style.display="none":W.style.display="";let St=(Gd=fe.closeButtonSize)!=null?Gd:"32px",Ut=(Jd=fe.closeButtonPlacement)!=null?Jd:"inline";W.style.height=St,W.style.width=St;let{closeButtonWrapper:pt}=Be,It=Ut==="top-right",gn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&It!==gn)if(pt.remove(),It)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",z.style.position="relative",z.appendChild(pt);else{let mt=(Xd=(Qd=fe.clearChat)==null?void 0:Qd.placement)!=null?Xd:"inline",fn=(Zd=(Yd=fe.clearChat)==null?void 0:Yd.enabled)!=null?Zd:!0;pt.className=fn&&mt==="inline"?"":"persona-ml-auto";let $n=z.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(pt)}if(W.style.color=fe.closeButtonColor||Dn.actionIconColor,fe.closeButtonBackgroundColor?(W.style.backgroundColor=fe.closeButtonBackgroundColor,W.classList.remove("hover:persona-bg-gray-100")):(W.style.backgroundColor="",W.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let mt=fe.closeButtonBorderWidth||"0px",fn=fe.closeButtonBorderColor||"transparent";W.style.border=`${mt} solid ${fn}`,W.classList.remove("persona-border-none")}else W.style.border="",W.classList.add("persona-border-none");fe.closeButtonBorderRadius?(W.style.borderRadius=fe.closeButtonBorderRadius,W.classList.remove("persona-rounded-full")):(W.style.borderRadius="",W.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(W.style.paddingLeft=fe.closeButtonPaddingX,W.style.paddingRight=fe.closeButtonPaddingX):(W.style.paddingLeft="",W.style.paddingRight=""),fe.closeButtonPaddingY?(W.style.paddingTop=fe.closeButtonPaddingY,W.style.paddingBottom=fe.closeButtonPaddingY):(W.style.paddingTop="",W.style.paddingBottom="");let En=(ep=fe.closeButtonIconName)!=null?ep:"x",wr=(tp=fe.closeButtonIconText)!=null?tp:"\xD7";W.innerHTML="";let Bn=Se(En,"28px","currentColor",1);Bn?W.appendChild(Bn):W.textContent=wr;let sn=(np=fe.closeButtonTooltipText)!=null?np:"Close chat",er=(rp=fe.closeButtonShowTooltip)!=null?rp:!0;if(W.setAttribute("aria-label",sn),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),er&&sn)){let mt=null,fn=()=>{if(mt||!W)return;let Bo=W.ownerDocument,$s=Bo.body;if(!$s)return;mt=Hr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=sn;let Us=Hr(Bo,"div");Us.className="persona-clear-chat-tooltip-arrow",mt.appendChild(Us);let Do=W.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(bo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",$s.appendChild(mt)},$n=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};pt.addEventListener("mouseenter",fn),pt.addEventListener("mouseleave",$n),W.addEventListener("focus",fn),W.addEventListener("blur",$n),pt._cleanupTooltip=()=>{$n(),pt&&(pt.removeEventListener("mouseenter",fn),pt.removeEventListener("mouseleave",$n)),W&&(W.removeEventListener("focus",fn),W.removeEventListener("blur",$n))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Pt}=Be;if(Xe){let J=(op=fe.clearChat)!=null?op:{},St=(sp=J.enabled)!=null?sp:!0,Ut=(ip=(ap=r.layout)==null?void 0:ap.header)==null?void 0:ip.showClearChat,pt=Ut!==void 0?Ut:St,It=(lp=J.placement)!=null?lp:"inline";if(Pt){Pt.style.display=pt?"":"none";let{closeButtonWrapper:gn}=Be;!F()&&gn&&!gn.classList.contains("persona-absolute")&&(pt?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let En=It==="top-right",wr=Pt.classList.contains("persona-absolute");if(!F()&&En!==wr&&pt){if(Pt.remove(),En)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",z.style.position="relative",z.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let sn=z.querySelector(".persona-border-b-persona-divider"),er=Be.closeButtonWrapper;sn&&er&&er.parentElement===sn?sn.insertBefore(Pt,er):sn&&sn.appendChild(Pt)}let Bn=Be.closeButtonWrapper;Bn&&!Bn.classList.contains("persona-absolute")&&(En?Bn.classList.add("persona-ml-auto"):Bn.classList.remove("persona-ml-auto"))}}if(pt){if(!F()){let mt=(cp=J.size)!=null?cp:"32px";Xe.style.height=mt,Xe.style.width=mt}let gn=(dp=J.iconName)!=null?dp:"refresh-cw",En=(pp=J.iconColor)!=null?pp:"";Xe.style.color=En||Dn.actionIconColor,Xe.innerHTML="";let wr=F()?"14px":"20px",Bn=Se(gn,wr,"currentColor",2);if(Bn&&Xe.appendChild(Bn),J.backgroundColor?(Xe.style.backgroundColor=J.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let mt=J.borderWidth||"0px",fn=J.borderColor||"transparent";Xe.style.border=`${mt} solid ${fn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");J.borderRadius?(Xe.style.borderRadius=J.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),J.paddingX?(Xe.style.paddingLeft=J.paddingX,Xe.style.paddingRight=J.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),J.paddingY?(Xe.style.paddingTop=J.paddingY,Xe.style.paddingBottom=J.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let sn=(up=J.tooltipText)!=null?up:"Clear chat",er=(mp=J.showTooltip)!=null?mp:!0;if(Xe.setAttribute("aria-label",sn),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),er&&sn)){let mt=null,fn=()=>{if(mt||!Xe)return;let Bo=Xe.ownerDocument,$s=Bo.body;if(!$s)return;mt=Hr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=sn;let Us=Hr(Bo,"div");Us.className="persona-clear-chat-tooltip-arrow",mt.appendChild(Us);let Do=Xe.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(bo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",$s.appendChild(mt)},$n=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};Pt.addEventListener("mouseenter",fn),Pt.addEventListener("mouseleave",$n),Xe.addEventListener("focus",fn),Xe.addEventListener("blur",$n),Pt._cleanupTooltip=()=>{$n(),Pt&&(Pt.removeEventListener("mouseenter",fn),Pt.removeEventListener("mouseleave",$n)),Xe&&(Xe.removeEventListener("focus",fn),Xe.removeEventListener("blur",$n))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ei],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ws.message,ws.messageAndClick];w=Mi({parsers:pn,handlers:cr,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Me=qm(r,w,re),_.updateConfig(r),ko(rt,_.getMessages(),Me),Vo(),Lo(),Zo(_.isStreaming());let Zn=((gp=r.voiceRecognition)==null?void 0:gp.enabled)===!0,Po=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Io=((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype";if(Zn&&(Po||Io))if(!K||!yt){let J=Mg(r.voiceRecognition,r.sendButton);J&&(K=J.micButton,yt=J.micButtonWrapper,zt.insertBefore(yt,On),K.addEventListener("click",Ra),K.disabled=_.isStreaming())}else{let J=(bp=r.voiceRecognition)!=null?bp:{},St=(yp=r.sendButton)!=null?yp:{},Ut=(xp=J.iconName)!=null?xp:"mic",pt=(vp=St.size)!=null?vp:"40px",It=(wp=J.iconSize)!=null?wp:pt,gn=parseFloat(It)||24;K.style.width=It,K.style.height=It,K.style.minWidth=It,K.style.minHeight=It;let En=(Ap=(Cp=J.iconColor)!=null?Cp:St.textColor)!=null?Ap:"currentColor";K.innerHTML="";let wr=Se(Ut,gn,En,2);wr?K.appendChild(wr):K.textContent="\u{1F3A4}";let Bn=(Sp=J.backgroundColor)!=null?Sp:St.backgroundColor;Bn?K.style.backgroundColor=Bn:K.style.backgroundColor="",En?K.style.color=En:K.style.color="var(--persona-text, #111827)",J.borderWidth?(K.style.borderWidth=J.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),J.borderColor?K.style.borderColor=J.borderColor:K.style.borderColor="",J.paddingX?(K.style.paddingLeft=J.paddingX,K.style.paddingRight=J.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),J.paddingY?(K.style.paddingTop=J.paddingY,K.style.paddingBottom=J.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let sn=yt==null?void 0:yt.querySelector(".persona-send-button-tooltip"),er=(Tp=J.tooltipText)!=null?Tp:"Start voice recognition";if(((Ep=J.showTooltip)!=null?Ep:!1)&&er)if(sn)sn.textContent=er,sn.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=er,yt==null||yt.insertBefore(fn,K)}else sn&&(sn.style.display="none");yt.style.display="",K.disabled=_.isStreaming()}else K&&yt&&(yt.style.display="none",((kp=(Mp=r.voiceRecognition)==null?void 0:Mp.provider)==null?void 0:kp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():ft&&yn());if(((Lp=r.attachments)==null?void 0:Lp.enabled)===!0)if(!ve||!it){let J=(Pp=r.attachments)!=null?Pp:{},Ut=(Rp=((Ip=r.sendButton)!=null?Ip:{}).size)!=null?Rp:"40px";tt||(tt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),tt.style.display="none",Wt.insertBefore(tt,te)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Wp=J.allowedTypes)!=null?Wp:Kr).join(","),ie.multiple=((Hp=J.maxFiles)!=null?Hp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Wt.insertBefore(ie,te)),ve=h("div","persona-send-button-wrapper"),it=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(Bp=J.buttonTooltipText)!=null?Bp:"Attach file");let pt=(Dp=J.buttonIconName)!=null?Dp:"paperclip",It=Ut,gn=parseFloat(It)||40,En=Math.round(gn*.6);it.style.width=It,it.style.height=It,it.style.minWidth=It,it.style.minHeight=It,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let wr=Se(pt,En,"currentColor",1.5);wr?it.appendChild(wr):it.textContent="\u{1F4CE}",it.addEventListener("click",er=>{er.preventDefault(),ie==null||ie.click()}),ve.appendChild(it);let Bn=(Op=J.buttonTooltipText)!=null?Op:"Attach file",sn=h("div","persona-send-button-tooltip");sn.textContent=Bn,ve.appendChild(sn),Lt.append(ve),!Ct&&ie&&tt&&(Ct=gs.fromConfig(J),Ct.setPreviewsContainer(tt),ie.addEventListener("change",async()=>{Ct&&(ie!=null&&ie.files)&&(await Ct.handleFileSelect(ie.files),ie.value="")})),z.querySelector(".persona-attachment-drop-overlay")||z.appendChild(zm(J.dropOverlay))}else{ve.style.display="";let J=(Np=r.attachments)!=null?Np:{};ie&&(ie.accept=((Fp=J.allowedTypes)!=null?Fp:Kr).join(","),ie.multiple=((_p=J.maxFiles)!=null?_p:4)>1),Ct&&Ct.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else ve&&(ve.style.display="none"),Ct&&Ct.clearAttachments(),($p=z.querySelector(".persona-attachment-drop-overlay"))==null||$p.remove();let Qt=(Up=r.sendButton)!=null?Up:{},Ro=(jp=Qt.useIcon)!=null?jp:!1,co=(qp=Qt.iconText)!=null?qp:"\u2191",po=Qt.iconName,Vr=(zp=Qt.tooltipText)!=null?zp:"Send message",Wo=(Vp=Qt.showTooltip)!=null?Vp:!1,vr=(Kp=Qt.size)!=null?Kp:"40px",nt=Qt.backgroundColor,mn=Qt.textColor;if(Ro){if(ze.style.width=vr,ze.style.height=vr,ze.style.minWidth=vr,ze.style.minHeight=vr,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",mn?ze.style.color=mn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",po){let J=parseFloat(vr)||24,St=(mn==null?void 0:mn.trim())||"currentColor",Ut=Se(po,J,St,2);Ut?ze.appendChild(Ut):ze.textContent=co}else ze.textContent=co;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nt?(ze.style.backgroundColor=nt,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(Jp=(Gp=r.copy)==null?void 0:Gp.sendButtonLabel)!=null?Jp:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nt?(ze.style.backgroundColor=nt,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),mn?ze.style.color=mn:ze.classList.add("persona-text-white");Qt.borderWidth?(ze.style.borderWidth=Qt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Qt.borderColor?ze.style.borderColor=Qt.borderColor:ze.style.borderColor="",Qt.paddingX?(ze.style.paddingLeft=Qt.paddingX,ze.style.paddingRight=Qt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Qt.paddingY?(ze.style.paddingTop=Qt.paddingY,ze.style.paddingBottom=Qt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let $t=On==null?void 0:On.querySelector(".persona-send-button-tooltip");if(Wo&&Vr)if($t)$t.textContent=Vr,$t.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Vr,On==null||On.insertBefore(J,ze)}else $t&&($t.style.display="none");let Nt=(eu=(Qp=r.layout)==null?void 0:Qp.contentMaxWidth)!=null?eu:F()?(Zp=(Yp=(Xp=r.launcher)==null?void 0:Xp.composerBar)==null?void 0:Yp.contentMaxWidth)!=null?Zp:"720px":void 0;Nt?(rt.style.maxWidth=Nt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",Wt&&(Wt.style.maxWidth=Nt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Tt&&(Tt.style.maxWidth=Nt,Tt.style.marginLeft="auto",Tt.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Tt&&(Tt.style.maxWidth="",Tt.style.marginLeft="",Tt.style.marginRight=""));let ht=(tu=r.statusIndicator)!=null?tu:{},Xt=(nu=ht.visible)!=null?nu:!0;if(ln.style.display=Xt?"":"none",_){let J=_.getStatus();Ye(ln,(Ut=>{var pt,It,gn,En;return Ut==="idle"?(pt=ht.idleText)!=null?pt:Mn.idle:Ut==="connecting"?(It=ht.connectingText)!=null?It:Mn.connecting:Ut==="connected"?(gn=ht.connectedText)!=null?gn:Mn.connected:Ut==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[Ut]})(J),ht,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Mt)},open(){N()&&Bt(!0,"api")},close(){N()&&Bt(!1,"api")},toggle(){N()&&Bt(!E,"api")},clearChat(){Pn=!1,_.clearMessages(),$r.clear(),Ir();try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},w.syncFromMetadata(),le==null||le.clear(),me==null||me.reset(),V==null||V.update()},setMessage(c){return!te||_.isStreaming()?!1:(!E&&N()&&Bt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let m=(c==null?void 0:c.trim())||te.value.trim();return m?(!E&&N()&&Bt(!0,"system"),te.value="",te.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,b;return _.isStreaming()?!1:((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype"?(_.isVoiceActive()||(!E&&N()&&Bt(!0,"system"),bt.manuallyDeactivated=!1,Fn(),_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("user"),_.isVoiceActive()&&Os()})),!0):ft?!0:wn()?(!E&&N()&&Bt(!0,"system"),bt.manuallyDeactivated=!1,Fn(),Jt("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Fn(),ir("user"),io()}),!0):!1:ft?(bt.manuallyDeactivated=!0,Fn(),yn("user"),!0):!1},injectMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!E&&N()&&Bt(!0,"system");let m=_.injectAssistantMessage(c);return U&&(U=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!E&&N()&&Bt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!E&&N()&&Bt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!E&&N()&&Bt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,m){return _.connectStream(c,m)},__pushEventStreamEvent(c){le&&(me==null||me.processEvent(c.type,c.payload),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ie||!le||Or()},hideEventStream(){se&&gr()},isEventStreamVisible(){return se},showArtifacts(){mr(r)&&(Pn=!1,Gn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){mr(r)&&(Pn=!0,Gn())},upsertArtifact(c){return mr(r)?(Pn=!1,_.upsertArtifact(c)):null},selectArtifact(c){mr(r)&&_.selectArtifact(c)},clearArtifacts(){mr(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!E&&!F()||!te?!1:(te.focus(),!0)},async resolveApproval(c,m,b){let T=_.getMessages().find(B=>{var O;return B.variant==="approval"&&((O=B.approval)==null?void 0:O.id)===c});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${c}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,m);return}return _.resolveApproval(T.approval,m,b)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return o.on(c,m)},off(c,m){o.off(c,m)},isOpen(){return N()&&E},isVoiceActive(){return bt.active},getState(){return{open:N()&&E,launcherEnabled:A,voiceActive:bt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!E&&N()&&Bt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let b=Wl({onSubmit:async(x,T)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(x,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,x,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&N()&&Bt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let b=Hl({onSubmit:async(x,T)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(x,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,x,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return _.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return _.submitNPSFeedback(c,m)},destroy(){Ue!=null&&(clearInterval(Ue),Ue=null),gt.forEach(c=>c()),xe.remove(),Ge==null||Ge.remove(),rn==null||rn.destroy(),on==null||on.remove(),ar&&W.removeEventListener("click",ar)}};if((((Yc=n==null?void 0:n.debugTools)!=null?Yc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:b=>b?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,gt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",m),gt.push(()=>{window.removeEventListener("persona:focusInput",m)}),Ie){let j=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&dn.showEventStream()},H=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",H),gt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",H)})}let b=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.showArtifacts()},x=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.hideArtifacts()},T=j=>{let H=j.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&dn.upsertArtifact(H.artifact)},B=j=>{let H=j.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&dn.selectArtifact(H.id)},O=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",O),gt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",O)})}let lr=Wx(r.persistState);if(lr&&N()){let c=Hx(lr.storage),m=`${lr.keyPrefix}widget-open`,b=`${lr.keyPrefix}widget-voice`,x=`${lr.keyPrefix}widget-voice-mode`;if(c){let T=((Zc=lr.persist)==null?void 0:Zc.openState)&&c.getItem(m)==="true",B=((ed=lr.persist)==null?void 0:ed.voiceState)&&c.getItem(b)==="true",O=((td=lr.persist)==null?void 0:td.voiceState)&&c.getItem(x)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var j;if(B||O)dn.startVoiceRecognition();else if((j=lr.persist)!=null&&j.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(nd=lr.persist)!=null&&nd.openState&&(o.on("widget:opened",()=>{c.setItem(m,"true")}),o.on("widget:closed",()=>{c.setItem(m,"false")})),(rd=lr.persist)!=null&&rd.voiceState&&(o.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),o.on("user:message",j=>{c.setItem(x,j.viaVoice?"true":"false")})),lr.clearOnChatClear){let j=()=>{c.removeItem(m),c.removeItem(b),c.removeItem(x)},H=()=>j();window.addEventListener("persona:clear-chat",H),gt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&N()&&setTimeout(()=>{dn.open()},0),zr(),dn};var Bx=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Dx=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Ox=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nx=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Vm=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},_l=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Km=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",_l(e)},Ol=e=>{e.style.transition=""},Nl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform=""},Fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Li=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Fx=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},_x=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Gm=(e,t,n,r,s,o,a)=>{var v,y,w,A,D,M;let i=ur(o),d=i.reveal==="push";Fx(e,t,n,r,d),_x(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(y=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?y:!0,u=(A=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Ol(r),Km(r),Fl(n),Li(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((M=(D=o==null?void 0:o.launcher)==null?void 0:D.zIndex)!=null?M:kn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Km(r),Dx(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Nl(t),Ol(r),Fl(n),Li(s,r);let P=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=P,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ol(r),_l(r),Li(s,r);let P=Bx(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),S=i.animate?"transform 180ms ease":"none",R=i.side==="right"?a?`translateX(-${P}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${P}px)`;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+P}px`,t.style.transition=S,t.style.transform=R,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Nl(t),_l(r),Fl(n),Li(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",Ox(r,i.maxHeight),r.style.overflow=P||R?"hidden":"visible",r.style.transition=S,P&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},$x=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Vm(n,r)},destroy(){n.remove()}}},Ux=(e,t)=>{var M,P,I,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(P=(M=t==null?void 0:t.launcher)==null?void 0:M.enabled)==null||P?(S=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),ur(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Gm(a,i,d,l,p,t,u)}),f.observe(a))},y=!1,w=()=>{Gm(a,i,d,l,p,t,u),v(),u&&!y&&a.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,Nx(a,ur(t)))},A=a.ownerDocument.defaultView,D=()=>{w()};return A==null||A.addEventListener("resize",D),ur(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),w(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,w())},updateConfig(R){var F,N;t=R,((N=(F=t==null?void 0:t.launcher)==null?void 0:F.enabled)!=null?N:!0)===!1&&(u=!0),w()},destroy(){A==null||A.removeEventListener("resize",D),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Pi=(e,t)=>hn(t)?Ux(e,t):$x(e,t);var $l={},Jm=!1,jx=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},qx=()=>{try{if(typeof $l!="undefined"&&$l.url)return new URL("../widget.css",$l.url).href}catch{}return null},Qm=(e,t)=>{let n=qx(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Xm=e=>{let t=jx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=Pi(t,s),a,i=[],d=(w,A)=>{var I,S;let M=!((S=(I=A==null?void 0:A.launcher)==null?void 0:I.enabled)!=null?S:!0)||hn(A),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),M&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let R=w.attachShadow({mode:"open"});R.appendChild(P),Qm(R,r)}else w.appendChild(P),Qm(w,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(o.host,s);a=Dl(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(Jm||(Jm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let g=w=>{f(),o.destroy(),o=Pi(t,w),s=w,u()},v={update(w){var S,R,F,N,E,U;let A={...s,...w,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(R=w==null?void 0:w.launcher)!=null?R:{},dock:{...(N=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?N:{},...(U=(E=w==null?void 0:w.launcher)==null?void 0:E.dock)!=null?U:{}}}},D=hn(s),M=hn(A),P=xo(s),I=xo(A);if(D!==M||P!==I){g(A);return}s=A,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(v,{get(w,A,D){if(A==="host")return o.host;if(A in w)return Reflect.get(w,A,D);let M=a[A];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var ng=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zx=new Set(["button","a","input","select","textarea","details","summary"]),Vx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ul=/\b(product|card|item|listing|result)\b/i,ql=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Kx=3e3,Gx=100;function rg(e){let t=typeof e.className=="string"?e.className:"";if(Ul.test(t)||e.id&&Ul.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ul.test(r.value))return!0}return!1}function og(e){var t;return ql.test(((t=e.textContent)!=null?t:"").trim())}function sg(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Jx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ym(e){let t=e.match(ql);return t?t[0]:null}function Zm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Qx(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Xx="commerce-card",Yx="result-card";function eg(e){return!rg(e)||!og(e)||!sg(e)&&!Jx(e)?0:5200}function tg(e){var r;return!rg(e)||og(e)||!sg(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ag=[{id:Xx,scoreElement(e){return eg(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||ql.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(eg(e)===0)return null;let{title:n,href:r}=Zm(e),s=(p=(l=Ym(((d=e.textContent)!=null?d:"").trim()))!=null?l:Ym(t.text))!=null?p:"",o=Qx(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
107
+ `}if(!x&&!c){let $t="max-height: -moz-available !important; max-height: stretch !important;",Nt=m?"":"padding-top: 1.25em !important;",ht=m?"":`z-index: ${(mn=(nt=r.launcher)==null?void 0:nt.zIndex)!=null?mn:kn} !important;`;xe.style.cssText+=$t+Nt+ht}Qe()};fr(),$o(e,r),Ai(e,r),Si(e,r);let gt=[];gt.push(()=>{document.removeEventListener("keydown",Yr)});let tn=null,nn=null;gt.push(()=>{tn==null||tn(),tn=null,nn==null||nn(),nn=null}),qn&&gt.push(()=>{qn==null||qn.disconnect(),qn=null}),gt.push(()=>{In==null||In(),In=null,_r(),Ht&&(Ht.remove(),Ht=null),At==null||At.element.style.removeProperty("width"),At==null||At.element.style.removeProperty("maxWidth")}),Ie&&gt.push(()=>{We!==null&&(cancelAnimationFrame(We),We=null),V==null||V.destroy(),V=null,le==null||le.destroy(),le=null,Q=null});let Jn=null,to=()=>{Jn&&(Jn(),Jn=null),r.colorScheme==="auto"&&(Jn=dl(()=>{$o(e,r)}))};to(),gt.push(()=>{Jn&&(Jn(),Jn=null)});let be=(zc=r.features)==null?void 0:zc.streamAnimation;if(be!=null&&be.type&&be.type!=="none"){let c=sa(be.type,be.plugins);c&&(ml(c,e),gt.push(()=>lm(e)))}let hr=Em(Tt),ar=null,_,Vo=c=>{var x,T;if(!_)return;let m=c!=null?c:_.getMessages(),b=((T=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:T.enabled)!==!1?Yi(m):null;b?hr.render(b,_,te,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(B=>B.role==="user")?hr.render([],_,te,m):hr.render(r.suggestionChips,_,te,m,r.suggestionChipsConfig)},kr=!1,$r=Zu(),Ur=new Map,Lr=new Map,br=new Map,Ss=0,Qn=oi(),Xn=0,yr=null,xr=!1,To=!1,jr=0,Sn=null,Pr=null,Ko=!1,Eo=!1,Go=null,ya=4,Jo=24,xa=80,Qo=new Map,bt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Ts=(Kc=(Vc=r.voiceRecognition)==null?void 0:Vc.autoResume)!=null?Kc:!1,ir=c=>{o.emit("voice:state",{active:bt.active,source:c,timestamp:Date.now()})},Fn=()=>{g(c=>({...c,voiceState:{active:bt.active,timestamp:Date.now(),manuallyDeactivated:bt.manuallyDeactivated}}))},va=()=>{var x,T;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let c=Bl(d.voiceState),m=!!c.active,b=Number((T=c.timestamp)!=null?T:0);bt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-b<Px&&setTimeout(()=>{var B,O;bt.active||(bt.manuallyDeactivated=!1,((O=(B=r.voiceRecognition)==null?void 0:B.provider)==null?void 0:O.type)==="runtype"?_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("restore"),_.isVoiceActive()&&Os()}):Jt("restore"))},1e3)},wa=()=>_?jm(_.getMessages()).filter(c=>!c.__skipPersist):[];function Xo(c){if(!(i!=null&&i.save))return;let b={messages:c?jm(c):_?wa():[],metadata:d,artifacts:zn.artifacts,selectedArtifactId:zn.selectedId};try{let x=i.save(b);x instanceof Promise&&x.catch(T=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",T)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let qr=null,Es=()=>xe.querySelector("#persona-scroll-container")||pe,no=()=>{qr!==null&&(cancelAnimationFrame(qr),qr=null),xr=!1},Ms=()=>{yr!==null&&(cancelAnimationFrame(yr),yr=null),To=!1,no()},ks=()=>{jr>0?(Cn.textContent=String(jr),Cn.style.display="",Ze.setAttribute("aria-label",`${Vt()||"Jump to latest"} (${jr} new)`)):(Cn.textContent="",Cn.style.display="none",Ze.setAttribute("aria-label",Vt()||"Jump to latest"))},Ls=()=>{jr!==0&&(jr=0,ks())},Ps=()=>ut()==="follow"?!Qn.isFollowing():!Uo(pe,Jo),_n=()=>{if(!vn()||se){Ze.parentNode&&Ze.remove(),Ze.style.display="none";return}Ze.parentNode!==z&&z.appendChild(Ze),bn();let m=Gr(pe)>0&&Ps();m||Ls(),Ze.style.display=m?"":"none"},Yo=()=>{Qn.pause()&&(Ms(),_n())},Ir=()=>{Qn.resume(),Ls(),_n()},Rr=(c=!1)=>{ut()==="follow"&&Qn.isFollowing()&&(!c&&!kr||(yr!==null&&(cancelAnimationFrame(yr),yr=null),To=!0,yr=requestAnimationFrame(()=>{yr=null,To=!1,Qn.isFollowing()&&Ca(Es(),c?220:140)})))},Is=(c,m,b,x=()=>!0)=>{let T=c.scrollTop,B=m(),O=B-T;no();let j=performance.now();xr=!0;let H=ue=>1-Math.pow(1-ue,3),ye=ue=>{if(!x()){no();return}let ee=m();ee!==B&&(B=ee,O=B-T);let Te=ue-j,_e=Math.min(Te/b,1),Ae=H(_e),ot=T+O*Ae;c.scrollTop=ot,Xn=c.scrollTop,_e<1?qr=requestAnimationFrame(ye):(c.scrollTop=B,Xn=c.scrollTop,qr=null,xr=!1)};qr=requestAnimationFrame(ye)},Ca=(c,m=500)=>{let b=Gr(c)-c.scrollTop;if(Math.abs(b)<1){Xn=c.scrollTop;return}if(Math.abs(b)>=xa){no(),xr=!0,c.scrollTop=Gr(c),Xn=c.scrollTop,xr=!1;return}Is(c,()=>Gr(c),m,()=>Qn.isFollowing())},Rs=()=>{let c=Es();xr=!0,c.scrollTop=Gr(c),Xn=c.scrollTop,xr=!1,_n()},Ws=c=>{An.style.height=`${Math.max(0,Math.round(c))}px`,Sn&&(Sn.spacerHeight=Math.max(0,c))},Mo=()=>{Pr!==null&&(cancelAnimationFrame(Pr),Pr=null),no(),Sn=null,An.style.height="0px"},Aa=c=>{Pr!==null&&cancelAnimationFrame(Pr),Pr=requestAnimationFrame(()=>{var ye;Pr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=pe.querySelector(`[data-message-id="${m}"]`);if(!b)return;let x=0,T=b;for(;T&&T!==pe;)x+=T.offsetTop,T=T.offsetParent;let B=(ye=Sn==null?void 0:Sn.spacerHeight)!=null?ye:0,O=pe.scrollHeight-B,{targetScrollTop:j,spacerHeight:H}=om({anchorOffsetTop:x,topOffset:Et(),viewportHeight:pe.clientHeight,contentHeight:O});Sn={initialSpacerHeight:H,contentHeightAtAnchor:O,spacerHeight:H},Ws(H),Is(pe,()=>j,220)})},Sa=()=>{if(ut()==="follow"){if(!Qn.isFollowing()||Uo(pe,1))return;Rr(!kr);return}if(Sn&&Sn.initialSpacerHeight>0){let c=pe.scrollHeight-Sn.spacerHeight,m=sm({initialSpacerHeight:Sn.initialSpacerHeight,contentHeightAtAnchor:Sn.contentHeightAtAnchor,currentContentHeight:c});m!==Sn.spacerHeight&&Ws(m)}_n()},Ta=c=>{let m=ut();m==="follow"?(Ir(),Rr(!0)):m==="anchor-top"&&Aa(c)},Ea=c=>{let m=new Map;c.forEach(b=>{let x=Qo.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(o.emit("assistant:message",b),!Eo&&ut()!=="anchor-top"&&Ps()&&(jr+=1,ks(),_n())),b.role==="assistant"&&(x!=null&&x.streaming)&&b.streaming===!1&&o.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&o.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):o.emit("approval:requested",{approval:b.approval,message:b}))}),Qo.clear(),m.forEach((b,x)=>{Qo.set(x,b)})},ko=(c,m,b)=>{var dt,Pe,Le,je,Qe,vt;let x=document.createElement("div"),B=(()=>{var He;let L=s.find(Oe=>Oe.renderLoadingIndicator);if(L!=null&&L.renderLoadingIndicator)return L.renderLoadingIndicator;if((He=r.loadingIndicator)!=null&&He.render)return r.loadingIndicator.render})(),O=(L,He)=>He==null?!1:typeof He=="string"?(L.textContent=He,!0):(L.appendChild(He),!0),j=new Set,H=new Set,ye=s.some(L=>L.renderAskUserQuestion),ue=[],ee=[],Te=r.enableComponentStreaming!==!1,_e=s.some(L=>L.renderApproval)&&r.approval!==!1,Ae=[];if(m.forEach(L=>{var Xe,Pt,pn,cr,Zn,Po,Io,rs,os,Qt,Ro,co,po,Vr,Wo,vr;j.add(L.id);let He=ye&&mo(L),Oe=_e&&L.variant==="approval"&&!!L.approval,fe=!He&&L.role==="assistant"&&!L.variant&&Te&&Il(L);if(!Oe&&br.has(L.id)){let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),br.delete(L.id)}if(!fe&&Lr.has(L.id)){let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime"),Lr.delete(L.id)}let Ot=mo(L)?`:${(Xe=L.agentMetadata)!=null&&Xe.askUserQuestionAnswered?"a":"u"}:${(Pt=L.agentMetadata)!=null&&Pt.askUserQuestionAnswers?Object.keys(L.agentMetadata.askUserQuestionAnswers).length:0}`:"",Dt=Yu(L,Ss)+Ot,Kt=He||Oe||fe?null:em($r,L.id,Dt);if(Kt){x.appendChild(Kt.cloneNode(!0)),mo(L)&&((pn=L.toolCall)!=null&&pn.id)&&((cr=L.agentMetadata)==null?void 0:cr.awaitingLocalTool)===!0&&!((Zn=L.agentMetadata)!=null&&Zn.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}let wt=null,qt=s.find(nt=>!!(L.variant==="reasoning"&&nt.renderReasoning||L.variant==="tool"&&nt.renderToolCall||!L.variant&&nt.renderMessage)),Yn=(Po=r.layout)==null?void 0:Po.messages;if(mo(L)&&((Io=L.agentMetadata)==null?void 0:Io.askUserQuestionAnswered)===!0){Ur.delete(L.id);let nt=c.querySelector(`#wrapper-${L.id}`);nt==null||nt.removeAttribute("data-preserve-runtime");return}if(_a(L)&&((os=(rs=r.features)==null?void 0:rs.suggestReplies)==null?void 0:os.enabled)!==!1)return;if(mo(L)&&((Ro=(Qt=r.features)==null?void 0:Qt.askUserQuestion)==null?void 0:Ro.enabled)!==!1){let nt=s.find(mn=>typeof mn.renderAskUserQuestion=="function");if(nt&&kt.current){let mn=Ur.get(L.id),$t=mn!==Dt,Nt=null;if($t){let{payload:Mt,complete:Tn}=go(L),Rn=L.id,Wr=()=>{var xn;return(xn=kt.current)==null?void 0:xn.getMessages().find(Wn=>Wn.id===Rn)};Nt=nt.renderAskUserQuestion({message:L,payload:Mt,complete:Tn,resolve:xn=>{var Hn;let Wn=Wr();Wn&&((Hn=kt.current)==null||Hn.resolveAskUserQuestion(Wn,xn))},dismiss:()=>{var Wn,Hn,Ho;let xn=Wr();(Wn=xn==null?void 0:xn.agentMetadata)!=null&&Wn.awaitingLocalTool&&((Hn=kt.current)==null||Hn.markAskUserQuestionResolved(xn),(Ho=kt.current)==null||Ho.resolveAskUserQuestion(xn,"(dismissed)"))},config:r})}let ht=mn!=null;if($t&&Nt===null&&!ht){((co=L.agentMetadata)==null?void 0:co.awaitingLocalTool)===!0&&!((po=L.agentMetadata)!=null&&po.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),Xt.setAttribute("data-ask-plugin-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),x.appendChild(Xt),ue.push({messageId:L.id,fingerprint:Dt,bubble:Nt});return}else{((Vr=L.agentMetadata)==null?void 0:Vr.awaitingLocalTool)===!0&&!((Wo=L.agentMetadata)!=null&&Wo.askUserQuestionAnswered)&&(H.add(L.toolCall.id),Ks(L,r,Be.composerOverlay));return}}else if(Oe){let nt=s.find(ht=>typeof ht.renderApproval=="function"),$t=br.get(L.id)!==Dt,Nt=null;if($t&&(nt!=null&&nt.renderApproval)){let ht=L.id,Xt=(Mt,Tn)=>{var Wr,xn,Wn;let Rn=(Wr=kt.current)==null?void 0:Wr.getMessages().find(Hn=>Hn.id===ht);Rn!=null&&Rn.approval&&(Rn.approval.toolType==="webmcp"?(xn=kt.current)==null||xn.resolveWebMcpApproval(Rn.id,Mt):(Wn=kt.current)==null||Wn.resolveApproval(Rn.approval,Mt,Tn))};Nt=nt.renderApproval({message:L,defaultRenderer:()=>wi(L,r),config:r,approve:Mt=>Xt("approved",Mt),deny:Mt=>Xt("denied",Mt)})}if($t&&Nt===null){let ht=c.querySelector(`#wrapper-${L.id}`);ht==null||ht.removeAttribute("data-preserve-runtime"),br.delete(L.id),wt=wi(L,r)}else{let ht=document.createElement("div");ht.className="persona-flex",ht.id=`wrapper-${L.id}`,ht.setAttribute("data-wrapper-id",L.id),ht.setAttribute("data-approval-plugin-stub","true"),ht.setAttribute("data-preserve-runtime","true"),x.appendChild(ht),Ae.push({messageId:L.id,fingerprint:Dt,bubble:Nt});return}}else if(qt)if(L.variant==="reasoning"&&L.reasoning&&qt.renderReasoning){if(!qe)return;wt=qt.renderReasoning({message:L,defaultRenderer:()=>vl(L,r),config:r})}else if(L.variant==="tool"&&L.toolCall&&qt.renderToolCall){if(!we)return;wt=qt.renderToolCall({message:L,defaultRenderer:()=>wl(L,r),config:r})}else qt.renderMessage&&(wt=qt.renderMessage({message:L,defaultRenderer:()=>{let nt=ma(L,b,Yn,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r});return L.role!=="user"&&Tl(nt,L,r,_),nt},config:r}));if(!wt&&fe){let nt=Rl(L);if(nt){let mn=Lr.get(L.id),$t=mn!==Dt,Nt=r.wrapComponentDirectiveInBubble!==!1,ht=null;if($t){let Xt=Pl(nt,{config:r,message:L,transform:b});if(Xt)if(Nt){let Mt=document.createElement("div");if(Mt.className=["persona-message-bubble","persona-max-w-[85%]","persona-rounded-2xl","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-p-4"].join(" "),Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),L.content&&L.content.trim()){let Tn=document.createElement("div");Tn.className="persona-mb-3 persona-text-sm persona-leading-relaxed",Tn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Tn)}Mt.appendChild(Xt),ht=Mt}else{let Mt=document.createElement("div");if(Mt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",Mt.id=`bubble-${L.id}`,Mt.setAttribute("data-message-id",L.id),Mt.setAttribute("data-persona-component-directive","true"),L.content&&L.content.trim()){let Tn=document.createElement("div");Tn.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",Tn.innerHTML=b({text:L.content,message:L,streaming:!!L.streaming,raw:L.rawContent}),Mt.appendChild(Tn)}Mt.appendChild(Xt),ht=Mt}}if(ht||mn!=null){let Xt=document.createElement("div");Xt.className="persona-flex",Xt.id=`wrapper-${L.id}`,Xt.setAttribute("data-wrapper-id",L.id),Xt.setAttribute("data-component-directive-stub","true"),Xt.setAttribute("data-preserve-runtime","true"),Nt||Xt.classList.add("persona-w-full"),x.appendChild(Xt),ee.push({messageId:L.id,fingerprint:Dt,bubble:ht});return}}}if(!wt)if(L.variant==="reasoning"&&L.reasoning){if(!qe)return;wt=vl(L,r)}else if(L.variant==="tool"&&L.toolCall){if(!we)return;wt=wl(L,r)}else if(L.variant==="approval"&&L.approval){if(r.approval===!1)return;wt=wi(L,r)}else{let nt=(vr=r.layout)==null?void 0:vr.messages;nt!=null&&nt.renderUserMessage&&L.role==="user"?wt=nt.renderUserMessage({message:L,config:r,streaming:!!L.streaming}):nt!=null&&nt.renderAssistantMessage&&L.role==="assistant"?wt=nt.renderAssistantMessage({message:L,config:r,streaming:!!L.streaming}):wt=ma(L,b,nt,r.messageActions,Z,{loadingIndicatorRenderer:B,widgetConfig:r}),L.role!=="user"&&wt&&Tl(wt,L,r,_)}let an=document.createElement("div");an.className="persona-flex",an.id=`wrapper-${L.id}`,an.setAttribute("data-wrapper-id",L.id),L.role==="user"&&an.classList.add("persona-justify-end"),(wt==null?void 0:wt.getAttribute("data-persona-component-directive"))==="true"&&an.classList.add("persona-w-full"),an.appendChild(wt),tm($r,L.id,Dt,an),x.appendChild(an)}),Be.composerOverlay&&Be.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(He=>{let Oe=He.getAttribute("data-persona-ask-sheet-for");Oe&&!H.has(Oe)&&No(Be.composerOverlay,Oe)}),(Pe=(dt=r.features)==null?void 0:dt.toolCallDisplay)!=null&&Pe.grouped){let L=[],He=[];m.forEach(Oe=>{if(Oe.variant==="tool"&&Oe.toolCall&&we){He.push(Oe);return}He.length>1&&L.push(He),He=[]}),He.length>1&&L.push(He),L.forEach((Oe,fe)=>{var Xe,Pt;let Ot=Oe.map(pn=>Array.from(x.children).find(cr=>cr instanceof HTMLElement&&cr.getAttribute("data-wrapper-id")===pn.id)).filter(pn=>!!pn);if(Ot.length<2)return;let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id=`wrapper-tool-group-${fe}-${Oe[0].id}`,Dt.setAttribute("data-wrapper-id",`tool-group-${fe}-${Oe[0].id}`);let Kt=document.createElement("div");Kt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Kt.setAttribute("data-persona-tool-group","true");let wt=document.createElement("div");wt.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let qt=`Called ${Oe.length} tools`,Yn=(Pt=(Xe=r.toolCall)==null?void 0:Xe.renderGroupedSummary)==null?void 0:Pt.call(Xe,{messages:Oe,toolCalls:Oe.map(pn=>pn.toolCall).filter(pn=>!!pn),defaultSummary:qt,config:r});O(wt,Yn)||(wt.textContent=qt);let an=document.createElement("div");an.className="persona-tool-group-stack persona-flex persona-flex-col",Kt.append(wt,an),Dt.appendChild(Kt),Ot[0].before(Dt),Ot.forEach((pn,cr)=>{let Zn=document.createElement("div");Zn.className="persona-tool-group-item persona-relative",Zn.setAttribute("data-persona-tool-group-item","true"),cr<Ot.length-1&&Zn.setAttribute("data-persona-tool-group-connector","true"),Zn.appendChild(pn),an.appendChild(Zn)})})}nm($r,j);let ot=m.some(L=>L.role==="assistant"&&L.streaming),Ve=m[m.length-1],ct=(Ve==null?void 0:Ve.role)==="assistant"&&!Ve.streaming&&Ve.variant!=="approval";if(kr&&m.some(L=>L.role==="user")&&!ot&&!ct){let L={config:r,streaming:!0,location:"standalone",defaultRenderer:bs},He=s.find(fe=>fe.renderLoadingIndicator),Oe=null;if(He!=null&&He.renderLoadingIndicator&&(Oe=He.renderLoadingIndicator(L)),Oe===null&&((Le=r.loadingIndicator)!=null&&Le.render)&&(Oe=r.loadingIndicator.render(L)),Oe===null&&(Oe=bs()),Oe){let fe=document.createElement("div"),Ot=((je=r.loadingIndicator)==null?void 0:je.showBubble)!==!1;fe.className=Ot?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),fe.setAttribute("data-typing-indicator","true"),fe.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",fe.appendChild(Oe);let Dt=document.createElement("div");Dt.className="persona-flex",Dt.id="wrapper-typing-indicator",Dt.setAttribute("data-wrapper-id","typing-indicator"),Dt.appendChild(fe),x.appendChild(Dt)}}if(!kr&&m.length>0){let L=m[m.length-1],He={config:r,lastMessage:L,messageCount:m.length},Oe=s.find(Ot=>Ot.renderIdleIndicator),fe=null;if(Oe!=null&&Oe.renderIdleIndicator&&(fe=Oe.renderIdleIndicator(He)),fe===null&&((Qe=r.loadingIndicator)!=null&&Qe.renderIdle)&&(fe=r.loadingIndicator.renderIdle(He)),fe){let Ot=document.createElement("div"),Dt=((vt=r.loadingIndicator)==null?void 0:vt.showBubble)!==!1;Ot.className=Dt?["persona-max-w-[85%]","persona-rounded-2xl","persona-text-sm","persona-leading-relaxed","persona-shadow-sm","persona-bg-persona-surface","persona-border","persona-border-persona-message-border","persona-text-persona-primary","persona-px-5","persona-py-3"].join(" "):["persona-max-w-[85%]","persona-text-sm","persona-leading-relaxed","persona-text-persona-primary"].join(" "),Ot.setAttribute("data-idle-indicator","true"),Ot.appendChild(fe);let Kt=document.createElement("div");Kt.className="persona-flex",Kt.id="wrapper-idle-indicator",Kt.setAttribute("data-wrapper-id","idle-indicator"),Kt.appendChild(Ot),x.appendChild(Kt)}}if(ni(c,x),ue.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of ue){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),Ur.set(L,He))}if(Ur.size>0)for(let L of Ur.keys())j.has(L)||Ur.delete(L);if(ee.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of ee){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),Lr.set(L,He))}if(Lr.size>0)for(let L of Lr.keys())j.has(L)||Lr.delete(L);if(Ae.length>0)for(let{messageId:L,fingerprint:He,bubble:Oe}of Ae){let fe=c.querySelector(`#wrapper-${L}`);fe&&Oe!==null&&(fe.replaceChildren(Oe),fe.setAttribute("data-bubble-fp",He),br.set(L,He))}if(br.size>0)for(let L of br.keys())j.has(L)||br.delete(L)},ro=null,Ma=()=>{var b;if(ro)return;let c=x=>{let T=x.composedPath();T.includes(xe)||Ge&&T.includes(Ge)||Bt(!1,"user")};ro=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Hs=()=>{var m;if(!ro)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",ro,!0),ro=null};gt.push(()=>Hs());let oo=null,ka=()=>{var b;if(oo)return;let c=x=>{x.key==="Escape"&&(x.isComposing||Bt(!1,"user"))};oo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Bs=()=>{var m;if(!oo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",oo,!0),oo=null};gt.push(()=>Bs());let so=!1,Ds=new Set,La=()=>{var m,b,x,T;let c=(x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.peek)==null?void 0:x.streamAnimation;return c||((T=r.features)==null?void 0:T.streamAnimation)},zr=()=>{var ct,dt,Pe,Le;if(!F())return;let c=Be.peekBanner,m=Be.peekTextNode;if(!c||!m)return;if(E){c.classList.remove("persona-pill-peek--visible");return}let b=(ct=_==null?void 0:_.getMessages())!=null?ct:[],x;for(let je=b.length-1;je>=0;je--){let Qe=b[je];if(Qe.role==="assistant"&&Qe.content){x=Qe;break}}if(!x){c.classList.remove("persona-pill-peek--visible");return}let T=x.content,B=!!x.streaming,O=La(),j=ii(O),H=j.type!=="none"?sa(j.type,O==null?void 0:O.plugins):null,ye=((dt=H==null?void 0:H.isAnimating)==null?void 0:dt.call(H,x))===!0,ue=H!==null&&(B||ye);ue&&H&&!Ds.has(H.name)&&(ml(H,e),Ds.add(H.name));let ee=ue&&(H!=null&&H.containerClass)?H.containerClass:null,Te=(Pe=m.dataset.personaPeekStreamClass)!=null?Pe:null;Te&&Te!==ee&&(m.classList.remove(Te),delete m.dataset.personaPeekStreamClass),ee&&Te!==ee&&(m.classList.add(ee),m.dataset.personaPeekStreamClass=ee),ue?(m.style.setProperty("--persona-stream-step",`${j.speed}ms`),m.style.setProperty("--persona-stream-duration",`${j.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let _e=ue?li(T,j.buffer,H,x,B):T;if(ue&&j.placeholder==="skeleton"&&B&&(!_e||!_e.trim())){let je=document.createElement("div"),Qe=ia();Qe.classList.add("persona-pill-peek__skeleton"),je.appendChild(Qe),ni(m,je)}else{let je=Math.max(0,_e.length-100),Qe=_e.length>100?_e.slice(-100):_e,vt=as(Qe);if(!ue||!H){let L=_e.length>100?`\u2026${Qe}`:Qe;m.textContent!==L&&(m.textContent=L)}else{let L=vt;(H.wrap==="char"||H.wrap==="word")&&(L=aa(vt,H.wrap,`peek-${x.id}`,{skipTags:H.skipTags,startIndex:je}));let He=document.createElement("div");if(He.innerHTML=L,H.useCaret&&Qe.length>0){let Oe=ci(),fe=He.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ot=fe[fe.length-1];Ot!=null&&Ot.parentNode?Ot.parentNode.insertBefore(Oe,Ot.nextSibling):He.appendChild(Oe)}ni(m,He),(Le=H.onAfterRender)==null||Le.call(H,{container:m,bubble:c,messageId:x.id,message:x,speed:j.speed,duration:j.duration})}}let Ve=kr||so;c.classList.toggle("persona-pill-peek--visible",Ve)};if(F()){let c=Be.peekBanner;if(c){let x=T=>{T.preventDefault(),T.stopPropagation(),Bt(!0,"user")};c.addEventListener("pointerdown",x),gt.push(()=>{c.removeEventListener("pointerdown",x)})}let m=()=>{so||(so=!0,zr())},b=()=>{so&&(so=!1,zr())};ge.addEventListener("pointerenter",m),ge.addEventListener("pointerleave",b),gt.push(()=>{ge.removeEventListener("pointerenter",m),ge.removeEventListener("pointerleave",b)}),Ge&&(Ge.addEventListener("pointerenter",m),Ge.addEventListener("pointerleave",b),gt.push(()=>{Ge.removeEventListener("pointerenter",m),Ge.removeEventListener("pointerleave",b)}))}let Pa=c=>{var Te,_e,Ae,ot,Ve,ct,dt,Pe;let m=(_e=(Te=r.launcher)==null?void 0:Te.composerBar)!=null?_e:{},b=(Ae=m.expandedSize)!=null?Ae:"anchored",x=(ot=m.bottomOffset)!=null?ot:"16px",T=m.collapsedMaxWidth,B=(Ve=m.expandedMaxWidth)!=null?Ve:"880px",O=(ct=m.expandedTopOffset)!=null?ct:"5vh",j=(dt=m.modalMaxWidth)!=null?dt:"880px",H=(Pe=m.modalMaxHeight)!=null?Pe:"min(90vh, 800px)",ye="calc(100vw - 32px)",ue="var(--persona-pill-area-height, 80px)",ee=xe.style;if(ee.left="",ee.right="",ee.top="",ee.bottom="",ee.transform="",ee.width="",ee.maxWidth="",ee.height="",ee.maxHeight="",Ge){let Le=Ge.style;Le.bottom=x,Le.width=T!=null?T:""}if(c&&b!=="fullscreen"){if(b==="modal"){ee.top="50%",ee.left="50%",ee.transform="translate(-50%, -50%)",ee.bottom="auto",ee.right="auto",ee.width=j,ee.maxWidth=ye,ee.maxHeight=H,ee.height=H;return}ee.left="50%",ee.transform="translateX(-50%)",ee.bottom=`calc(${x} + ${ue})`,ee.top=O,ee.width=B,ee.maxWidth=ye}},ao=()=>{var H,ye,ue,ee,Te,_e,Ae,ot;if(!N())return;if(F()){let ct=(ue=((ye=(H=r.launcher)==null?void 0:H.composerBar)!=null?ye:{}).expandedSize)!=null?ue:"anchored",dt=E?"expanded":"collapsed";xe.dataset.state=dt,xe.dataset.expandedSize=ct,Ge&&(Ge.dataset.state=dt,Ge.dataset.expandedSize=ct),xe.style.removeProperty("display"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Pa(E),z.style.display=E?"flex":"none",fr(),E?(Ma(),ka()):(Hs(),Bs()),zr();return}let c=hn(r),m=(ee=e.ownerDocument.defaultView)!=null?ee:window,b=(_e=(Te=r.launcher)==null?void 0:Te.mobileBreakpoint)!=null?_e:640,x=(ot=(Ae=r.launcher)==null?void 0:Ae.mobileFullscreen)!=null?ot:!0,T=m.innerWidth<=b,B=x&&T&&A,O=ur(r).reveal;E?(xe.style.removeProperty("display"),xe.style.display=c?"flex":"",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-95","persona-opacity-0"),ge.classList.add("persona-scale-100","persona-opacity-100"),rn?rn.element.style.display="none":on&&(on.style.display="none")):(c?c&&(O==="overlay"||O==="push")&&!B?(xe.style.removeProperty("display"),xe.style.display="flex",xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.setProperty("display","none","important"),xe.classList.remove("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(xe.style.display="",xe.classList.add("persona-pointer-events-none","persona-opacity-0"),ge.classList.remove("persona-scale-100","persona-opacity-100"),ge.classList.add("persona-scale-95","persona-opacity-0")),rn?rn.element.style.display=c?"none":"":on&&(on.style.display=c?"none":""))},Bt=(c,m="user")=>{var B,O;if(!N()||E===c)return;let b=E;E=c,ao();let x=(()=>{var Ae,ot,Ve,ct,dt,Pe,Le,je,Qe,vt;let j=(ot=(Ae=r.launcher)==null?void 0:Ae.sidebarMode)!=null?ot:!1,H=(Ve=e.ownerDocument.defaultView)!=null?Ve:window,ye=(dt=(ct=r.launcher)==null?void 0:ct.mobileFullscreen)!=null?dt:!0,ue=(Le=(Pe=r.launcher)==null?void 0:Pe.mobileBreakpoint)!=null?Le:640,ee=H.innerWidth<=ue,Te=hn(r)&&ye&&ee,_e=F()&&((vt=(Qe=(je=r.launcher)==null?void 0:je.composerBar)==null?void 0:Qe.expandedSize)!=null?vt:"fullscreen")==="fullscreen";return j||ye&&ee&&A||Te||_e})();if(E&&x){if(!tn){let j=e.getRootNode(),H=j instanceof ShadowRoot?j.host:e.closest(".persona-host");H&&(tn=gl(H,(O=(B=r.launcher)==null?void 0:B.zIndex)!=null?O:kn))}nn||(nn=fl(e.ownerDocument))}else E||(tn==null||tn(),tn=null,nn==null||nn(),nn=null);E&&(Ns(),ut()==="follow"?Rr(!0):Rs());let T={open:E,source:m,timestamp:Date.now()};E&&!b?o.emit("widget:opened",T):!E&&b&&o.emit("widget:closed",T),o.emit("widget:state",{open:E,launcherEnabled:A,voiceActive:bt.active,streaming:_.isStreaming()})},Zo=c=>{Yt(c?"stop":"send"),K&&(K.disabled=c),hr.buttons.forEach(m=>{m.disabled=c}),$e.dataset.personaComposerStreaming=c?"true":"false",$e.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},es=()=>{bt.active||te&&te.focus()};o.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>es(),200)});let Lo=()=>{var b,x,T,B,O,j,H,ye,ue,ee,Te;nr.textContent=(x=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?x:"Hello \u{1F44B}",Sr.textContent=(B=(T=r.copy)==null?void 0:T.welcomeSubtitle)!=null?B:"Ask anything about your account or products.",te.placeholder=(j=(O=r.copy)==null?void 0:O.inputPlaceholder)!=null?j:"How can I help...";let c=pe.querySelector("[data-persona-intro-card]");if(c){let _e=((H=r.copy)==null?void 0:H.showWelcomeCard)!==!1;c.style.display=_e?"":"none",_e?(pe.classList.remove("persona-gap-3"),pe.classList.add("persona-gap-6")):(pe.classList.remove("persona-gap-6"),pe.classList.add("persona-gap-3"))}!((ue=(ye=r.sendButton)==null?void 0:ye.useIcon)!=null&&ue)&&!(_!=null&&_.isStreaming())&&(ze.textContent=(Te=(ee=r.copy)==null?void 0:ee.sendButtonLabel)!=null?Te:"Send"),te.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',te.style.fontWeight="var(--persona-input-font-weight, var(--persona-font-weight, 400))"};r.clientToken&&(r={...r,getStoredSessionId:()=>{let c=d.sessionId;return typeof c=="string"?c:null},setStoredSessionId:c=>{g(m=>({...m,sessionId:c}))}});let Ue=null,C=()=>{Ue==null&&(Ue=setInterval(()=>{let c=rt.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(Ue),Ue=null;return}let m=Date.now();c.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ja(m-x))})},100))};if(_=new Zs(r,{onMessagesChanged(c){var x;ko(rt,c,Me),C(),Vo(c),Rr(!kr),Ea(c);let m=[...c].reverse().find(T=>T.role==="user");c.length===0&&Mo(),!Ko||Eo?(Ko=!0,Go=(x=m==null?void 0:m.id)!=null?x:null):m&&m.id!==Go&&(Go=m.id,Ta(m.id));let b=bt.lastUserMessageId;m&&m.id!==b&&(bt.lastUserMessageId=m.id,o.emit("user:message",m)),bt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),Xo(c),zr()},onStatusChanged(c){var x;let m=(x=r.statusIndicator)!=null?x:{};Ye(ln,(T=>{var B,O,j,H;return T==="idle"?(B=m.idleText)!=null?B:Mn.idle:T==="connecting"?(O=m.connectingText)!=null?O:Mn.connecting:T==="connected"?(j=m.connectedText)!=null?j:Mn.connected:T==="error"?(H=m.errorText)!=null?H:Mn.error:Mn[T]})(c),m,c)},onStreamingChanged(c){kr=c,Zo(c),_&&ko(rt,_.getMessages(),Me),c||Rr(!0),zr()},onVoiceStatusChanged(c){var m,b;if(((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype")switch(c){case"listening":break;case"processing":io(),kg();break;case"speaking":io(),Lg();break;default:c==="idle"&&_.isBargeInActive()?(io(),Os(),K==null||K.setAttribute("aria-label","End voice session")):(bt.active=!1,io(),ir("system"),Fn());break}},onArtifactsState(c){zn=c,Gn(),Xo()}}),kt.current=_,Ko=!0,((Jc=(Gc=r.voiceRecognition)==null?void 0:Gc.provider)==null?void 0:Jc.type)==="runtype")try{_.setupVoice()}catch(c){typeof console!="undefined"&&console.warn("[AgentWidget] Runtype voice setup failed:",c)}r.clientToken&&_.initClientSession().catch(c=>{r.debug&&console.warn("[AgentWidget] Pre-init client session failed:",c)}),(le||r.onSSEEvent)&&_.setSSEEventCallback((c,m)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,m),me==null||me.processEvent(c,m),le==null||le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c,timestamp:Date.now(),payload:JSON.stringify(m)})}),l&&l.then(c=>{var m,b,x;if(c){if(c.metadata&&(d=Bl(c.metadata),w.syncFromMetadata()),(m=c.messages)!=null&&m.length){Eo=!0;try{_.hydrateMessages(c.messages)}finally{Eo=!1}}(b=c.artifacts)!=null&&b.length&&_.hydrateArtifacts(c.artifacts,(x=c.selectedArtifactId)!=null?x:null)}}).catch(c=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to hydrate stored state:",c)});let $=()=>{var m,b,x;!F()||E||!((x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.expandOnSubmit)==null||x)||Bt(!0,"auto")},k=c=>{var T;if(c.preventDefault(),_.isStreaming()){_.cancel(),me==null||me.reset(),V==null||V.update();return}let m=te.value.trim(),b=(T=Ct==null?void 0:Ct.hasAttachments())!=null?T:!1;if(!m&&!b)return;$();let x;b&&(x=[],x.push(...Ct.getContentParts()),m&&x.push(Ja(m))),te.value="",te.style.height="auto",Ee(),_.sendMessage(m,{contentParts:x}),b&&Ct.clearAttachments()},Y=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},oe={...ri},G=!1,Ee=()=>{oe={...ri}},Ne=()=>_.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),lt=c=>{if(!te)return;G=!0,te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),G=!1;let m=te.value.length;te.setSelectionRange(m,m)},et=()=>{G||Ee()},Rt=c=>{if(te){if(Y()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=te.selectionStart===0&&te.selectionEnd===0,b=Xu({direction:c.key==="ArrowUp"?"up":"down",history:Ne(),currentValue:te.value,atStart:m,state:oe});if(oe=b.state,b.handled){c.preventDefault(),b.value!==void 0&&lt(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if(_.isStreaming()){c.preventDefault();return}Ee(),c.preventDefault(),ze.click()}}},_t=c=>{c.key!=="Escape"||c.isComposing||_.isStreaming()&&c.composedPath().includes(z)&&(_.cancel(),me==null||me.reset(),V==null||V.update(),Ee(),c.preventDefault(),c.stopImmediatePropagation())},un=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!Ct)return;let m=Rx(c.clipboardData);m.length!==0&&(c.preventDefault(),await Ct.handleFiles(m))},at=null,ft=!1,Zt=null,Ke=null,wn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Jt=(c="user")=>{var B,O,j,H,ye,ue,ee;if(ft||_.isStreaming())return;let m=wn();if(!m)return;at=new m;let x=(O=((B=r.voiceRecognition)!=null?B:{}).pauseDuration)!=null?O:2e3;at.continuous=!0,at.interimResults=!0,at.lang="en-US";let T=te.value;at.onresult=Te=>{let _e="",Ae="";for(let Ve=0;Ve<Te.results.length;Ve++){let ct=Te.results[Ve],dt=ct[0].transcript;ct.isFinal?_e+=dt+" ":Ae=dt}let ot=T+_e+Ae;te.value=ot,Zt&&clearTimeout(Zt),(_e||Ae)&&(Zt=window.setTimeout(()=>{let Ve=te.value.trim();Ve&&at&&ft&&(yn(),te.value="",te.style.height="auto",_.sendMessage(Ve,{viaVoice:!0}))},x))},at.onerror=Te=>{Te.error!=="no-speech"&&yn()},at.onend=()=>{if(ft){let Te=te.value.trim();Te&&Te!==T.trim()&&(te.value="",te.style.height="auto",_.sendMessage(Te,{viaVoice:!0})),yn()}};try{if(at.start(),ft=!0,bt.active=!0,c!=="system"&&(bt.manuallyDeactivated=!1),ir(c),Fn(),K){let Te=(j=r.voiceRecognition)!=null?j:{};Ke={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(H=Te.iconName)!=null?H:"mic",iconSize:parseFloat((ee=(ue=Te.iconSize)!=null?ue:(ye=r.sendButton)==null?void 0:ye.size)!=null?ee:"40")||24};let _e=Te.recordingBackgroundColor,Ae=Te.recordingIconColor,ot=Te.recordingBorderColor;if(K.classList.add("persona-voice-recording"),K.style.backgroundColor=_e!=null?_e:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=Ae!=null?Ae:"var(--persona-voice-recording-indicator, #ffffff)",Ae){let Ve=K.querySelector("svg");Ve&&Ve.setAttribute("stroke",Ae)}ot&&(K.style.borderColor=ot),K.setAttribute("aria-label","Stop voice recognition")}}catch{yn("system")}},yn=(c="user")=>{if(ft){if(ft=!1,Zt&&(clearTimeout(Zt),Zt=null),at){try{at.stop()}catch{}at=null}if(bt.active=!1,ir(c),Fn(),K){if(K.classList.remove("persona-voice-recording"),Ke){K.style.backgroundColor=Ke.backgroundColor,K.style.color=Ke.color,K.style.borderColor=Ke.borderColor;let m=K.querySelector("svg");m&&m.setAttribute("stroke",Ke.color||"currentColor"),Ke=null}K.setAttribute("aria-label","Start voice recognition")}}},Mg=(c,m)=>{var ct,dt,Pe,Le,je,Qe,vt,L;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((ct=c==null?void 0:c.provider)==null?void 0:ct.type)==="runtype";if(!(b||x))return null;let B=h("div","persona-send-button-wrapper"),O=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");O.type="button",O.setAttribute("aria-label","Start voice recognition");let j=(dt=c==null?void 0:c.iconName)!=null?dt:"mic",H=(Pe=m==null?void 0:m.size)!=null?Pe:"40px",ye=(Le=c==null?void 0:c.iconSize)!=null?Le:H,ue=parseFloat(ye)||24,ee=(je=c==null?void 0:c.backgroundColor)!=null?je:m==null?void 0:m.backgroundColor,Te=(Qe=c==null?void 0:c.iconColor)!=null?Qe:m==null?void 0:m.textColor;O.style.width=ye,O.style.height=ye,O.style.minWidth=ye,O.style.minHeight=ye,O.style.fontSize="18px",O.style.lineHeight="1",Te?O.style.color=Te:O.style.color="var(--persona-text, #111827)";let Ae=Se(j,ue,Te||"currentColor",1.5);Ae?O.appendChild(Ae):O.textContent="\u{1F3A4}",ee?O.style.backgroundColor=ee:O.style.backgroundColor="",c!=null&&c.borderWidth&&(O.style.borderWidth=c.borderWidth,O.style.borderStyle="solid"),c!=null&&c.borderColor&&(O.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(O.style.paddingLeft=c.paddingX,O.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(O.style.paddingTop=c.paddingY,O.style.paddingBottom=c.paddingY),B.appendChild(O);let ot=(vt=c==null?void 0:c.tooltipText)!=null?vt:"Start voice recognition";if(((L=c==null?void 0:c.showTooltip)!=null?L:!1)&&ot){let He=h("div","persona-send-button-tooltip");He.textContent=ot,B.appendChild(He)}return{micButton:O,micButtonWrapper:B}},Ni=()=>{var m,b,x,T,B;if(!K||Ke)return;let c=(m=r.voiceRecognition)!=null?m:{};Ke={backgroundColor:K.style.backgroundColor,color:K.style.color,borderColor:K.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((B=(T=c.iconSize)!=null?T:(x=r.sendButton)==null?void 0:x.size)!=null?B:"40")||24}},Fi=(c,m)=>{var B,O,j,H,ye;if(!K)return;let b=K.querySelector("svg");b&&b.remove();let x=(ye=Ke==null?void 0:Ke.iconSize)!=null?ye:parseFloat((H=(j=(B=r.voiceRecognition)==null?void 0:B.iconSize)!=null?j:(O=r.sendButton)==null?void 0:O.size)!=null?H:"40")||24,T=Se(c,x,m,1.5);T&&K.appendChild(T)},Ia=()=>{K&&K.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Os=()=>{var T;if(!K)return;Ni();let c=(T=r.voiceRecognition)!=null?T:{},m=c.recordingBackgroundColor,b=c.recordingIconColor,x=c.recordingBorderColor;if(Ia(),K.classList.add("persona-voice-recording"),K.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",K.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let B=K.querySelector("svg");B&&B.setAttribute("stroke",b)}x&&(K.style.borderColor=x),K.setAttribute("aria-label","Stop voice recognition")},kg=()=>{var j,H,ye,ue,ee,Te,_e,Ae;if(!K)return;Ni();let c=(j=r.voiceRecognition)!=null?j:{},m=_.getVoiceInterruptionMode(),b=(H=c.processingIconName)!=null?H:"loader",x=(ue=(ye=c.processingIconColor)!=null?ye:Ke==null?void 0:Ke.color)!=null?ue:"",T=(Te=(ee=c.processingBackgroundColor)!=null?ee:Ke==null?void 0:Ke.backgroundColor)!=null?Te:"",B=(Ae=(_e=c.processingBorderColor)!=null?_e:Ke==null?void 0:Ke.borderColor)!=null?Ae:"";Ia(),K.classList.add("persona-voice-processing"),K.style.backgroundColor=T,K.style.borderColor=B;let O=x||"currentColor";K.style.color=O,Fi(b,O),K.setAttribute("aria-label","Processing voice input"),m==="none"&&(K.style.cursor="default")},Lg=()=>{var ye,ue,ee,Te,_e,Ae,ot,Ve,ct,dt,Pe,Le;if(!K)return;Ni();let c=(ye=r.voiceRecognition)!=null?ye:{},m=_.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(ue=c.speakingIconName)!=null?ue:b,T=(Ae=c.speakingIconColor)!=null?Ae:m==="barge-in"?(Te=(ee=c.recordingIconColor)!=null?ee:Ke==null?void 0:Ke.color)!=null?Te:"":(_e=Ke==null?void 0:Ke.color)!=null?_e:"",B=(ct=c.speakingBackgroundColor)!=null?ct:m==="barge-in"?(ot=c.recordingBackgroundColor)!=null?ot:"var(--persona-voice-recording-bg, #ef4444)":(Ve=Ke==null?void 0:Ke.backgroundColor)!=null?Ve:"",O=(Le=c.speakingBorderColor)!=null?Le:m==="barge-in"?(dt=c.recordingBorderColor)!=null?dt:"":(Pe=Ke==null?void 0:Ke.borderColor)!=null?Pe:"";Ia(),K.classList.add("persona-voice-speaking"),K.style.backgroundColor=B,K.style.borderColor=O;let j=T||"currentColor";K.style.color=j,Fi(x,j);let H=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";K.setAttribute("aria-label",H),m==="none"&&(K.style.cursor="default"),m==="barge-in"&&K.classList.add("persona-voice-recording")},io=()=>{var c,m,b;K&&(Ia(),Ke&&(K.style.backgroundColor=(c=Ke.backgroundColor)!=null?c:"",K.style.color=(m=Ke.color)!=null?m:"",K.style.borderColor=(b=Ke.borderColor)!=null?b:"",Fi(Ke.iconName,Ke.color||"currentColor"),Ke=null),K.style.cursor="",K.setAttribute("aria-label","Start voice recognition"))},Ra=()=>{var c,m;if(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"){let b=_.getVoiceStatus(),x=_.getVoiceInterruptionMode();if(x==="none"&&(b==="processing"||b==="speaking"))return;if(x==="cancel"&&(b==="processing"||b==="speaking")){_.stopVoicePlayback();return}if(_.isBargeInActive()){_.stopVoicePlayback(),_.deactivateBargeIn().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Fn(),ir("user"),io()});return}_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),bt.manuallyDeactivated=!_.isVoiceActive(),Fn(),ir("user"),_.isVoiceActive()?Os():io()});return}if(ft){let b=te.value.trim();bt.manuallyDeactivated=!0,Fn(),yn("user"),b&&(te.value="",te.style.height="auto",_.sendMessage(b))}else bt.manuallyDeactivated=!1,Fn(),Jt("user")};Un=Ra,K&&(K.addEventListener("click",Ra),gt.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?(_.isVoiceActive()&&_.toggleVoice(),io()):yn("system"),K&&K.removeEventListener("click",Ra)}));let Pg=o.on("assistant:complete",()=>{Ts&&(bt.active||bt.manuallyDeactivated||Ts==="assistant"&&!bt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!bt.active&&!bt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("auto"),_.isVoiceActive()&&Os()}):Jt("auto"))},600))});gt.push(Pg);let Ig=o.on("action:resubmit",()=>{setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)});gt.push(Ig);let ts=()=>{Bt(!E,"user")},rn=null,on=null;if(A&&!F()){let c=s.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>da(r,ts).element,onToggle:ts});m&&(on=m)}on||(rn=da(r,ts))}rn?e.appendChild(rn.element):on&&e.appendChild(on),ao(),Vo(),Lo(),Zo(_.isStreaming()),ut()==="follow"?Rr(!0):Rs(),va(),M&&(!A||F()?setTimeout(()=>es(),0):E&&setTimeout(()=>es(),200));let Ns=()=>{var H,ye,ue,ee,Te,_e,Ae,ot,Ve,ct,dt,Pe,Le,je,Qe,vt,L,He,Oe,fe,Ot,Dt;if(F()){bn(),ao();return}let c=hn(r),m=(ye=(H=r.launcher)==null?void 0:H.sidebarMode)!=null?ye:!1,b=c||m||((ee=(ue=r.launcher)==null?void 0:ue.fullHeight)!=null?ee:!1),x=(Te=e.ownerDocument.defaultView)!=null?Te:window,T=(Ae=(_e=r.launcher)==null?void 0:_e.mobileFullscreen)!=null?Ae:!0,B=(Ve=(ot=r.launcher)==null?void 0:ot.mobileBreakpoint)!=null?Ve:640,O=x.innerWidth<=B,j=T&&O&&A;try{if(j){fr(),$o(e,r);return}if(R&&(R=!1,fr(),$o(e,r)),!A&&!c){ge.style.height="",ge.style.width="";return}if(!m&&!c){let Kt=(dt=(ct=r==null?void 0:r.launcher)==null?void 0:ct.width)!=null?dt:r==null?void 0:r.launcherWidth,wt=Kt!=null?Kt:pr;ge.style.width=wt,ge.style.maxWidth=wt}if(Mr(),!b){let Kt=x.innerHeight,wt=64,qt=(Le=(Pe=r.launcher)==null?void 0:Pe.heightOffset)!=null?Le:0,Yn=Math.max(200,Kt-wt),an=Math.min(640,Yn),Xe=Math.max(200,an-qt);ge.style.height=`${Xe}px`}}finally{if(bn(),ao(),E&&A){let wt=((je=e.ownerDocument.defaultView)!=null?je:window).innerWidth<=((vt=(Qe=r.launcher)==null?void 0:Qe.mobileBreakpoint)!=null?vt:640),qt=(He=(L=r.launcher)==null?void 0:L.sidebarMode)!=null?He:!1,Yn=(fe=(Oe=r.launcher)==null?void 0:Oe.mobileFullscreen)!=null?fe:!0,an=hn(r)&&Yn&&wt,Xe=qt||Yn&&wt&&A||an;if(Xe&&!nn){let Pt=e.getRootNode(),pn=Pt instanceof ShadowRoot?Pt.host:e.closest(".persona-host");pn&&!tn&&(tn=gl(pn,(Dt=(Ot=r.launcher)==null?void 0:Ot.zIndex)!=null?Dt:kn)),nn=fl(e.ownerDocument)}else Xe||(tn==null||tn(),tn=null,nn==null||nn(),nn=null)}}};Ns();let Kl=(Qc=e.ownerDocument.defaultView)!=null?Qc:window;if(Kl.addEventListener("resize",Ns),gt.push(()=>Kl.removeEventListener("resize",Ns)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{bn()});c.observe($e),gt.push(()=>c.disconnect())}Xn=pe.scrollTop;let Gl=Gr(pe),Rg=()=>{let c=pe.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:pe.ownerDocument.getSelection()},_i=()=>rm(Rg(),pe),Jl=()=>{let c=pe.scrollTop,m=Gr(pe),b=m<Gl;if(Gl=m,ut()!=="follow"){Xn=c,_n();return}let{action:x,nextLastScrollTop:T}=si({following:Qn.isFollowing(),currentScrollTop:c,lastScrollTop:Xn,nearBottom:Uo(pe,Jo),userScrollThreshold:ya,isAutoScrolling:xr||To||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Xn=T,x==="resume"){_i()||Ir();return}x==="pause"&&Yo()};if(pe.addEventListener("scroll",Jl,{passive:!0}),gt.push(()=>pe.removeEventListener("scroll",Jl)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{Sa()});c.observe(rt),c.observe(pe),gt.push(()=>c.disconnect())}let Ql=()=>{ut()==="follow"&&Qn.isFollowing()&&_i()&&Yo()},Xl=pe.ownerDocument;Xl.addEventListener("selectionchange",Ql),gt.push(()=>{Xl.removeEventListener("selectionchange",Ql)});let Yl=c=>{if(ut()!=="follow")return;let m=ai({following:Qn.isFollowing(),deltaY:c.deltaY,nearBottom:Uo(pe,Jo),resumeWhenNearBottom:!0});m==="pause"?Yo():m==="resume"&&!_i()&&Ir()};pe.addEventListener("wheel",Yl,{passive:!0}),gt.push(()=>pe.removeEventListener("wheel",Yl)),Ze.addEventListener("click",()=>{Mo(),pe.scrollTop=pe.scrollHeight,Xn=pe.scrollTop,Ir(),Rr(!0),_n()}),gt.push(()=>Ze.remove()),gt.push(()=>{Ms(),Mo()});let Zl=()=>{W&&(ar&&(W.removeEventListener("click",ar),ar=null),N()?(W.style.display="",ar=()=>{Bt(!1,"user")},W.addEventListener("click",ar)):W.style.display="none")};Zl(),(()=>{let{clearChatButton:c}=Be;c&&c.addEventListener("click",()=>{_.clearMessages(),$r.clear(),Ir(),No(Be.composerOverlay);try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(b){console.error("[AgentWidget] Failed to clear custom localStorage:",b)}let m=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(m),i!=null&&i.clear)try{let b=i.clear();b instanceof Promise&&b.catch(x=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",x)})}catch(b){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)}d={},w.syncFromMetadata(),le==null||le.clear(),me==null||me.reset(),V==null||V.update()})})(),Wt&&Wt.addEventListener("submit",k),te==null||te.addEventListener("keydown",Rt),te==null||te.addEventListener("input",et),te==null||te.addEventListener("paste",un);let ec=(Xc=e.ownerDocument)!=null?Xc:document;ec.addEventListener("keydown",_t,!0);let tc="persona-attachment-drop-active",Fs=0,$i=()=>{Fs=0,z.classList.remove(tc)},ns=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&Ct!==null},nc=c=>{!ki(c.dataTransfer)||!ns()||(Fs++,Fs===1&&z.classList.add(tc))},rc=c=>{!ki(c.dataTransfer)||!ns()||(Fs--,Fs<=0&&$i())},oc=c=>{!ki(c.dataTransfer)||!ns()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},sc=c=>{var b;if(!ki(c.dataTransfer)||!ns())return;c.preventDefault(),c.stopPropagation(),$i();let m=Array.from((b=c.dataTransfer.files)!=null?b:[]);m.length!==0&&Ct.handleFiles(m)},lo=!0;z.addEventListener("dragenter",nc,lo),z.addEventListener("dragleave",rc,lo),e.addEventListener("dragover",oc,lo),e.addEventListener("drop",sc,lo);let Wa=e.ownerDocument,ac=c=>{ns()&&c.preventDefault()},ic=c=>{ns()&&c.preventDefault()};Wa.addEventListener("dragover",ac),Wa.addEventListener("drop",ic),gt.push(()=>{Wt&&Wt.removeEventListener("submit",k),te==null||te.removeEventListener("keydown",Rt),te==null||te.removeEventListener("input",et),te==null||te.removeEventListener("paste",un),ec.removeEventListener("keydown",_t,!0)}),gt.push(()=>{z.removeEventListener("dragenter",nc,lo),z.removeEventListener("dragleave",rc,lo),e.removeEventListener("dragover",oc,lo),e.removeEventListener("drop",sc,lo),Wa.removeEventListener("dragover",ac),Wa.removeEventListener("drop",ic),$i()}),gt.push(()=>{_.cancel()}),rn?gt.push(()=>{rn==null||rn.destroy()}):on&&gt.push(()=>{on==null||on.remove()});let dn={update(c){var Tn,Rn,Wr,xn,Wn,Hn,Ho,_s,od,sd,ad,id,ld,cd,dd,pd,ud,md,gd,fd,hd,bd,yd,xd,vd,wd,Cd,Ad,Sd,Td,Ed,Md,kd,Ld,Pd,Id,Rd,Wd,Hd,Bd,Dd,Od,Nd,Fd,_d,$d,Ud,jd,qd,zd,Vd,Kd,Gd,Jd,Qd,Xd,Yd,Zd,ep,tp,np,rp,op,sp,ap,ip,lp,cp,dp,pp,up,mp,gp,fp,hp,bp,yp,xp,vp,wp,Cp,Ap,Sp,Tp,Ep,Mp,kp,Lp,Pp,Ip,Rp,Wp,Hp,Bp,Dp,Op,Np,Fp,_p,$p,Up,jp,qp,zp,Vp,Kp,Gp,Jp,Qp,Xp,Yp,Zp,eu,tu,nu;let m=r.toolCall,b=r.messageActions,x=(Tn=r.layout)==null?void 0:Tn.messages,T=r.colorScheme,B=r.loadingIndicator,O=r.iterationDisplay,j=(Rn=r.features)==null?void 0:Rn.showReasoning,H=(Wr=r.features)==null?void 0:Wr.showToolCalls,ye=(xn=r.features)==null?void 0:xn.toolCallDisplay,ue=(Wn=r.features)==null?void 0:Wn.reasoningDisplay;r={...r,...c},fr(),$o(e,r),Ai(e,r),Si(e,r),Gn(),r.colorScheme!==T&&to();let ee=Ti.getForInstance(r.plugins);s.length=0,s.push(...ee),A=(Ho=(Hn=r.launcher)==null?void 0:Hn.enabled)!=null?Ho:!0,D=(od=(_s=r.launcher)==null?void 0:_s.autoExpand)!=null?od:!1,qe=(ad=(sd=r.features)==null?void 0:sd.showReasoning)!=null?ad:!0,we=(ld=(id=r.features)==null?void 0:id.showToolCalls)!=null?ld:!0,he=(dd=(cd=r.features)==null?void 0:cd.scrollToBottom)!=null?dd:{};let Te=ut();ke=(ud=(pd=r.features)==null?void 0:pd.scrollBehavior)!=null?ud:{},Te!==ut()&&(Mo(),Ir()),Tr(),_n();let _e=Ie;if(Ie=(gd=(md=r.features)==null?void 0:md.showEventStreamToggle)!=null?gd:!1,Ie&&!_e){if(le||(Q=new fa(ce),le=new ga(ne,Q),me=me!=null?me:new ha,Q.open().then(()=>le==null?void 0:le.restore()).catch(()=>{}),_.setSSEEventCallback((J,St)=>{var Ut;(Ut=r.onSSEEvent)==null||Ut.call(r,J,St),me==null||me.processEvent(J,St),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:J,timestamp:Date.now(),payload:JSON.stringify(St)})})),!xt&&Fe){let J=(hd=(fd=r.features)==null?void 0:fd.eventStream)==null?void 0:hd.classNames,St="persona-inline-flex persona-items-center persona-justify-center persona-rounded-full hover:persona-opacity-80 persona-cursor-pointer persona-border-none persona-bg-transparent persona-p-1"+(J!=null&&J.toggleButton?" "+J.toggleButton:"");xt=h("button",St),xt.style.width="28px",xt.style.height="28px",xt.style.color=Dn.actionIconColor,xt.type="button",xt.setAttribute("aria-label","Event Stream"),xt.title="Event Stream";let Ut=Se("activity","18px","currentColor",1.5);Ut&&xt.appendChild(Ut);let pt=Be.clearChatButtonWrapper,It=Be.closeButtonWrapper,gn=pt||It;gn&&gn.parentNode===Fe?Fe.insertBefore(xt,gn):Fe.appendChild(xt),xt.addEventListener("click",()=>{se?gr():Or()})}}else!Ie&&_e&&(gr(),xt&&(xt.remove(),xt=null),le==null||le.clear(),Q==null||Q.destroy(),le=null,Q=null,me==null||me.reset(),me=null);if(((bd=r.launcher)==null?void 0:bd.enabled)===!1&&rn&&(rn.destroy(),rn=null),((yd=r.launcher)==null?void 0:yd.enabled)===!1&&on&&(on.remove(),on=null),((xd=r.launcher)==null?void 0:xd.enabled)!==!1&&!rn&&!on){let J=s.find(St=>St.renderLauncher);if(J!=null&&J.renderLauncher){let St=J.renderLauncher({config:r,defaultRenderer:()=>da(r,ts).element,onToggle:ts});St&&(on=St,e.appendChild(on))}on||(rn=da(r,ts),e.appendChild(rn.element))}rn&&rn.update(r),De&&((vd=r.launcher)==null?void 0:vd.title)!==void 0&&(De.textContent=r.launcher.title),Je&&((wd=r.launcher)==null?void 0:wd.subtitle)!==void 0&&(Je.textContent=r.launcher.subtitle);let Ae=(Cd=r.layout)==null?void 0:Cd.header;if((Ae==null?void 0:Ae.layout)!==S&&Fe){let J=Ae?pa(r,Ae,{showClose:N(),onClose:()=>Bt(!1,"user")}):vo({config:r,showClose:N(),onClose:()=>Bt(!1,"user")});Fe.replaceWith(J.header),Fe=J.header,de=J.iconHolder,De=J.headerTitle,Je=J.headerSubtitle,W=J.closeButton,S=Ae==null?void 0:Ae.layout}else if(Ae&&(de&&(de.style.display=Ae.showIcon===!1?"none":""),De&&(De.style.display=Ae.showTitle===!1?"none":""),Je&&(Je.style.display=Ae.showSubtitle===!1?"none":""),W&&(W.style.display=Ae.showCloseButton===!1?"none":""),Be.clearChatButtonWrapper)){let J=Ae.showClearChat;if(J!==void 0){Be.clearChatButtonWrapper.style.display=J?"":"none";let{closeButtonWrapper:St}=Be;St&&!St.classList.contains("persona-absolute")&&(J?St.classList.remove("persona-ml-auto"):St.classList.add("persona-ml-auto"))}}let Ve=((Ad=r.layout)==null?void 0:Ad.showHeader)!==!1;Fe&&(Fe.style.display=Ve?"":"none");let ct=((Sd=r.layout)==null?void 0:Sd.showFooter)!==!1;$e&&($e.style.display=ct?"":"none"),bn(),_n(),A!==I?A?Bt(D,"auto"):(E=!0,ao()):D!==P&&Bt(D,"auto"),P=D,I=A,Ns(),Zl();let Le=JSON.stringify(c.toolCall)!==JSON.stringify(m),je=JSON.stringify(r.messageActions)!==JSON.stringify(b),Qe=JSON.stringify((Td=r.layout)==null?void 0:Td.messages)!==JSON.stringify(x),vt=((Ed=r.loadingIndicator)==null?void 0:Ed.render)!==(B==null?void 0:B.render)||((Md=r.loadingIndicator)==null?void 0:Md.renderIdle)!==(B==null?void 0:B.renderIdle)||((kd=r.loadingIndicator)==null?void 0:kd.showBubble)!==(B==null?void 0:B.showBubble),L=r.iterationDisplay!==O,He=((Pd=(Ld=r.features)==null?void 0:Ld.showReasoning)!=null?Pd:!0)!==(j!=null?j:!0)||((Rd=(Id=r.features)==null?void 0:Id.showToolCalls)!=null?Rd:!0)!==(H!=null?H:!0)||JSON.stringify((Wd=r.features)==null?void 0:Wd.toolCallDisplay)!==JSON.stringify(ye)||JSON.stringify((Hd=r.features)==null?void 0:Hd.reasoningDisplay)!==JSON.stringify(ue);(Le||je||Qe||vt||L||He)&&_&&(Ss++,ko(rt,_.getMessages(),Me));let fe=(Bd=r.launcher)!=null?Bd:{},Ot=(Dd=fe.headerIconHidden)!=null?Dd:!1,Dt=(Nd=(Od=r.layout)==null?void 0:Od.header)==null?void 0:Nd.showIcon,Kt=Ot||Dt===!1,wt=fe.headerIconName,qt=(Fd=fe.headerIconSize)!=null?Fd:"48px";if(de){let J=z.querySelector(".persona-border-b-persona-divider"),St=J==null?void 0:J.querySelector(".persona-flex-col");if(Kt)de.style.display="none",J&&St&&!J.contains(St)&&J.insertBefore(St,J.firstChild);else{if(de.style.display="",de.style.height=qt,de.style.width=qt,J&&St&&(J.contains(de)?de.nextSibling!==St&&(de.remove(),J.insertBefore(de,St)):J.insertBefore(de,St)),wt){let pt=parseFloat(qt)||24,It=Se(wt,pt*.6,"#ffffff",2);It?de.replaceChildren(It):de.textContent=(_d=fe.agentIconText)!=null?_d:"\u{1F4AC}"}else if(fe.iconUrl){let pt=de.querySelector("img");if(pt)pt.src=fe.iconUrl,pt.style.height=qt,pt.style.width=qt;else{let It=document.createElement("img");It.src=fe.iconUrl,It.alt="",It.className="persona-rounded-xl persona-object-cover",It.style.height=qt,It.style.width=qt,de.replaceChildren(It)}}else{let pt=de.querySelector("svg"),It=de.querySelector("img");(pt||It)&&de.replaceChildren(),de.textContent=($d=fe.agentIconText)!=null?$d:"\u{1F4AC}"}let Ut=de.querySelector("img");Ut&&(Ut.style.height=qt,Ut.style.width=qt)}}let Yn=(jd=(Ud=r.layout)==null?void 0:Ud.header)==null?void 0:jd.showTitle,an=(zd=(qd=r.layout)==null?void 0:qd.header)==null?void 0:zd.showSubtitle;if(De&&(De.style.display=Yn===!1?"none":""),Je&&(Je.style.display=an===!1?"none":""),W){((Kd=(Vd=r.layout)==null?void 0:Vd.header)==null?void 0:Kd.showCloseButton)===!1?W.style.display="none":W.style.display="";let St=(Gd=fe.closeButtonSize)!=null?Gd:"32px",Ut=(Jd=fe.closeButtonPlacement)!=null?Jd:"inline";W.style.height=St,W.style.width=St;let{closeButtonWrapper:pt}=Be,It=Ut==="top-right",gn=pt==null?void 0:pt.classList.contains("persona-absolute");if(pt&&It!==gn)if(pt.remove(),It)pt.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",z.style.position="relative",z.appendChild(pt);else{let mt=(Xd=(Qd=fe.clearChat)==null?void 0:Qd.placement)!=null?Xd:"inline",fn=(Zd=(Yd=fe.clearChat)==null?void 0:Yd.enabled)!=null?Zd:!0;pt.className=fn&&mt==="inline"?"":"persona-ml-auto";let $n=z.querySelector(".persona-border-b-persona-divider");$n&&$n.appendChild(pt)}if(W.style.color=fe.closeButtonColor||Dn.actionIconColor,fe.closeButtonBackgroundColor?(W.style.backgroundColor=fe.closeButtonBackgroundColor,W.classList.remove("hover:persona-bg-gray-100")):(W.style.backgroundColor="",W.classList.add("hover:persona-bg-gray-100")),fe.closeButtonBorderWidth||fe.closeButtonBorderColor){let mt=fe.closeButtonBorderWidth||"0px",fn=fe.closeButtonBorderColor||"transparent";W.style.border=`${mt} solid ${fn}`,W.classList.remove("persona-border-none")}else W.style.border="",W.classList.add("persona-border-none");fe.closeButtonBorderRadius?(W.style.borderRadius=fe.closeButtonBorderRadius,W.classList.remove("persona-rounded-full")):(W.style.borderRadius="",W.classList.add("persona-rounded-full")),fe.closeButtonPaddingX?(W.style.paddingLeft=fe.closeButtonPaddingX,W.style.paddingRight=fe.closeButtonPaddingX):(W.style.paddingLeft="",W.style.paddingRight=""),fe.closeButtonPaddingY?(W.style.paddingTop=fe.closeButtonPaddingY,W.style.paddingBottom=fe.closeButtonPaddingY):(W.style.paddingTop="",W.style.paddingBottom="");let En=(ep=fe.closeButtonIconName)!=null?ep:"x",wr=(tp=fe.closeButtonIconText)!=null?tp:"\xD7";W.innerHTML="";let Bn=Se(En,"28px","currentColor",1);Bn?W.appendChild(Bn):W.textContent=wr;let sn=(np=fe.closeButtonTooltipText)!=null?np:"Close chat",er=(rp=fe.closeButtonShowTooltip)!=null?rp:!0;if(W.setAttribute("aria-label",sn),pt&&(pt._cleanupTooltip&&(pt._cleanupTooltip(),delete pt._cleanupTooltip),er&&sn)){let mt=null,fn=()=>{if(mt||!W)return;let Bo=W.ownerDocument,$s=Bo.body;if(!$s)return;mt=Hr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=sn;let Us=Hr(Bo,"div");Us.className="persona-clear-chat-tooltip-arrow",mt.appendChild(Us);let Do=W.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(bo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",$s.appendChild(mt)},$n=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};pt.addEventListener("mouseenter",fn),pt.addEventListener("mouseleave",$n),W.addEventListener("focus",fn),W.addEventListener("blur",$n),pt._cleanupTooltip=()=>{$n(),pt&&(pt.removeEventListener("mouseenter",fn),pt.removeEventListener("mouseleave",$n)),W&&(W.removeEventListener("focus",fn),W.removeEventListener("blur",$n))}}}let{clearChatButton:Xe,clearChatButtonWrapper:Pt}=Be;if(Xe){let J=(op=fe.clearChat)!=null?op:{},St=(sp=J.enabled)!=null?sp:!0,Ut=(ip=(ap=r.layout)==null?void 0:ap.header)==null?void 0:ip.showClearChat,pt=Ut!==void 0?Ut:St,It=(lp=J.placement)!=null?lp:"inline";if(Pt){Pt.style.display=pt?"":"none";let{closeButtonWrapper:gn}=Be;!F()&&gn&&!gn.classList.contains("persona-absolute")&&(pt?gn.classList.remove("persona-ml-auto"):gn.classList.add("persona-ml-auto"));let En=It==="top-right",wr=Pt.classList.contains("persona-absolute");if(!F()&&En!==wr&&pt){if(Pt.remove(),En)Pt.className="persona-absolute persona-top-4 persona-z-50",Pt.style.right="48px",z.style.position="relative",z.appendChild(Pt);else{Pt.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",Pt.style.right="";let sn=z.querySelector(".persona-border-b-persona-divider"),er=Be.closeButtonWrapper;sn&&er&&er.parentElement===sn?sn.insertBefore(Pt,er):sn&&sn.appendChild(Pt)}let Bn=Be.closeButtonWrapper;Bn&&!Bn.classList.contains("persona-absolute")&&(En?Bn.classList.add("persona-ml-auto"):Bn.classList.remove("persona-ml-auto"))}}if(pt){if(!F()){let mt=(cp=J.size)!=null?cp:"32px";Xe.style.height=mt,Xe.style.width=mt}let gn=(dp=J.iconName)!=null?dp:"refresh-cw",En=(pp=J.iconColor)!=null?pp:"";Xe.style.color=En||Dn.actionIconColor,Xe.innerHTML="";let wr=F()?"14px":"20px",Bn=Se(gn,wr,"currentColor",2);if(Bn&&Xe.appendChild(Bn),J.backgroundColor?(Xe.style.backgroundColor=J.backgroundColor,Xe.classList.remove("hover:persona-bg-gray-100")):(Xe.style.backgroundColor="",Xe.classList.add("hover:persona-bg-gray-100")),J.borderWidth||J.borderColor){let mt=J.borderWidth||"0px",fn=J.borderColor||"transparent";Xe.style.border=`${mt} solid ${fn}`,Xe.classList.remove("persona-border-none")}else Xe.style.border="",Xe.classList.add("persona-border-none");J.borderRadius?(Xe.style.borderRadius=J.borderRadius,Xe.classList.remove("persona-rounded-full")):(Xe.style.borderRadius="",Xe.classList.add("persona-rounded-full")),J.paddingX?(Xe.style.paddingLeft=J.paddingX,Xe.style.paddingRight=J.paddingX):(Xe.style.paddingLeft="",Xe.style.paddingRight=""),J.paddingY?(Xe.style.paddingTop=J.paddingY,Xe.style.paddingBottom=J.paddingY):(Xe.style.paddingTop="",Xe.style.paddingBottom="");let sn=(up=J.tooltipText)!=null?up:"Clear chat",er=(mp=J.showTooltip)!=null?mp:!0;if(Xe.setAttribute("aria-label",sn),Pt&&(Pt._cleanupTooltip&&(Pt._cleanupTooltip(),delete Pt._cleanupTooltip),er&&sn)){let mt=null,fn=()=>{if(mt||!Xe)return;let Bo=Xe.ownerDocument,$s=Bo.body;if(!$s)return;mt=Hr(Bo,"div","persona-clear-chat-tooltip"),mt.textContent=sn;let Us=Hr(Bo,"div");Us.className="persona-clear-chat-tooltip-arrow",mt.appendChild(Us);let Do=Xe.getBoundingClientRect();mt.style.position="fixed",mt.style.zIndex=String(bo),mt.style.left=`${Do.left+Do.width/2}px`,mt.style.top=`${Do.top-8}px`,mt.style.transform="translate(-50%, -100%)",$s.appendChild(mt)},$n=()=>{mt&&mt.parentNode&&(mt.parentNode.removeChild(mt),mt=null)};Pt.addEventListener("mouseenter",fn),Pt.addEventListener("mouseleave",$n),Xe.addEventListener("focus",fn),Xe.addEventListener("blur",$n),Pt._cleanupTooltip=()=>{$n(),Pt&&(Pt.removeEventListener("mouseenter",fn),Pt.removeEventListener("mouseleave",$n)),Xe&&(Xe.removeEventListener("focus",fn),Xe.removeEventListener("blur",$n))}}}}let pn=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ei],cr=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[ws.message,ws.messageAndClick];w=Mi({parsers:pn,handlers:cr,getSessionMetadata:f,updateSessionMetadata:g,emit:o.emit,documentRef:typeof document!="undefined"?document:null}),Me=qm(r,w,re),_.updateConfig(r),ko(rt,_.getMessages(),Me),Vo(),Lo(),Zo(_.isStreaming());let Zn=((gp=r.voiceRecognition)==null?void 0:gp.enabled)===!0,Po=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Io=((hp=(fp=r.voiceRecognition)==null?void 0:fp.provider)==null?void 0:hp.type)==="runtype";if(Zn&&(Po||Io))if(!K||!yt){let J=Mg(r.voiceRecognition,r.sendButton);J&&(K=J.micButton,yt=J.micButtonWrapper,zt.insertBefore(yt,On),K.addEventListener("click",Ra),K.disabled=_.isStreaming())}else{let J=(bp=r.voiceRecognition)!=null?bp:{},St=(yp=r.sendButton)!=null?yp:{},Ut=(xp=J.iconName)!=null?xp:"mic",pt=(vp=St.size)!=null?vp:"40px",It=(wp=J.iconSize)!=null?wp:pt,gn=parseFloat(It)||24;K.style.width=It,K.style.height=It,K.style.minWidth=It,K.style.minHeight=It;let En=(Ap=(Cp=J.iconColor)!=null?Cp:St.textColor)!=null?Ap:"currentColor";K.innerHTML="";let wr=Se(Ut,gn,En,2);wr?K.appendChild(wr):K.textContent="\u{1F3A4}";let Bn=(Sp=J.backgroundColor)!=null?Sp:St.backgroundColor;Bn?K.style.backgroundColor=Bn:K.style.backgroundColor="",En?K.style.color=En:K.style.color="var(--persona-text, #111827)",J.borderWidth?(K.style.borderWidth=J.borderWidth,K.style.borderStyle="solid"):(K.style.borderWidth="",K.style.borderStyle=""),J.borderColor?K.style.borderColor=J.borderColor:K.style.borderColor="",J.paddingX?(K.style.paddingLeft=J.paddingX,K.style.paddingRight=J.paddingX):(K.style.paddingLeft="",K.style.paddingRight=""),J.paddingY?(K.style.paddingTop=J.paddingY,K.style.paddingBottom=J.paddingY):(K.style.paddingTop="",K.style.paddingBottom="");let sn=yt==null?void 0:yt.querySelector(".persona-send-button-tooltip"),er=(Tp=J.tooltipText)!=null?Tp:"Start voice recognition";if(((Ep=J.showTooltip)!=null?Ep:!1)&&er)if(sn)sn.textContent=er,sn.style.display="";else{let fn=document.createElement("div");fn.className="persona-send-button-tooltip",fn.textContent=er,yt==null||yt.insertBefore(fn,K)}else sn&&(sn.style.display="none");yt.style.display="",K.disabled=_.isStreaming()}else K&&yt&&(yt.style.display="none",((kp=(Mp=r.voiceRecognition)==null?void 0:Mp.provider)==null?void 0:kp.type)==="runtype"?_.isVoiceActive()&&_.toggleVoice():ft&&yn());if(((Lp=r.attachments)==null?void 0:Lp.enabled)===!0)if(!ve||!it){let J=(Pp=r.attachments)!=null?Pp:{},Ut=(Rp=((Ip=r.sendButton)!=null?Ip:{}).size)!=null?Rp:"40px";tt||(tt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),tt.style.display="none",Wt.insertBefore(tt,te)),ie||(ie=document.createElement("input"),ie.type="file",ie.accept=((Wp=J.allowedTypes)!=null?Wp:Kr).join(","),ie.multiple=((Hp=J.maxFiles)!=null?Hp:4)>1,ie.style.display="none",ie.setAttribute("aria-label","Attach files"),Wt.insertBefore(ie,te)),ve=h("div","persona-send-button-wrapper"),it=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),it.type="button",it.setAttribute("aria-label",(Bp=J.buttonTooltipText)!=null?Bp:"Attach file");let pt=(Dp=J.buttonIconName)!=null?Dp:"paperclip",It=Ut,gn=parseFloat(It)||40,En=Math.round(gn*.6);it.style.width=It,it.style.height=It,it.style.minWidth=It,it.style.minHeight=It,it.style.fontSize="18px",it.style.lineHeight="1",it.style.backgroundColor="transparent",it.style.color="var(--persona-primary, #111827)",it.style.border="none",it.style.borderRadius="6px",it.style.transition="background-color 0.15s ease",it.addEventListener("mouseenter",()=>{it.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),it.addEventListener("mouseleave",()=>{it.style.backgroundColor="transparent"});let wr=Se(pt,En,"currentColor",1.5);wr?it.appendChild(wr):it.textContent="\u{1F4CE}",it.addEventListener("click",er=>{er.preventDefault(),ie==null||ie.click()}),ve.appendChild(it);let Bn=(Op=J.buttonTooltipText)!=null?Op:"Attach file",sn=h("div","persona-send-button-tooltip");sn.textContent=Bn,ve.appendChild(sn),Lt.append(ve),!Ct&&ie&&tt&&(Ct=gs.fromConfig(J),Ct.setPreviewsContainer(tt),ie.addEventListener("change",async()=>{Ct&&(ie!=null&&ie.files)&&(await Ct.handleFileSelect(ie.files),ie.value="")})),z.querySelector(".persona-attachment-drop-overlay")||z.appendChild(zm(J.dropOverlay))}else{ve.style.display="";let J=(Np=r.attachments)!=null?Np:{};ie&&(ie.accept=((Fp=J.allowedTypes)!=null?Fp:Kr).join(","),ie.multiple=((_p=J.maxFiles)!=null?_p:4)>1),Ct&&Ct.updateConfig({allowedTypes:J.allowedTypes,maxFileSize:J.maxFileSize,maxFiles:J.maxFiles})}else ve&&(ve.style.display="none"),Ct&&Ct.clearAttachments(),($p=z.querySelector(".persona-attachment-drop-overlay"))==null||$p.remove();let Qt=(Up=r.sendButton)!=null?Up:{},Ro=(jp=Qt.useIcon)!=null?jp:!1,co=(qp=Qt.iconText)!=null?qp:"\u2191",po=Qt.iconName,Vr=(zp=Qt.tooltipText)!=null?zp:"Send message",Wo=(Vp=Qt.showTooltip)!=null?Vp:!1,vr=(Kp=Qt.size)!=null?Kp:"40px",nt=Qt.backgroundColor,mn=Qt.textColor;if(Ro){if(ze.style.width=vr,ze.style.height=vr,ze.style.minWidth=vr,ze.style.minHeight=vr,ze.style.fontSize="18px",ze.style.lineHeight="1",ze.innerHTML="",mn?ze.style.color=mn:ze.style.color="var(--persona-button-primary-fg, #ffffff)",po){let J=parseFloat(vr)||24,St=(mn==null?void 0:mn.trim())||"currentColor",Ut=Se(po,J,St,2);Ut?ze.appendChild(Ut):ze.textContent=co}else ze.textContent=co;ze.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",nt?(ze.style.backgroundColor=nt,ze.classList.remove("persona-bg-persona-primary")):(ze.style.backgroundColor="",ze.classList.add("persona-bg-persona-primary"))}else ze.textContent=(Jp=(Gp=r.copy)==null?void 0:Gp.sendButtonLabel)!=null?Jp:"Send",ze.style.width="",ze.style.height="",ze.style.minWidth="",ze.style.minHeight="",ze.style.fontSize="",ze.style.lineHeight="",ze.className="persona-rounded-button persona-bg-persona-accent persona-px-4 persona-py-2 persona-text-sm persona-font-semibold persona-text-white disabled:persona-opacity-50 persona-cursor-pointer",nt?(ze.style.backgroundColor=nt,ze.classList.remove("persona-bg-persona-accent")):ze.classList.add("persona-bg-persona-accent"),mn?ze.style.color=mn:ze.classList.add("persona-text-white");Qt.borderWidth?(ze.style.borderWidth=Qt.borderWidth,ze.style.borderStyle="solid"):(ze.style.borderWidth="",ze.style.borderStyle=""),Qt.borderColor?ze.style.borderColor=Qt.borderColor:ze.style.borderColor="",Qt.paddingX?(ze.style.paddingLeft=Qt.paddingX,ze.style.paddingRight=Qt.paddingX):(ze.style.paddingLeft="",ze.style.paddingRight=""),Qt.paddingY?(ze.style.paddingTop=Qt.paddingY,ze.style.paddingBottom=Qt.paddingY):(ze.style.paddingTop="",ze.style.paddingBottom="");let $t=On==null?void 0:On.querySelector(".persona-send-button-tooltip");if(Wo&&Vr)if($t)$t.textContent=Vr,$t.style.display="";else{let J=document.createElement("div");J.className="persona-send-button-tooltip",J.textContent=Vr,On==null||On.insertBefore(J,ze)}else $t&&($t.style.display="none");let Nt=(eu=(Qp=r.layout)==null?void 0:Qp.contentMaxWidth)!=null?eu:F()?(Zp=(Yp=(Xp=r.launcher)==null?void 0:Xp.composerBar)==null?void 0:Yp.contentMaxWidth)!=null?Zp:"720px":void 0;Nt?(rt.style.maxWidth=Nt,rt.style.marginLeft="auto",rt.style.marginRight="auto",rt.style.width="100%",Wt&&(Wt.style.maxWidth=Nt,Wt.style.marginLeft="auto",Wt.style.marginRight="auto"),Tt&&(Tt.style.maxWidth=Nt,Tt.style.marginLeft="auto",Tt.style.marginRight="auto")):(rt.style.maxWidth="",rt.style.marginLeft="",rt.style.marginRight="",rt.style.width="",Wt&&(Wt.style.maxWidth="",Wt.style.marginLeft="",Wt.style.marginRight=""),Tt&&(Tt.style.maxWidth="",Tt.style.marginLeft="",Tt.style.marginRight=""));let ht=(tu=r.statusIndicator)!=null?tu:{},Xt=(nu=ht.visible)!=null?nu:!0;if(ln.style.display=Xt?"":"none",_){let J=_.getStatus();Ye(ln,(Ut=>{var pt,It,gn,En;return Ut==="idle"?(pt=ht.idleText)!=null?pt:Mn.idle:Ut==="connecting"?(It=ht.connectingText)!=null?It:Mn.connecting:Ut==="connected"?(gn=ht.connectedText)!=null?gn:Mn.connected:Ut==="error"?(En=ht.errorText)!=null?En:Mn.error:Mn[Ut]})(J),ht,J)}ln.classList.remove("persona-text-left","persona-text-center","persona-text-right");let Mt=ht.align==="left"?"persona-text-left":ht.align==="center"?"persona-text-center":"persona-text-right";ln.classList.add(Mt)},open(){N()&&Bt(!0,"api")},close(){N()&&Bt(!1,"api")},toggle(){N()&&Bt(!E,"api")},clearChat(){Pn=!1,_.clearMessages(),$r.clear(),Ir();try{localStorage.removeItem(Cs),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Cs}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Cs)try{localStorage.removeItem(r.clearChatHistoryStorageKey),r.debug&&console.log(`[AgentWidget] Cleared custom localStorage key: ${r.clearChatHistoryStorageKey}`)}catch(m){console.error("[AgentWidget] Failed to clear custom localStorage:",m)}let c=new CustomEvent("persona:clear-chat",{detail:{timestamp:new Date().toISOString()}});if(window.dispatchEvent(c),i!=null&&i.clear)try{let m=i.clear();m instanceof Promise&&m.catch(b=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",b)})}catch(m){typeof console!="undefined"&&console.error("[AgentWidget] Failed to clear storage adapter:",m)}d={},w.syncFromMetadata(),le==null||le.clear(),me==null||me.reset(),V==null||V.update()},setMessage(c){return!te||_.isStreaming()?!1:(!E&&N()&&Bt(!0,"system"),te.value=c,te.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if(_.isStreaming())return!1;let m=(c==null?void 0:c.trim())||te.value.trim();return m?(!E&&N()&&Bt(!0,"system"),te.value="",te.style.height="auto",_.sendMessage(m),!0):!1},startVoiceRecognition(){var m,b;return _.isStreaming()?!1:((b=(m=r.voiceRecognition)==null?void 0:m.provider)==null?void 0:b.type)==="runtype"?(_.isVoiceActive()||(!E&&N()&&Bt(!0,"system"),bt.manuallyDeactivated=!1,Fn(),_.toggleVoice().then(()=>{bt.active=_.isVoiceActive(),ir("user"),_.isVoiceActive()&&Os()})),!0):ft?!0:wn()?(!E&&N()&&Bt(!0,"system"),bt.manuallyDeactivated=!1,Fn(),Jt("user"),!0):!1},stopVoiceRecognition(){var c,m;return((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?_.isVoiceActive()?(_.toggleVoice().then(()=>{bt.active=!1,bt.manuallyDeactivated=!0,Fn(),ir("user"),io()}),!0):!1:ft?(bt.manuallyDeactivated=!0,Fn(),yn("user"),!0):!1},injectMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectMessage(c)},injectAssistantMessage(c){!E&&N()&&Bt(!0,"system");let m=_.injectAssistantMessage(c);return U&&(U=!1,q&&(clearTimeout(q),q=null),setTimeout(()=>{_&&!_.isStreaming()&&_.continueConversation()},100)),m},injectUserMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectUserMessage(c)},injectSystemMessage(c){return!E&&N()&&Bt(!0,"system"),_.injectSystemMessage(c)},injectMessageBatch(c){return!E&&N()&&Bt(!0,"system"),_.injectMessageBatch(c)},injectComponentDirective(c){return!E&&N()&&Bt(!0,"system"),_.injectComponentDirective(c)},injectTestMessage(c){!E&&N()&&Bt(!0,"system"),_.injectTestEvent(c)},async connectStream(c,m){return _.connectStream(c,m)},__pushEventStreamEvent(c){le&&(me==null||me.processEvent(c.type,c.payload),le.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Ie||!le||Or()},hideEventStream(){se&&gr()},isEventStreamVisible(){return se},showArtifacts(){mr(r)&&(Pn=!1,Gn(),At==null||At.setMobileOpen(!0))},hideArtifacts(){mr(r)&&(Pn=!0,Gn())},upsertArtifact(c){return mr(r)?(Pn=!1,_.upsertArtifact(c)):null},selectArtifact(c){mr(r)&&_.selectArtifact(c)},clearArtifacts(){mr(r)&&_.clearArtifacts()},getArtifacts(){var c;return(c=_==null?void 0:_.getArtifacts())!=null?c:[]},getSelectedArtifactId(){var c;return(c=_==null?void 0:_.getSelectedArtifactId())!=null?c:null},focusInput(){return A&&!E&&!F()||!te?!1:(te.focus(),!0)},async resolveApproval(c,m,b){let T=_.getMessages().find(B=>{var O;return B.variant==="approval"&&((O=B.approval)==null?void 0:O.id)===c});if(!(T!=null&&T.approval))throw new Error(`Approval not found: ${c}`);if(T.approval.toolType==="webmcp"){_.resolveWebMcpApproval(T.id,m);return}return _.resolveApproval(T.approval,m,b)},getMessages(){return _.getMessages()},getStatus(){return _.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return o.on(c,m)},off(c,m){o.off(c,m)},isOpen(){return N()&&E},isVoiceActive(){return bt.active},getState(){return{open:N()&&E,launcherEnabled:A,voiceActive:bt.active,streaming:_.isStreaming()}},showCSATFeedback(c){!E&&N()&&Bt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let b=Wl({onSubmit:async(x,T)=>{var B;_.isClientTokenMode()&&await _.submitCSATFeedback(x,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,x,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!E&&N()&&Bt(!0,"system");let m=rt.querySelector(".persona-feedback-container");m&&m.remove();let b=Hl({onSubmit:async(x,T)=>{var B;_.isClientTokenMode()&&await _.submitNPSFeedback(x,T),(B=c==null?void 0:c.onSubmit)==null||B.call(c,x,T)},onDismiss:c==null?void 0:c.onDismiss,...c});rt.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},async submitCSATFeedback(c,m){return _.submitCSATFeedback(c,m)},async submitNPSFeedback(c,m){return _.submitNPSFeedback(c,m)},destroy(){Ue!=null&&(clearInterval(Ue),Ue=null),gt.forEach(c=>c()),xe.remove(),Ge==null||Ge.remove(),rn==null||rn.destroy(),on==null||on.remove(),ar&&W.removeEventListener("click",ar)}};if((((Yc=n==null?void 0:n.debugTools)!=null?Yc:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:dn,getMessages:dn.getMessages,getStatus:dn.getStatus,getMetadata:dn.getPersistentMetadata,updateMetadata:dn.updatePersistentMetadata,clearHistory:()=>dn.clearChat(),setVoiceActive:b=>b?dn.startVoiceRecognition():dn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,gt.push(()=>{window.AgentWidgetBrowser===m&&(window.AgentWidgetBrowser=c)})}if(typeof window!="undefined"){let c=e.getAttribute("data-persona-instance")||e.id||"persona-"+Math.random().toString(36).slice(2,8),m=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.focusInput()};if(window.addEventListener("persona:focusInput",m),gt.push(()=>{window.removeEventListener("persona:focusInput",m)}),Ie){let j=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&dn.showEventStream()},H=ye=>{let ue=ye.detail;(!(ue!=null&&ue.instanceId)||ue.instanceId===c)&&dn.hideEventStream()};window.addEventListener("persona:showEventStream",j),window.addEventListener("persona:hideEventStream",H),gt.push(()=>{window.removeEventListener("persona:showEventStream",j),window.removeEventListener("persona:hideEventStream",H)})}let b=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.showArtifacts()},x=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.hideArtifacts()},T=j=>{let H=j.detail;H!=null&&H.instanceId&&H.instanceId!==c||H!=null&&H.artifact&&dn.upsertArtifact(H.artifact)},B=j=>{let H=j.detail;H!=null&&H.instanceId&&H.instanceId!==c||typeof(H==null?void 0:H.id)=="string"&&dn.selectArtifact(H.id)},O=j=>{let H=j.detail;(!(H!=null&&H.instanceId)||H.instanceId===c)&&dn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",T),window.addEventListener("persona:selectArtifact",B),window.addEventListener("persona:clearArtifacts",O),gt.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",T),window.removeEventListener("persona:selectArtifact",B),window.removeEventListener("persona:clearArtifacts",O)})}let lr=Wx(r.persistState);if(lr&&N()){let c=Hx(lr.storage),m=`${lr.keyPrefix}widget-open`,b=`${lr.keyPrefix}widget-voice`,x=`${lr.keyPrefix}widget-voice-mode`;if(c){let T=((Zc=lr.persist)==null?void 0:Zc.openState)&&c.getItem(m)==="true",B=((ed=lr.persist)==null?void 0:ed.voiceState)&&c.getItem(b)==="true",O=((td=lr.persist)==null?void 0:td.voiceState)&&c.getItem(x)==="true";if(T&&setTimeout(()=>{dn.open(),setTimeout(()=>{var j;if(B||O)dn.startVoiceRecognition();else if((j=lr.persist)!=null&&j.focusInput){let H=e.querySelector("textarea");H&&H.focus()}},100)},0),(nd=lr.persist)!=null&&nd.openState&&(o.on("widget:opened",()=>{c.setItem(m,"true")}),o.on("widget:closed",()=>{c.setItem(m,"false")})),(rd=lr.persist)!=null&&rd.voiceState&&(o.on("voice:state",j=>{c.setItem(b,j.active?"true":"false")}),o.on("user:message",j=>{c.setItem(x,j.viaVoice?"true":"false")})),lr.clearOnChatClear){let j=()=>{c.removeItem(m),c.removeItem(b),c.removeItem(x)},H=()=>j();window.addEventListener("persona:clear-chat",H),gt.push(()=>{window.removeEventListener("persona:clear-chat",H)})}}}return p&&N()&&setTimeout(()=>{dn.open()},0),zr(),dn};var Bx=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let s=/^(\d+(?:\.\d+)?)%$/i.exec(n);return s?Math.max(0,t*parseFloat(s[1])/100):420},Dx=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Ox=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Nx=(e,t)=>{let n=e.parentElement;if(!n)return;let r=e.ownerDocument.createElement("div");r.style.cssText="width:0;height:1px;margin:0;padding:0;border:0;visibility:hidden;",n.appendChild(r);let s=r.offsetHeight>0;r.style.height="100%";let o=r.offsetHeight>0;r.remove(),!(!s||o)&&console.warn("[AgentWidget] Docked mode: no ancestor of the dock target provides a definite height, so the dock panel cannot size to your layout."+(t.maxHeight===!1?" The viewport guard is disabled (dock.maxHeight: false), so the panel will grow with the conversation and overflow the viewport.":` Falling back to clamping the panel to ${t.maxHeight} (configurable via launcher.dock.maxHeight).`)+" To size the panel from your layout instead, give the height chain a definite height (e.g. `html, body { height: 100% }`) down to the dock target's parent.")},Vm=(e,t)=>{var r,s;let n=(s=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?s:!0;e.className="persona-host",e.style.height=n?"":"100%",e.style.display=n?"":"flex",e.style.flexDirection=n?"":"column",e.style.flex=n?"":"1 1 auto",e.style.minHeight=n?"":"0"},_l=e=>{e.style.position="",e.style.top="",e.style.bottom="",e.style.left="",e.style.right="",e.style.zIndex="",e.style.transform="",e.style.pointerEvents=""},Km=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",_l(e)},Ol=e=>{e.style.transition=""},Nl=e=>{e.style.display="",e.style.flexDirection="",e.style.flex="",e.style.minHeight="",e.style.minWidth="",e.style.width="",e.style.height="",e.style.alignItems="",e.style.transition="",e.style.transform="",e.style.marginLeft=""},Fl=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},Li=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Fx=(e,t,n,r,s)=>{s?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},_x=(e,t,n,r,s,o)=>{let a=o?t:e;s==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Gm=(e,t,n,r,s,o,a)=>{var v,y,w,A,D,M;let i=ur(o),d=i.reveal==="push";Fx(e,t,n,r,d),_x(e,t,n,r,i.side,d),e.dataset.personaHostLayout="docked",e.dataset.personaDockSide=i.side,e.dataset.personaDockOpen=a?"true":"false",e.style.width="100%",e.style.maxWidth="100%",e.style.minWidth="0",e.style.height="100%",e.style.minHeight="0",e.style.position="relative",n.style.display="flex",n.style.flexDirection="column",n.style.minHeight="0",n.style.position="relative",s.className="persona-host",s.style.height="100%",s.style.minHeight="0",s.style.display="flex",s.style.flexDirection="column",s.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(y=(v=o==null?void 0:o.launcher)==null?void 0:v.mobileFullscreen)!=null?y:!0,u=(A=(w=o==null?void 0:o.launcher)==null?void 0:w.mobileBreakpoint)!=null?A:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),Nl(t),Ol(r),Km(r),Fl(n),Li(s,r),e.style.display="flex",e.style.flexDirection="column",e.style.alignItems="stretch",e.style.overflow="hidden",n.style.flex="1 1 auto",n.style.width="100%",n.style.minWidth="0",r.style.display="flex",r.style.flexDirection="column",r.style.position="fixed",r.style.inset="0",r.style.width="100%",r.style.height="100%",r.style.maxWidth="100%",r.style.minWidth="0",r.style.minHeight="0",r.style.overflow="hidden",r.style.zIndex=String((M=(D=o==null?void 0:o.launcher)==null?void 0:D.zIndex)!=null?M:kn),r.style.transform="none",r.style.transition="none",r.style.pointerEvents="auto",r.style.flex="none",d&&(t.style.display="flex",t.style.flexDirection="column",t.style.width="100%",t.style.height="100%",t.style.minHeight="0",t.style.minWidth="0",t.style.flex="1 1 auto",t.style.alignItems="stretch",t.style.transform="none",t.style.marginLeft="0",t.style.transition="none",n.style.flex="1 1 auto",n.style.width="100%",n.style.maxWidth="100%",n.style.minWidth="0");return}if(e.removeAttribute("data-persona-dock-mobile-fullscreen"),Km(r),Dx(r,i.maxHeight),i.reveal==="overlay"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="overlay",Nl(t),Ol(r),Fl(n),Li(s,r);let P=i.animate?"transform 180ms ease":"none",I=i.side==="right"?"translateX(100%)":"translateX(-100%)",S=a?"translateX(0)":I;r.style.display="flex",r.style.flexDirection="column",r.style.flex="none",r.style.position="absolute",r.style.top="0",r.style.bottom="0",r.style.width=i.width,r.style.maxWidth=i.width,r.style.minWidth=i.width,r.style.minHeight="0",r.style.overflow="hidden",r.style.transition=P,r.style.transform=S,r.style.pointerEvents=a?"auto":"none",r.style.zIndex="2",i.side==="right"?(r.style.right="0",r.style.left=""):(r.style.left="0",r.style.right="")}else if(i.reveal==="push"){e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="hidden",e.dataset.personaDockReveal="push",Ol(r),_l(r),Li(s,r);let P=Bx(i.width,e.clientWidth),I=Math.max(0,e.clientWidth),S=i.animate?"margin-left 180ms ease":"none",R=i.side==="right"?a?-P:0:a?0:-P;t.style.display="flex",t.style.flexDirection="row",t.style.flex="0 0 auto",t.style.minHeight="0",t.style.minWidth="0",t.style.alignItems="stretch",t.style.height="100%",t.style.width=`${I+P}px`,t.style.transition=S,t.style.marginLeft=`${R}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${I}px`,n.style.maxWidth=`${I}px`,n.style.minWidth=`${I}px`,r.style.display="flex",r.style.flexDirection="column",r.style.flex="0 0 auto",r.style.flexShrink="0",r.style.width=i.width,r.style.minWidth=i.width,r.style.maxWidth=i.width,r.style.position="relative",r.style.top="",r.style.overflow="hidden",r.style.transition="none",r.style.pointerEvents=a?"auto":"none"}else{e.style.display="flex",e.style.flexDirection="row",e.style.alignItems="stretch",e.style.overflow="",Nl(t),_l(r),Fl(n),Li(s,r);let P=i.reveal==="emerge";P?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let I=a?i.width:"0px",S=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",R=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${I}`,r.style.width=I,r.style.maxWidth=I,r.style.minWidth=I,r.style.minHeight="0",Ox(r,i.maxHeight),r.style.overflow=P||R?"hidden":"visible",r.style.transition=S,P&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",s.style.width=i.width,s.style.minWidth=i.width,s.style.maxWidth=i.width,s.style.boxSizing="border-box")}},$x=(e,t)=>{let n=e.ownerDocument.createElement("div");return Vm(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Vm(n,r)},destroy(){n.remove()}}},Ux=(e,t)=>{var M,P,I,S;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let s=e.tagName.toUpperCase();if(s==="BODY"||s==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let o=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(P=(M=t==null?void 0:t.launcher)==null?void 0:M.enabled)==null||P?(S=(I=t==null?void 0:t.launcher)==null?void 0:I.autoExpand)!=null?S:!1:!0;i.dataset.personaDockRole="push-track",d.dataset.personaDockRole="content",l.dataset.personaDockRole="panel",p.dataset.personaDockRole="host",l.appendChild(p),r.insertBefore(a,e),d.appendChild(e);let f=null,g=()=>{f==null||f.disconnect(),f=null},v=()=>{g(),ur(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Gm(a,i,d,l,p,t,u)}),f.observe(a))},y=!1,w=()=>{Gm(a,i,d,l,p,t,u),v(),u&&!y&&a.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,Nx(a,ur(t)))},A=a.ownerDocument.defaultView,D=()=>{w()};return A==null||A.addEventListener("resize",D),ur(t).reveal==="push"?(i.appendChild(d),i.appendChild(l),a.appendChild(i)):(a.appendChild(d),a.appendChild(l)),w(),{mode:"docked",host:p,shell:a,syncWidgetState(R){let F=R.launcherEnabled?R.open:!0;u!==F&&(u=F,w())},updateConfig(R){var F,N;t=R,((N=(F=t==null?void 0:t.launcher)==null?void 0:F.enabled)!=null?N:!0)===!1&&(u=!0),w()},destroy(){A==null||A.removeEventListener("resize",D),g(),r.isConnected&&(o&&o.parentNode===r?r.insertBefore(e,o):r.appendChild(e)),a.remove()}}},Pi=(e,t)=>hn(t)?Ux(e,t):$x(e,t);var $l={},Jm=!1,jx=e=>{if(typeof window=="undefined"||typeof document=="undefined")throw new Error("Chat widget can only be mounted in a browser environment");if(typeof e=="string"){let t=document.querySelector(e);if(!t)throw new Error(`Chat widget target "${e}" was not found`);return t}return e},qx=()=>{try{if(typeof $l!="undefined"&&$l.url)return new URL("../widget.css",$l.url).href}catch{}return null},Qm=(e,t)=>{let n=qx(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let s=t.head.querySelector("link[data-persona]");if(!s)return;let o=s.cloneNode(!0);e.insertBefore(o,e.firstChild)};if(e instanceof ShadowRoot)if(n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),e.insertBefore(s,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),t.head.appendChild(o)}},Xm=e=>{let t=jx(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,s=e.config,o=Pi(t,s),a,i=[],d=(w,A)=>{var I,S;let M=!((S=(I=A==null?void 0:A.launcher)==null?void 0:I.enabled)!=null?S:!0)||hn(A),P=r.createElement("div");if(P.setAttribute("data-persona-root","true"),M&&(P.style.height="100%",P.style.display="flex",P.style.flexDirection="column",P.style.flex="1",P.style.minHeight="0"),n){let R=w.attachShadow({mode:"open"});R.appendChild(P),Qm(R,r)}else w.appendChild(P),Qm(w,r);return t.id&&P.setAttribute("data-persona-instance",t.id),P},l=()=>{o.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(o.host,s);a=Dl(w,s,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(Jm||(Jm=!0,console.warn("[Persona] `onReady` is deprecated \u2014 use `onChatReady`. `onReady` still works but is removed in the next major.")),e.onReady());let g=w=>{f(),o.destroy(),o=Pi(t,w),s=w,u()},v={update(w){var S,R,F,N,E,U;let A={...s,...w,launcher:{...(S=s==null?void 0:s.launcher)!=null?S:{},...(R=w==null?void 0:w.launcher)!=null?R:{},dock:{...(N=(F=s==null?void 0:s.launcher)==null?void 0:F.dock)!=null?N:{},...(U=(E=w==null?void 0:w.launcher)==null?void 0:E.dock)!=null?U:{}}}},D=hn(s),M=hn(A),P=xo(s),I=xo(A);if(D!==M||P!==I){g(A);return}s=A,o.updateConfig(s),a.update(w),l()},destroy(){f(),o.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(v,{get(w,A,D){if(A==="host")return o.host;if(A in w)return Reflect.get(w,A,D);let M=a[A];return typeof M=="function"?M.bind(a):M}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var ng=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),zx=new Set(["button","a","input","select","textarea","details","summary"]),Vx=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),Ul=/\b(product|card|item|listing|result)\b/i,ql=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,Kx=3e3,Gx=100;function rg(e){let t=typeof e.className=="string"?e.className:"";if(Ul.test(t)||e.id&&Ul.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&Ul.test(r.value))return!0}return!1}function og(e){var t;return ql.test(((t=e.textContent)!=null?t:"").trim())}function sg(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let s=(n=t[r].getAttribute("href"))!=null?n:"";if(s&&s!=="#"&&!s.toLowerCase().startsWith("javascript:"))return!0}return!1}function Jx(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Ym(e){let t=e.match(ql);return t?t[0]:null}function Zm(e){var r,s,o;let t=(r=e.querySelector(".product-title a, h1 a, h2 a, h3 a, h4 a, .title a, a[href]"))!=null?r:e.querySelector("a[href]");if(t&&((s=t.textContent)!=null&&s.trim())){let a=t.getAttribute("href");return{title:t.textContent.trim(),href:a&&a!=="#"?a:null}}let n=e.querySelector("h1, h2, h3, h4, h5, h6");return(o=n==null?void 0:n.textContent)!=null&&o.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function Qx(e){let t=[],n=r=>{let s=r.trim();s&&!t.includes(s)&&t.push(s)};return e.querySelectorAll("button").forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var s;return n((s=r.textContent)!=null?s:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var s;n((s=r.value)!=null?s:"")}),t.slice(0,6)}var Xx="commerce-card",Yx="result-card";function eg(e){return!rg(e)||!og(e)||!sg(e)&&!Jx(e)?0:5200}function tg(e){var r;return!rg(e)||og(e)||!sg(e)||((r=e.textContent)!=null?r:"").trim().length<20||!(!!e.querySelector("h1, h2, h3, h4, h5, h6, .title")||!!e.querySelector(".snippet, .description, p"))?0:2800}var ag=[{id:Xx,scoreElement(e){return eg(e)},shouldSuppressDescendant(e,t,n){if(t===e||!e.contains(t))return!1;if(n.interactivity==="static"){let r=n.text.trim();return!!(r.length===0||ql.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(eg(e)===0)return null;let{title:n,href:r}=Zm(e),s=(p=(l=Ym(((d=e.textContent)!=null?d:"").trim()))!=null?l:Ym(t.text))!=null?p:"",o=Qx(e);return[r&&n?`[${n}](${r})${s?` \u2014 ${s}`:""}`:n?`${n}${s?` \u2014 ${s}`:""}`:s||t.text.trim().slice(0,120),`selector: ${t.selector}`,o.length?`actions: ${o.join(", ")}`:""].filter(Boolean).join(`
108
108
  `)}},{id:Yx,scoreElement(e){return tg(e)},formatSummary(e,t){if(tg(e)===0)return null;let{title:n,href:r}=Zm(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
109
109
  `)}}];function Zx(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function ev(e){var p,u,f,g,v,y,w,A,D,M,P,I,S;let t=(p=e.options)!=null?p:{},n=(f=(u=t.maxElements)!=null?u:e.maxElements)!=null?f:80,r=(v=(g=t.excludeSelector)!=null?g:e.excludeSelector)!=null?v:".persona-host",s=(w=(y=t.maxTextLength)!=null?y:e.maxTextLength)!=null?w:200,o=(D=(A=t.visibleOnly)!=null?A:e.visibleOnly)!=null?D:!0,a=(M=t.root)!=null?M:e.root,i=(P=t.mode)!=null?P:"structured",d=(I=t.maxCandidates)!=null?I:Math.max(500,n*10),l=(S=e.rules)!=null?S:ag;return i==="simple"&&e.rules&&e.rules.length>0?(Zx(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:s,visibleOnly:o,root:a,rules:l}}function jl(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var tv=["data-testid","data-product","data-action","data-id","data-name","data-type"];function nv(e){let t=e.tagName.toLowerCase(),n=e.getAttribute("role");return t==="a"&&e.hasAttribute("href")?"navigable":t==="input"||t==="select"||t==="textarea"||n==="textbox"||n==="combobox"||n==="listbox"||n==="spinbutton"?"input":t==="button"||n==="button"||zx.has(t)||n&&Vx.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function ig(e){if(e.hidden)return!1;try{let t=getComputedStyle(e);if(t.display==="none"||t.visibility==="hidden")return!1}catch{}return!(e.style.display==="none"||e.style.visibility==="hidden")}function rv(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let s=e.getAttribute("aria-label");s&&(t["aria-label"]=s);let o=e.getAttribute("type");o&&(t.type=o);let a=e.getAttribute("value");a&&(t.value=a);let i=e.getAttribute("name");i&&(t.name=i);let d=e.getAttribute("role");d&&(t.role=d);for(let l=0;l<e.attributes.length;l++){let p=e.attributes[l];p.name.startsWith("data-")&&(t[p.name]=p.value)}return t}function lg(e){let t=e.tagName.toLowerCase();if(e.id){let s=`#${jl(e.id)}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}}for(let s of tv){let o=e.getAttribute(s);if(o){let a=`${t}[${s}="${jl(o)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(s=>s&&!s.startsWith("persona-")).slice(0,3);if(n.length>0){let s=`${t}.${n.map(a=>jl(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(s).length===1)return s}catch{}let o=e.parentElement;if(o){let i=Array.from(o.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${s}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let o=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(o>=0)return`${t}:nth-of-type(${o+1})`}return t}function ov(e){return e==="static"?Gx:Kx}function cg(e,t){var s;let n=e.tagName.toLowerCase(),r=((s=e.textContent)!=null?s:"").trim().substring(0,t);return{selector:lg(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:nv(e),attributes:rv(e)}}function sv(e,t,n,r){let s=ov(t.interactivity),o=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(s+=i,a.formatSummary&&!o&&(o=a))}return{score:s,formattingRule:o}}function av(e,t){var n;for(let r of e)if(t.el!==r.el&&(n=r.formattingRule)!=null&&n.shouldSuppressDescendant&&r.el.contains(t.el)&&r.formattingRule.shouldSuppressDescendant(r.el,t.el,t.enriched))return!0;return!1}function iv(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,s=[],o=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&s.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(ng.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!ig(l)){i=a.nextNode();continue}let u=cg(l,e.maxTextLength),f=u.text.length>0,g=Object.keys(u.attributes).length>0&&!Object.keys(u.attributes).every(w=>w==="role");if(!f&&!g){i=a.nextNode();continue}if(r.has(u.selector)){i=a.nextNode();continue}r.add(u.selector);let{score:v,formattingRule:y}=sv(l,u,e.rules,n);s.push({el:l,domIndex:o,enriched:u,score:v,formattingRule:y}),o+=1}i=a.nextNode()}s.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex});let d=[];for(let l of s){if(d.length>=e.maxElements)break;av(d,l)||d.push(l)}return d.sort((l,p)=>{let u=l.enriched.interactivity==="static"?1:0,f=p.enriched.interactivity==="static"?1:0;return u!==f?u-f:u===1&&p.score!==l.score?p.score-l.score:l.domIndex-p.domIndex}),d.map(l=>{var f;let p;if((f=l.formattingRule)!=null&&f.formatSummary){let g=l.formattingRule.formatSummary(l.el,l.enriched,n);g&&(p=g)}let u={...l.enriched};return p&&(u.formattedSummary=p),u})}function lv(e,t){let n=[],r=new Set,s=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),o=s.currentNode;for(;o&&n.length<e.maxElements;){if(o.nodeType===Node.ELEMENT_NODE){let d=o,l=d.tagName.toLowerCase();if(ng.has(l)){o=s.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){o=s.nextNode();continue}}catch{}if(e.visibleOnly&&!ig(d)){o=s.nextNode();continue}let p=cg(d,e.maxTextLength),u=p.text.length>0,f=Object.keys(p.attributes).length>0&&!Object.keys(p.attributes).every(g=>g==="role");if(!u&&!f){o=s.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}o=s.nextNode()}let a=[],i=[];for(let d of n)d.interactivity!=="static"?a.push(d):i.push(d);return[...a,...i].slice(0,e.maxElements)}function cv(e={}){var r;let t=ev(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?lv(t,n):iv(t,n):[]}var Ii=100;function dv(e,t={}){var o;if(e.length===0)return"No page elements found.";let n=(o=t.mode)!=null?o:"structured",r=[];if(n==="structured"){let a=e.map(i=>i.formattedSummary).filter(i=>!!i&&i.length>0);a.length>0&&r.push(`Structured summaries:
110
110
  ${a.map(i=>`- ${i.split(`
@@ -120,7 +120,7 @@ ${a.join(`
120
120
  ${a.join(`
121
121
  `)}`)}return r.join(`
122
122
 
123
- `)}var dg="3.33.0";var As=dg;function uv(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function mv(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function gv(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function fv(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function hv(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function bv(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var yv={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},pg={components:{panel:{borderRadius:"0",shadow:"none"}}},ug={id:"shop",label:"Shopping Assistant",config:{theme:yv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},mg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pg}},gg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pg}},fg={shop:ug,minimal:mg,fullscreen:gg};function xv(e){return fg[e]}var vv=Xm;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function wv(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var hg=`({ text, message }: any) => {
123
+ `)}var dg="3.34.1";var As=dg;function uv(){return{name:"@persona/accessibility",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,interactive:{...e.semantic.colors.interactive,focus:"palette.colors.primary.700",disabled:"palette.colors.gray.300"}}}}},cssVariables:{"--persona-accessibility-focus-ring":"0 0 0 2px var(--persona-semantic-colors-surface, #fff), 0 0 0 4px var(--persona-semantic-colors-interactive-focus, #0f0f0f)"}}}function mv(){return{name:"@persona/animations",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"150ms",normal:"200ms",slow:"300ms",bounce:"500ms cubic-bezier(0.68, -0.55, 0.265, 1.55)"},easings:{easeIn:"cubic-bezier(0.4, 0, 1, 1)",easeOut:"cubic-bezier(0, 0, 0.2, 1)",easeInOut:"cubic-bezier(0.4, 0, 0.2, 1)"}}}},cssVariables:{"--persona-transition-fast":"150ms ease","--persona-transition-normal":"200ms ease","--persona-transition-slow":"300ms ease"}}}function gv(e){return{name:"@persona/brand",version:"1.0.0",transform(t){var r;let n={...t.palette};return(r=e.colors)!=null&&r.primary&&(n.colors={...n.colors,primary:{50:Dr(e.colors.primary,.95),100:Dr(e.colors.primary,.9),200:Dr(e.colors.primary,.8),300:Dr(e.colors.primary,.7),400:Dr(e.colors.primary,.6),500:e.colors.primary,600:Dr(e.colors.primary,.8),700:Dr(e.colors.primary,.7),800:Dr(e.colors.primary,.6),900:Dr(e.colors.primary,.5),950:Dr(e.colors.primary,.45)}}),{...t,palette:n}}}}function fv(){return{name:"@persona/reduced-motion",version:"1.0.0",transform(e){return{...e,palette:{...e.palette,transitions:{fast:"0ms",normal:"0ms",slow:"0ms",bounce:"0ms"}}}},afterResolve(e){return{...e,"--persona-transition-fast":"0ms","--persona-transition-normal":"0ms","--persona-transition-slow":"0ms"}}}}function hv(){return{name:"@persona/high-contrast",version:"1.0.0",transform(e){return{...e,semantic:{...e.semantic,colors:{...e.semantic.colors,text:"palette.colors.gray.950",textMuted:"palette.colors.gray.700",border:"palette.colors.gray.900",divider:"palette.colors.gray.900"}}}}}}function Dr(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),s=parseInt(e.slice(5,7),16),o=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(s+(255-s)*(1-t));return`#${o.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function bv(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var yv={palette:{colors:{primary:{500:"#111827"},accent:{600:"#1d4ed8"},gray:{50:"#ffffff",100:"#f8fafc",200:"#f1f5f9",500:"#6b7280",900:"#000000"}},radius:{sm:"0.75rem",md:"1rem",lg:"1.5rem",launcher:"9999px",button:"9999px"}},semantic:{colors:{primary:"palette.colors.primary.500",textInverse:"palette.colors.gray.50"}}},pg={components:{panel:{borderRadius:"0",shadow:"none"}}},ug={id:"shop",label:"Shopping Assistant",config:{theme:yv,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:pr},copy:{welcomeTitle:"Welcome to our shop!",welcomeSubtitle:"I can help you find products and answer questions",inputPlaceholder:"Ask me anything...",sendButtonLabel:"Send"},suggestionChips:["What can you help me with?","Tell me about your features","How does this work?"]}},mg={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:pg}},gg={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:pg}},fg={shop:ug,minimal:mg,fullscreen:gg};function xv(e){return fg[e]}var vv=Xm;function Jr(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function wv(e){if(e)return{getHeaders:Jr(e.getHeaders),onFeedback:Jr(e.onFeedback),onCopy:Jr(e.onCopy),requestMiddleware:Jr(e.requestMiddleware),actionHandlers:Jr(e.actionHandlers),actionParsers:Jr(e.actionParsers),postprocessMessage:Jr(e.postprocessMessage),contextProviders:Jr(e.contextProviders),streamParser:Jr(e.streamParser)}}var hg=`({ text, message }: any) => {
124
124
  const jsonSource = (message as any).rawContent || text || message.content;
125
125
  if (!jsonSource || typeof jsonSource !== 'string') return null;
126
126
  let cleanJson = jsonSource