@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/README.md +15 -10
- package/dist/codegen.cjs +1 -1
- package/dist/codegen.js +1 -1
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.global.js +191 -190
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +3 -3
- package/dist/index.js.map +1 -1
- package/dist/launcher.global.js +117 -117
- package/dist/launcher.global.js.map +1 -1
- package/dist/smart-dom-reader.d.cts +32 -0
- package/dist/smart-dom-reader.d.ts +32 -0
- package/dist/theme-editor.cjs +13 -13
- package/dist/theme-editor.d.cts +32 -0
- package/dist/theme-editor.d.ts +32 -0
- package/dist/theme-editor.js +14 -14
- package/package.json +3 -3
- package/src/client.test.ts +55 -0
- package/src/client.ts +10 -1
- package/src/codegen.test.ts +0 -14
- package/src/runtime/host-layout.test.ts +51 -9
- package/src/runtime/host-layout.ts +29 -10
- package/src/runtime/init.test.ts +2 -2
- package/src/types.ts +29 -0
- package/src/ui.docked.test.ts +2 -2
- package/src/voice/voice.test.ts +0 -51
- package/src/install-config.test.ts +0 -38
package/dist/index.cjs
CHANGED
|
@@ -6,7 +6,7 @@ ${t}`:"")+(e.description?`
|
|
|
6
6
|
${e.description}`:"");return window.confirm(n)},Hf=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)}},Bf=e=>{if(e===void 0)return"{}";try{let t=JSON.stringify(e);return t===void 0?"{}":t}catch{return"{}"}},Df=e=>{if(e===void 0)return"";try{return JSON.stringify(e)}catch{return String(e)}};var xo=require("partial-json");var h=(e,t)=>{let n=document.createElement(e);return t&&(n.className=t),n},Dr=(e,t,n)=>{let r=e.createElement(t);return n&&(r.className=n),r};var sa="ask_user_question",oa=8,ws="data-persona-ask-sheet-for",Of="Other",Nf="Other\u2026",zu="Type your own answer here",Vu="Send",Ff="Next",_f="Back",$f="Submit all",Uf="Skip",jf=3,vl="data-ask-current-index",wl="data-ask-question-count",Ku="data-ask-answers",Cl="data-ask-grouped",Gu="data-ask-layout",qf=e=>e.layout==="pills"?"pills":"rows",zf=e=>e.getAttribute(Gu)==="pills"?"pills":"rows",qu=!1,Ju=e=>e.replace(/["\\]/g,"\\$&"),Jr=e=>e.variant==="tool"&&!!e.toolCall&&e.toolCall.name===sa,ei=e=>{var t,n;return(n=(t=e==null?void 0:e.features)==null?void 0:t.askUserQuestion)!=null?n:{}},Qr=e=>{let t=e.toolCall;if(!t)return{payload:null,complete:!1};let n=t.status==="complete";if(t.args&&typeof t.args=="object")return{payload:t.args,complete:n};let r=t.chunks;if(!r||r.length===0)return{payload:null,complete:n};try{let o=r.join(""),s=(0,xo.parse)(o,xo.STR|xo.OBJ|xo.ARR);if(s&&typeof s=="object")return{payload:s,complete:n}}catch{}return{payload:null,complete:n}},aa=e=>{let t=Array.isArray(e==null?void 0:e.questions)?e.questions:[];return t.length>oa&&!qu&&(qu=!0,typeof console!="undefined"&&console.warn(`[AgentWidget] ask_user_question received ${t.length} questions; truncating to ${oa}.`)),t.slice(0,oa)},Vf=e=>{var t;return(t=aa(e)[0])!=null?t:null},Kf=(e,t)=>{var n;return(n=aa(e)[t])!=null?n:null},Qu=(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 o=h("span","persona-ask-row-check");r.appendChild(o)}else{let o=h("span","persona-ask-row-badge");o.textContent=String(n+1),r.appendChild(o)}return r},Gf=(e,t,n,r)=>{let s=h("button",n==="rows"?"persona-ask-pill persona-ask-row persona-pointer-events-auto":"persona-ask-pill persona-pointer-events-auto");if(s.type="button",s.setAttribute("role",r?"checkbox":"button"),s.setAttribute("aria-pressed","false"),s.setAttribute("data-ask-user-action","pick"),s.setAttribute("data-option-index",String(t)),s.setAttribute("data-option-label",e.label),n==="rows"){let a=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)}s.appendChild(a);let d=Xu(n,r,t);d&&s.appendChild(d)}else s.textContent=e.label,e.description&&(s.title=e.description);return s},Jf=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},Qf=(e,t,n,r)=>{var p,u,f;let s=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");s.setAttribute("role","group"),s.setAttribute("data-ask-pill-list","true");let a=!!(e!=null&&e.multiSelect),d=(Array.isArray(e==null?void 0:e.options)?e.options:[]).filter(g=>g&&typeof g.label=="string"&&g.label.length>0);if(d.length===0&&!n){for(let g=0;g<jf;g++)s.appendChild(Jf(r));return s}if(d.forEach((g,v)=>{s.appendChild(Gf(g,v,r,a))}),(e==null?void 0:e.allowFreeText)!==!1){let g=r==="rows"?Of:Nf;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:zu,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 S=Xu(r,a,d.length);S&&v.appendChild(S),s.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,s.appendChild(v)}}return s},Yu=(e,t)=>{var s,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 o=document.createElement("input");if(o.type="text",o.className="persona-ask-free-text-input persona-flex-1 persona-pointer-events-auto",o.placeholder=(s=e.freeTextPlaceholder)!=null?s:zu,o.setAttribute("data-ask-free-text-input","true"),r.appendChild(o),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:Vu,i.setAttribute("data-ask-user-action","submit-free-text"),r.appendChild(i)}return r},Xf=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:Vu,n.setAttribute("data-ask-user-action","submit-multi"),n.disabled=!0,t.appendChild(n),t},Yf=(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 o=h("button","persona-ask-nav-back persona-pointer-events-auto");o.type="button",o.textContent=(l=n.backLabel)!=null?l:_f,o.setAttribute("data-ask-user-action","back"),o.disabled=e===0,r.appendChild(o);let s=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:Uf,a.setAttribute("data-ask-user-action","skip"),s.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:$f:(f=n.nextLabel)!=null?f:Ff,i.setAttribute("data-ask-user-action",d?"submit-all":"next"),i.disabled=!0,s.appendChild(i),r.appendChild(s),r},Vo=e=>{let t=e.getAttribute(Ku);if(!t)return{};try{let n=JSON.parse(t);return n&&typeof n=="object"?n:{}}catch{return{}}},Zu=(e,t)=>{e.setAttribute(Ku,JSON.stringify(t))},mr=e=>{var n;let t=Number((n=e.getAttribute(vl))!=null?n:"0");return Number.isFinite(t)?Math.max(0,Math.floor(t)):0},Zf=(e,t)=>{e.setAttribute(vl,String(Math.max(0,Math.floor(t))))},Cs=e=>{var n;let t=Number((n=e.getAttribute(wl))!=null?n:"1");return Number.isFinite(t)?Math.max(1,Math.floor(t)):1},vo=e=>e.getAttribute(Cl)==="true",eh=(e,t)=>{var o;let n=(o=e.agentMetadata)==null?void 0:o.askUserQuestionAnswers;if(!n||typeof n!="object")return{};let r={};return t.forEach((s,a)=>{let i=typeof(s==null?void 0:s.question)=="string"?s.question:"";if(i&&Object.prototype.hasOwnProperty.call(n,i)){let d=n[i];(typeof d=="string"||Array.isArray(d))&&(r[a]=d)}}),r},th=(e,t)=>{var r;let n=(r=e.agentMetadata)==null?void 0:r.askUserQuestionIndex;return typeof n!="number"||!Number.isFinite(n)?0:Math.max(0,Math.min(t-1,Math.floor(n)))},ti=(e,t)=>{let{payload:n}=Qr(t),r=aa(n),o=Vo(e),s={},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(o,d)&&(s[l]=o[d]))}),s},em=e=>{let t=Vo(e),n=mr(e),r=t[n],o=new Set;typeof r=="string"?o.add(r):Array.isArray(r)&&r.forEach(d=>o.add(d));let s=e.querySelectorAll('[data-ask-user-action="pick"][data-option-label]');s.forEach(d=>{var u;let l=(u=d.getAttribute("data-option-label"))!=null?u:"",p=o.has(l);d.setAttribute("aria-pressed",p?"true":"false"),d.classList.toggle("persona-ask-pill-selected",p)});let a=new Set(Array.from(s).map(d=>{var 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=""},tm=e=>{if(!vo(e))return;let t=Vo(e),n=mr(e),r=t[n],o=typeof r=="string"&&r.length>0||Array.isArray(r)&&r.length>0,s=e.querySelector('[data-ask-user-action="next"], [data-ask-user-action="submit-all"]');s&&(s.disabled=!o);let a=e.querySelector('[data-ask-user-action="submit-multi"]');if(a){let i=Array.from(e.querySelectorAll('[aria-pressed="true"][data-option-label]'));a.disabled=i.length===0}},Al=(e,t,n)=>{let r=ei(n),o=zf(e),{payload:s,complete:a}=Qr(t),i=vo(e),d=mr(e),l=Cs(e),p=i?Kf(s,d):Vf(s),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 O=typeof(p==null?void 0:p.question)=="string"?p.question:"";v.textContent=O,v.classList.toggle("persona-ask-question-skeleton",!O&&!a)}let y=e.querySelector('[data-ask-pill-list="true"]');if(y){let O=Qf(p,r,a,o);y.replaceWith(O)}if(o!=="rows"){let O=e.querySelector('[data-ask-free-text-row="true"]');O&&O.replaceWith(Yu(r,o))}let w=e.querySelector('[data-ask-multi-actions="true"]');!i&&u&&!w?e.appendChild(Xf(r)):(!u||i)&&w&&w.remove(),e.setAttribute("data-multi-select",u?"true":"false");let S=e.querySelector('[data-ask-nav-row="true"]');if(i){let O=Yf(d,l,r);S?S.replaceWith(O):e.appendChild(O)}else S&&S.remove();em(e),tm(e)},nh=(e,t,n)=>{let r=ei(t),o=qf(r),s=e.toolCall.id,a=aa(n),i=Math.max(1,a.length),d=i>1,l=eh(e,a),p=d?th(e,i):0,u=h("div",["persona-ask-sheet",`persona-ask-sheet--${o}`,"persona-pointer-events-auto","persona-ask-sheet-enter"].join(" "));u.setAttribute(ws,s),u.setAttribute("data-tool-call-id",s),u.setAttribute("data-message-id",e.id),u.setAttribute(wl,String(i)),u.setAttribute(vl,String(p)),u.setAttribute(Cl,d?"true":"false"),u.setAttribute(Gu,o),Zu(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`),Qu(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",o==="rows"?"persona-ask-pills persona-ask-pills--rows persona-flex persona-flex-col persona-gap-2":"persona-ask-pills persona-flex persona-flex-wrap persona-gap-2");return w.setAttribute("data-ask-pill-list","true"),w.setAttribute("role","group"),u.appendChild(w),o!=="rows"&&u.appendChild(Yu(r,o)),Al(u,e,t),requestAnimationFrame(()=>{requestAnimationFrame(()=>u.classList.remove("persona-ask-sheet-enter"))}),u},rh=(e,t,n)=>{let{payload:r}=Qr(t),o=Math.max(1,aa(r).length);o>Cs(e)&&(e.setAttribute(wl,String(o)),o>1&&!vo(e)&&e.setAttribute(Cl,"true")),Al(e,t,n)},nm=(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=ei(t);Qu(n,r);let o=h("span","persona-ask-stub-label"),{complete:s}=Qr(e);return o.textContent=s?"Awaiting your response\u2026":"Preparing options\u2026",n.appendChild(o),n},As=(e,t,n)=>{if(!n||!Jr(e)||ei(t).enabled===!1)return;let o=e.toolCall.id;n.querySelectorAll(`[${ws}]`).forEach(l=>{l.getAttribute(ws)!==o&&l.remove()});let a=n.querySelector(`[${ws}="${Ju(o)}"]`);if(a){rh(a,e,t);return}let{payload:i}=Qr(e),d=nh(e,t,i);n.appendChild(d)},wo=(e,t)=>{if(!e)return;let n=t?`[${ws}="${Ju(t)}"]`:`[${ws}]`;e.querySelectorAll(n).forEach(o=>{o.classList.add("persona-ask-sheet-leave");let s=Number.parseInt(getComputedStyle(o).getPropertyValue("--persona-ask-sheet-duration")||"180",10);setTimeout(()=>o.remove(),Number.isFinite(s)?s:180)})},Sl=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),Co=(e,t)=>{let n=Vo(e),r=mr(e);typeof t=="string"&&t.length===0||Array.isArray(t)&&t.length===0?delete n[r]:n[r]=t,Zu(e,n),em(e),tm(e)},ni=(e,t,n,r)=>{let o=Cs(e),s=Math.max(0,Math.min(o-1,r));Zf(e,s),Al(e,t,n)};var Sr="suggest_replies";var Tl={type:"object",properties:{suggestions:{type:"array",minItems:1,maxItems:4,description:"1-4 short, distinct follow-up replies, phrased in the user's voice.",items:{type:"string",minLength:1,maxLength:60}}},required:["suggestions"],additionalProperties:!1},ri={name:Sr,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:Tl,origin:"sdk",annotations:{readOnlyHint:!0}},El=()=>({content:[{type:"text",text:"Suggestions shown to the user."}]}),ia=e=>{var t;return e.variant==="tool"&&((t=e.toolCall)==null?void 0:t.name)===Sr},Ml=e=>{let t=e;if(typeof t=="string")try{t=JSON.parse(t)}catch{return[]}let n=t==null?void 0:t.suggestions;if(!Array.isArray(n))return[];let r=n.filter(o=>typeof o=="string").map(o=>o.trim()).filter(o=>o.length>0);return r.length>4?(console.warn(`[persona] suggest_replies: ${r.length} suggestions exceeds the cap of 4; extra suggestions dropped.`),r.slice(0,4)):r},oi=e=>{var t;for(let n=e.length-1;n>=0;n--){let r=e[n];if(r.role==="user")return null;if(!ia(r))continue;let o=Ml((t=r.toolCall)==null?void 0:t.args);return o.length>0?o:null}return null},rm=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 kl={type:"object",properties:{questions:{type:"array",minItems:1,maxItems:oa,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},Ll={name:sa,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:kl,origin:"sdk",annotations:{readOnlyHint:!0}},la=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(Ll),rm(e)&&t.push(ri),t};var Xr=require("partial-json"),si=e=>e.replace(/\\n/g,`
|
|
7
7
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\"),Ss=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)}},oh=e=>{var a,i;let t=(a=e.completedAt)!=null?a:Date.now(),n=(i=e.startedAt)!=null?i:t,o=(e.durationMs!==void 0?e.durationMs:Math.max(0,t-n))/1e3;return o<.1?"Thought for <0.1 seconds":`Thought for ${o>=10?Math.round(o).toString():o.toFixed(1).replace(/\.0$/,"")} seconds`},om=e=>e.status==="complete"?oh(e):e.status==="pending"?"Waiting":"",sh=e=>{var o,s,a;let n=(typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((o=e.completedAt)!=null?o:Date.now())-((a=(s=e.startedAt)!=null?s:e.completedAt)!=null?a:Date.now())))/1e3;return n<.1?"Used tool for <0.1 seconds":`Used tool for ${n>=10?Math.round(n).toString():n.toFixed(1).replace(/\.0$/,"")} seconds`};var sm=e=>e.status==="complete"?sh(e):"Using tool...",ai=e=>{let t=e/1e3;return t<.1?"<0.1s":t>=10?`${Math.round(t)}s`:`${t.toFixed(1).replace(/\.0$/,"")}s`},da=e=>{var n,r,o;let t=typeof e.duration=="number"?e.duration:typeof e.durationMs=="number"?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},ii=e=>{var n,r,o;let t=e.durationMs!==void 0?e.durationMs:Math.max(0,((n=e.completedAt)!=null?n:Date.now())-((o=(r=e.startedAt)!=null?r:e.completedAt)!=null?o:Date.now()));return ai(t)},Pl=(e,t,n)=>{var s;if(!t)return n;let r=((s=e.name)==null?void 0:s.trim())||"tool",o=da(e);return t.replace(/\{toolName\}/g,r).replace(/\{duration\}/g,o)},li=(e,t)=>{let n=e.replace(/\{toolName\}/g,t),r=[],o=/\*\*(.+?)\*\*|\*(.+?)\*|~(.+?)~/g,s=0,a;for(;(a=o.exec(n))!==null;)a.index>s&&ca(r,n.slice(s,a.index),[]),a[1]!==void 0?ca(r,a[1],["bold"]):a[2]!==void 0?ca(r,a[2],["italic"]):a[3]!==void 0&&ca(r,a[3],["dim"]),s=a.index+a[0].length;return s<n.length&&ca(r,n.slice(s),[]),r},ca=(e,t,n)=>{let r=t.split("{duration}");for(let o=0;o<r.length;o++)r[o]&&e.push({text:r[o],styles:n}),o<r.length-1&&e.push({text:"{duration}",styles:n,isDuration:!0})},ah=()=>{let e=null,t=0,n=r=>{let o=/"text"\s*:\s*"((?:[^"\\]|\\.|")*?)"/,s=r.match(o);if(s&&s[1])try{return s[1].replace(/\\n/g,`
|
|
8
8
|
`).replace(/\\r/g,"\r").replace(/\\t/g," ").replace(/\\"/g,'"').replace(/\\\\/g,"\\")}catch{return s[1]}let a=/"text"\s*:\s*"((?:[^"\\]|\\.)*)/,i=r.match(a);if(i&&i[1])try{return i[1].replace(/\\n/g,`
|
|
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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ko=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ah();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Xr.parse)(n,Xr.STR|Xr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},am=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Xr.parse)(s,Xr.STR|Xr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var mi=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 s,a,i;let r=(i=(s=n==null?void 0:n.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 ih="https://api.runtype.com/v1/dispatch",gi="https://api.runtype.com";function lh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Il=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 ch(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var im=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=im(n);if(!im(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Ko(e);return Ko(t)!==null&&a===null?t:e}var Go=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:ih,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:ch(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new vs(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$/,""))||gi}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.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$/,""))||gi}/v1/client/feedback`}async sendFeedback(t){var s,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 o=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t)});if(!o.ok){let i=await o.json().catch(()=>({error:"Feedback submission failed"}));throw o.status===401?(this.clientSession=null,(a=(s=this.config).onSessionExpired)==null||a.call(s),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 o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let I=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:I}),I}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Il).map(I=>{var R,T,W;return{id:I.id,role:I.role,content:(W=(T=(R=I.contentParts)!=null?R:I.llmContent)!=null?T:I.rawContent)!=null?W:I.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?ju(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,S=!1,O=null,k;for(let I=0;;I++){let T={...u,...g&&(S||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T),signal:r.signal}),k.status===409&&I===0&&g){let W=await k.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}O=W!=null?W:{error:"Chat request failed"}}break}if(!k.ok){let I=O!=null?O:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let T=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:T}),T}if(k.status===429){let T=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:T}),T}let R=new Error(I.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!k.body){let I=new Error("No response body received");throw n({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.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 o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||gi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||gi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Il).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}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),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 s,a;let r={messages:t.slice().filter(Il).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}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),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,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,o(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,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,cn,sr,Er;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=H=>{let pe=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Oe=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Qe=H.tools?H.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...H,reasoning:pe,toolCall:Oe,tools:Qe}},u=H=>{if(H.role!=="assistant"||H.variant)return!0;let pe=Array.isArray(H.contentParts)&&H.contentParts.length>0,Oe=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||pe||Oe||!!H.stopReason},f=H=>{u(H)&&n({type:"message",message:p(H)})},g=null,v=null,y={current:null},w={current:null},S=!1,O=new Map,k=new Map,I=new Map,R=new Map,T={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},_=(H,pe,Oe="")=>`${H}::${pe}::${Oe}`,F=(H,pe)=>`${H}::${pe}::`,M=(H,pe,Oe,Qe)=>{let _e=_(H,pe,Oe),Ue=I.get(_e);if(Ue)return Ue;let at=Oe?`-${Oe}`:"",Pt={id:`nested-${H}-${pe}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Qe,parentToolId:H,parentStepId:pe}};return I.set(_e,Pt),f(Pt),Pt},j=H=>{if(H==null)return null;try{return String(H)}catch{return null}},z=H=>{var pe,Oe,Qe,_e,Ue;return j((Ue=(_e=(Qe=(Oe=(pe=H.stepId)!=null?pe:H.step_id)!=null?Oe:H.step)!=null?Qe:H.parentId)!=null?_e:H.flowStepId)!=null?Ue:H.flow_step_id)},oe=H=>{var pe,Oe,Qe,_e,Ue,at,Pt;return j((Pt=(at=(Ue=(_e=(Qe=(Oe=(pe=H.callId)!=null?pe:H.call_id)!=null?Oe:H.requestId)!=null?Qe:H.request_id)!=null?_e:H.toolCallId)!=null?Ue:H.tool_call_id)!=null?at:H.stepId)!=null?Pt:H.step_id)},ke=r,ze=!1,Ae=()=>{if(g)return g;let H;return!ze&&ke?(H=ke,ze=!0):ke&&w.current?H=`${ke}_${w.current}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Re=(H,pe)=>{T.lastId=pe,H&&T.byStep.set(H,pe)},be=(H,pe)=>{var Ue;let Oe=(Ue=H.reasoningId)!=null?Ue:H.id,Qe=z(H);if(Oe){let at=String(Oe);return Re(Qe,at),at}if(Qe){let at=T.byStep.get(Qe);if(at)return T.lastId=at,at}if(T.lastId&&!pe)return T.lastId;if(!pe)return null;let _e=`reason-${l()}`;return Re(Qe,_e),_e},Le=H=>{let pe=O.get(H);if(pe)return pe;let Oe={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"streaming",chunks:[]}};return O.set(H,Oe),f(Oe),Oe},We=(H,pe)=>{W.lastId=pe,H&&W.byCall.set(H,pe)},de=new Set,X=new Map,re=new Set,ce=new Map,ge=H=>{if(!H)return!1;let pe=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},K=(H,pe)=>{var Ue;let Oe=(Ue=H.toolId)!=null?Ue:H.id,Qe=oe(H);if(Oe){let at=String(Oe);return We(Qe,at),at}if(Qe){let at=W.byCall.get(Qe);if(at)return W.lastId=at,at}if(W.lastId&&!pe)return W.lastId;if(!pe)return null;let _e=`tool-${l()}`;return We(Qe,_e),_e},ae=H=>{let pe=k.get(H);if(pe)return pe;let Oe={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:H,status:"pending"}};return k.set(H,Oe),f(Oe),Oe},He=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let pe=Number(H);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let Oe=Date.parse(H);if(!Number.isNaN(Oe))return Oe}return Date.now()},Y=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},ee=new Map,ie=new Map,Se=new Map,Ze=new Map,ve=null,fe=(H,pe,Oe)=>{var Pt;let Qe=Se.get(H);Qe||(Qe=[],Se.set(H,Qe));let _e=0,Ue=Qe.length;for(;_e<Ue;){let Kt=_e+Ue>>>1;Qe[Kt].seq<pe?_e=Kt+1:Ue=Kt}((Pt=Qe[_e])==null?void 0:Pt.seq)===pe?Qe[_e]={seq:pe,text:Oe}:Qe.splice(_e,0,{seq:pe,text:Oe});let at="";for(let Kt=0;Kt<Qe.length;Kt++)at+=Qe[Kt].text;return at},Je=(H,pe)=>{let Oe=Y(pe),Qe=ie.get(H.id),_e=dh(Qe,Oe);H.rawContent=_e;let Ue=ee.get(H.id),at=xt=>{var we;let lt=(we=H.content)!=null?we:"";xt.trim()!==""&&(lt.trim().length===0||xt.startsWith(lt)||xt.trimStart().startsWith(lt.trim()))&&(H.content=xt)},Pt=()=>{var xt;if(Ue){let lt=(xt=Ue.close)==null?void 0:xt.call(Ue);lt instanceof Promise&<.catch(()=>{})}ee.delete(H.id),ie.delete(H.id),H.streaming=!1,f(H)};if(!Ue){at(Oe),Pt();return}let Kt=Ko(_e);if(Kt!==null&&Kt.trim()!==""){at(Kt),Pt();return}let Zt=xt=>{var le;let lt=typeof xt=="string"?xt:(le=xt==null?void 0:xt.text)!=null?le:null;if(lt!==null&<.trim()!=="")return lt;let we=Ue.getExtractedText();return we!==null&&we.trim()!==""?we:Oe},G;try{G=Ue.processChunk(_e)}catch{at(Oe),Pt();return}if(G instanceof Promise){G.then(xt=>{at(Zt(xt)),Pt()}).catch(()=>{at(Oe),Pt()});return}at(Zt(G)),Pt()},De=[],V=!1,ue,ot=()=>{V||(V=!0,queueMicrotask(()=>{V=!1,ue()}))},Et=new mi((H,pe)=>{De.push({payloadType:H,payload:pe}),ot()}),ne=null,Ve=new Map,Nn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ue=()=>{var H,pe,Oe,Qe,_e,Ue,at,Pt,Kt,Zt,G,xt,lt,we,le,nt,tn,Gt,Pn,wn,mt,Mt,et,qt,dn,An,Sn,yn,Mr,At,jn,qn,Nr,fr,vt,Lo,kr,Po,Fn,ss,ro,Fr,St,zn,Vn,In,Lt,ar,ir,Kn,oo,_r,so,Gn,Bt,Rn,lr,ao,$r,io,Lr,Jn,hr,ft,nn,rn,Qn,lo,ye,br,cr,$,as,Pr,Ur,jr,Ir,yr,Ns,Xn,Yn,xr,vr,Io,qr,Tn,Rr,is,Ro,ls,Ba,cs,Da,ds,yt,Fs,dr,_n,Oa,Na,ps,zr,_s,co,$s,Us,js,qs,$n,us,Wr,Hr,zs,Fa,Vs,Ks,Wo,_a,$a,Ua,ja,pl,Ho,po,qa,Gs,uo,za,Js,mo,Qs,Va,Vr,Ka,go,Dt,ms,gs;for(let Bo=0;Bo<De.length;Bo++){let je=De[Bo].payloadType,A=De[Bo].payload;if(je==="reason_start"){let U=(H=be(A,!0))!=null?H:`reason-${l()}`,L=Le(U);L.reasoning=(pe=L.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Qe=L.reasoning.startedAt)!=null?Qe:He((Oe=A.startedAt)!=null?Oe:A.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",f(L)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(Ue=(_e=be(A,!1))!=null?_e:be(A,!0))!=null?Ue:`reason-${l()}`,L=Le(U);L.reasoning=(at=L.reasoning)!=null?at:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Kt=L.reasoning.startedAt)!=null?Kt:He((Pt=A.startedAt)!=null?Pt:A.timestamp);let Z=(xt=(G=(Zt=A.reasoningText)!=null?Zt:A.text)!=null?G:A.delta)!=null?xt:"";if(Z&&A.hidden!==!0){let se=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(se!==void 0){let J=fe(U,se,String(Z));L.reasoning.chunks=[J]}else L.reasoning.chunks.push(String(Z))}if(L.reasoning.status=A.done?"complete":"streaming",A.done){L.reasoning.completedAt=He((lt=A.completedAt)!=null?lt:A.timestamp);let se=(we=L.reasoning.startedAt)!=null?we:Date.now();L.reasoning.durationMs=Math.max(0,((le=L.reasoning.completedAt)!=null?le:Date.now())-se)}L.streaming=L.reasoning.status!=="complete",f(L)}else if(je==="reason_complete"){let U=(tn=(nt=be(A,!1))!=null?nt:be(A,!0))!=null?tn:`reason-${l()}`,L=O.get(U);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=He((Gt=A.completedAt)!=null?Gt:A.timestamp);let se=(Pn=L.reasoning.startedAt)!=null?Pn:Date.now();L.reasoning.durationMs=Math.max(0,((wn=L.reasoning.completedAt)!=null?wn:Date.now())-se),L.streaming=!1,f(L)}let Z=z(A);Z&&T.byStep.delete(Z)}else if(je==="tool_start"){let U=(mt=K(A,!0))!=null?mt:`tool-${l()}`,L=(Mt=A.toolName)!=null?Mt:A.name;if(ge(L)){de.add(U);continue}let Z=ae(U),se=(et=Z.toolCall)!=null?et:{id:U,status:"pending"};se.name=L!=null?L:se.name,se.status="running",A.args!==void 0?se.args=A.args:A.parameters!==void 0&&(se.args=A.parameters),se.startedAt=(dn=se.startedAt)!=null?dn:He((qt=A.startedAt)!=null?qt:A.timestamp),se.completedAt=void 0,se.durationMs=void 0,Z.toolCall=se,Z.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Z.agentMetadata={executionId:(An=J==null?void 0:J.executionId)!=null?An:A.executionId,iteration:(Sn=J==null?void 0:J.iteration)!=null?Sn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(Mr=(yn=K(A,!1))!=null?yn:K(A,!0))!=null?Mr:`tool-${l()}`;if(de.has(U))continue;let L=ae(U),Z=(At=L.toolCall)!=null?At:{id:U,status:"running"};Z.startedAt=(qn=Z.startedAt)!=null?qn:He((jn=A.startedAt)!=null?jn:A.timestamp);let se=(vt=(fr=(Nr=A.text)!=null?Nr:A.delta)!=null?fr:A.message)!=null?vt:"";se&&(Z.chunks=(Lo=Z.chunks)!=null?Lo:[],Z.chunks.push(String(se))),Z.status="running",L.toolCall=Z,L.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(Fn=L.agentMetadata)!=null?Fn:{executionId:(kr=J==null?void 0:J.executionId)!=null?kr:A.executionId,iteration:(Po=J==null?void 0:J.iteration)!=null?Po:A.iteration}),f(L)}else if(je==="tool_complete"){let U=(ro=(ss=K(A,!1))!=null?ss:K(A,!0))!=null?ro:`tool-${l()}`;if(de.has(U)){de.delete(U);continue}let L=ae(U),Z=(Fr=L.toolCall)!=null?Fr:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=He((St=A.completedAt)!=null?St:A.timestamp);let se=(zn=A.duration)!=null?zn:A.executionTime;if(typeof se=="number")Z.durationMs=se;else{let Fe=(Vn=Z.startedAt)!=null?Vn:Date.now();Z.durationMs=Math.max(0,((In=Z.completedAt)!=null?In:Date.now())-Fe)}L.toolCall=Z,L.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(ir=L.agentMetadata)!=null?ir:{executionId:(Lt=J==null?void 0:J.executionId)!=null?Lt:A.executionId,iteration:(ar=J==null?void 0:J.iteration)!=null?ar:A.iteration}),f(L);let Me=oe(A);Me&&W.byCall.delete(Me)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,L=(Kn=U!=null?U:A.toolId)!=null?Kn:`local-${l()}`,Z=ae(L),se=A.toolName,J=zo(se),Me=(oo=Z.toolCall)!=null?oo:{id:L,status:"pending"};Me.name=se,Me.args=A.parameters,Me.status=J?"running":"complete",Me.chunks=(_r=Me.chunks)!=null?_r:[],Me.startedAt=(Gn=Me.startedAt)!=null?Gn:He((so=A.startedAt)!=null?so:A.timestamp),J?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Bt=Me.completedAt)!=null?Bt:Me.startedAt,Z.toolCall=Me,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lr=A.executionId)!=null?lr:(Rn=Z.agentMetadata)==null?void 0:Rn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((ao=A.toolContext)!=null&&ao.toolId)continue;let U=A.partId;if(U!==void 0&&w.current!==null&&U!==w.current){let L=g;L&&(L.streaming=!1,f(L),ve=L,g=null,S=!0)}U!==void 0&&(w.current=U)}else if(je==="text_end"){if(($r=A.toolContext)!=null&&$r.toolId)continue;let U=g;U&&(U.streaming=!1,f(U),ve=U,g=null,S=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Lr=(io=A.id)!=null?io:Z.stepId)!=null?Lr:`step-${l()}`),ct=A.partId!==void 0&&A.partId!==null?String(A.partId):"",tt=`${Z.toolId}::${Fe}`,Wt=R.get(tt);if(ct!==""&&Wt!==void 0&&Wt!==""&&Wt!==ct){let it=I.get(_(Z.toolId,Fe,Wt));it&&it.streaming!==!1&&(it.streaming=!1,f(it))}ct!==""&&R.set(tt,ct);let $t=M(Z.toolId,Fe,ct,Z.executionId),gn=(nn=(ft=(hr=(Jn=A.text)!=null?Jn:A.delta)!=null?hr:A.content)!=null?ft:A.chunk)!=null?nn:"";gn&&($t.content+=String(gn),$t.streaming=!0,f($t)),A.isComplete&&($t.streaming=!1,f($t));continue}let se=A.partId;if(se!==void 0&&w.current!==null&&se!==w.current){let Fe=g;Fe&&(Fe.streaming=!1,f(Fe),ve=Fe,g=null,S=!0)}se!==void 0&&(w.current=se);let J=se!==void 0&&(rn=Ze.get(se))!=null?rn:Ae();se!==void 0&&(J.partId||(J.partId=se),Ze.set(se,J));let Me=(br=(ye=(lo=(Qn=A.text)!=null?Qn:A.delta)!=null?lo:A.content)!=null?ye:A.chunk)!=null?br:"";if(Me){let Fe=typeof A.seq=="number"?A.seq:void 0,ct=se!=null?se:J.id,tt=Fe!==void 0?fe(ct,Fe,String(Me)):((cr=ie.get(J.id))!=null?cr:"")+Me;J.rawContent=tt,ee.has(J.id)||ee.set(J.id,this.createStreamParser());let Wt=ee.get(J.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(J.id,tt),Wt.__isPlainTextParser===!0){J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J);continue}let it=Wt.processChunk(tt);if(it instanceof Promise)it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null&&en.trim()!=="")J.content=en,f(J);else if(!$t&&!tt.trim().startsWith("<")){let Cn=g,Qt=Cn&&Cn.id===J.id?Cn:J;Qt.id===J.id&&(Qt.content=Fe!==void 0?tt:Qt.content+Me,ie.delete(Qt.id),ee.delete(Qt.id),Qt.rawContent=void 0,f(Qt))}}).catch(()=>{J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J)});else{let ht=typeof it=="string"?it:($=it==null?void 0:it.text)!=null?$:null;ht!==null&&ht.trim()!==""?(J.content=ht,f(J)):!$t&&!tt.trim().startsWith("<")&&(J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J))}}if(A.isComplete){let Fe=(Pr=(as=A.result)==null?void 0:as.response)!=null?Pr:J.content;if(Fe){let ct=ie.get(J.id),tt=ct!=null?ct:Y(Fe);J.rawContent=tt;let Wt=ee.get(J.id),$t=null,gn=!1;if(Wt&&($t=Wt.getExtractedText(),$t===null&&($t=Ko(tt)),$t===null)){let it=Wt.processChunk(tt);it instanceof Promise?(gn=!0,it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null){let Cn=g;Cn&&Cn.id===J.id&&(Cn.content=en,Cn.streaming=!1,ee.delete(Cn.id),ie.delete(Cn.id),f(Cn))}})):$t=typeof it=="string"?it:(Ur=it==null?void 0:it.text)!=null?Ur:null}if(!gn){$t!==null&&$t.trim()!==""?J.content=$t:ie.has(J.id)||(J.content=Y(Fe));let it=ee.get(J.id);if(it){let ht=(jr=it.close)==null?void 0:jr.call(it);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(J.id)}ie.delete(J.id),J.streaming=!1,f(J)}}}}else if(je==="step_complete"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((yr=(Ir=A.id)!=null?Ir:Z.stepId)!=null?yr:"");if(Fe){let ct=F(Z.toolId,Fe);for(let[tt,Wt]of I)tt.startsWith(ct)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${Z.toolId}::${Fe}`)}continue}let se=A.stopReason;if(S){if(g!==null){let tt=g;se&&(tt.stopReason=se),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,f(tt))}let Fe=(Ns=A.result)==null?void 0:Ns.response,ct=ve;ct&&(se&&(ct.stopReason=se),Fe!=null?Je(ct,Fe):(ee.delete(ct.id),ie.delete(ct.id))),ve=null;continue}let J=(Xn=A.result)==null?void 0:Xn.response,Me=Ae();if(se&&(Me.stopReason=se),J!=null){let Fe=ee.get(Me.id),ct=!1,tt=!1;if(Fe){let Wt=Fe.getExtractedText(),$t=ie.get(Me.id),gn=$t!=null?$t:Y(J);if(Me.rawContent=gn,Wt!==null&&Wt.trim()!=="")Me.content=Wt,ct=!0;else{let it=Ko(gn);if(it!==null)Me.content=it,ct=!0;else{let ht=Fe.processChunk(gn);if(ht instanceof Promise)tt=!0,ht.then(en=>{var Cn;let Ge=typeof en=="string"?en:(Cn=en==null?void 0:en.text)!=null?Cn:null;if(Ge!==null&&Ge.trim()!==""){let Qt=g;Qt&&Qt.id===Me.id&&(Qt.content=Ge,Qt.streaming=!1,ee.delete(Qt.id),ie.delete(Qt.id),f(Qt))}else{let Qt=Fe.getExtractedText(),xn=g;xn&&xn.id===Me.id&&(Qt!==null&&Qt.trim()!==""?xn.content=Qt:ie.has(xn.id)||(xn.content=Y(J)),xn.streaming=!1,ee.delete(xn.id),ie.delete(xn.id),f(xn))}});else{let en=typeof ht=="string"?ht:(Yn=ht==null?void 0:ht.text)!=null?Yn:null;if(en!==null&&en.trim()!=="")Me.content=en,ct=!0;else{let Ge=Fe.getExtractedText();Ge!==null&&Ge.trim()!==""&&(Me.content=Ge,ct=!0)}}}}}if(!tt){if(!Me.rawContent){let Wt=ie.get(Me.id);Me.rawContent=Wt!=null?Wt:Y(J)}if(!ct&&!ie.has(Me.id)&&(Me.content=Y(J)),Fe){let Wt=(xr=Fe.close)==null?void 0:xr.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}}else ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}else if(je==="flow_complete"){let U=(vr=A.result)==null?void 0:vr.response;if(S){if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}}else if(U!=null){let L=Ae(),Z=ie.get(L.id),se=Z!=null?Z:Y(U);L.rawContent=se;let J=Y(U),Me=ee.get(L.id);if(Me){let tt=Ko(se);if(tt!==null)J=tt;else{let Wt=Me.processChunk(se);Wt instanceof Promise&&Wt.then(gn=>{var ht;let it=typeof gn=="string"?gn:(ht=gn==null?void 0:gn.text)!=null?ht:null;it!==null&&(L.content=it,L.streaming=!1,f(L))});let $t=Me.getExtractedText();$t!==null&&(J=$t)}}ee.delete(L.id),ie.delete(L.id);let Fe=J!==L.content,ct=L.streaming!==!1;Fe&&(L.content=J),L.streaming=!1,(Fe||ct)&&f(L)}else if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}n({type:"status",status:"idle"})}else if(je==="agent_start")ne={executionId:A.executionId,agentId:(Io=A.agentId)!=null?Io:"virtual",agentName:(qr=A.agentName)!=null?qr:"",status:"running",currentIteration:0,maxTurns:(Tn=A.maxTurns)!=null?Tn:1,startedAt:He(A.startedAt)};else if(je==="agent_iteration_start"){if(ne&&(ne.currentIteration=A.iteration),Nn==="separate"&&A.iteration>1){let U=g;U&&(U.streaming=!1,f(U),Ve.set(A.iteration-1,U),g=null)}}else if(je==="agent_turn_start")v=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=Ae();U.content+=(Rr=A.delta)!=null?Rr:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ne==null?void 0:ne.agentName},v=U,f(U)}else if(A.contentType==="thinking"){let U=(is=A.turnId)!=null?is:`agent-think-${A.iteration}`,L=Le(U);L.reasoning=(Ro=L.reasoning)!=null?Ro:{id:U,status:"streaming",chunks:[]},L.reasoning.chunks.push((ls=A.delta)!=null?ls:""),L.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(L)}else if(A.contentType==="tool_input"){let U=(Ba=A.toolCallId)!=null?Ba:W.lastId;if(U){let L=k.get(U);L!=null&&L.toolCall&&(L.toolCall.chunks=(cs=L.toolCall.chunks)!=null?cs:[],L.toolCall.chunks.push((Da=A.delta)!=null?Da:""),f(L))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let se=O.get(U);if(se!=null&&se.reasoning){se.reasoning.status="complete",se.reasoning.completedAt=He(A.completedAt);let J=(ds=se.reasoning.startedAt)!=null?ds:Date.now();se.reasoning.durationMs=Math.max(0,((yt=se.reasoning.completedAt)!=null?yt:Date.now())-J),se.streaming=!1,f(se)}}let L=A.stopReason,Z=g!=null?g:v;if(L&&Z!==null){let se=A.turnId;(!se||((Fs=Z.agentMetadata)==null?void 0:Fs.turnId)===se)&&(Z.stopReason=L,f(Z))}}else if(je==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let U=(dr=A.toolCallId)!=null?dr:`agent-tool-${l()}`;We(oe(A),U);let L=ae(U),Z=(_n=L.toolCall)!=null?_n:{id:U,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};Z.name=(Na=(Oa=A.toolName)!=null?Oa:A.name)!=null?Na:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=He((ps=A.startedAt)!=null?ps:A.timestamp),L.toolCall=Z,L.streaming=!0,L.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(L)}else if(je==="agent_tool_delta"){let U=(zr=A.toolCallId)!=null?zr:W.lastId;if(U){let L=(_s=k.get(U))!=null?_s:ae(U);L.toolCall&&(L.toolCall.chunks=(co=L.toolCall.chunks)!=null?co:[],L.toolCall.chunks.push(($s=A.delta)!=null?$s:""),L.toolCall.status="running",L.streaming=!0,f(L))}}else if(je==="agent_tool_complete"){let U=(Us=A.toolCallId)!=null?Us:W.lastId;if(U){let L=(js=k.get(U))!=null?js:ae(U);if(L.toolCall){L.toolCall.status="complete",A.result!==void 0&&(L.toolCall.result=A.result),typeof A.executionTime=="number"&&(L.toolCall.durationMs=A.executionTime),L.toolCall.completedAt=He((qs=A.completedAt)!=null?qs:A.timestamp),L.streaming=!1,f(L);let Z=oe(A);Z&&W.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],L=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let se=Z,J=typeof se.type=="string"?se.type:void 0,Me=typeof se.mediaType=="string"?se.mediaType.toLowerCase():"",Fe=null,ct="";if(J==="media"){let tt=typeof se.data=="string"?se.data:void 0;if(!tt)continue;ct=Me.length>0?Me:"application/octet-stream",Fe=`data:${ct};base64,${tt}`}else if(J==="image-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else if(J==="file-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else continue;if(Fe)if(J==="image-url"||ct.startsWith("image/"))L.push({type:"image",image:Fe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))L.push({type:"audio",audio:Fe,mimeType:ct});else if(ct.startsWith("video/"))L.push({type:"video",video:Fe,mimeType:ct});else{let tt=ct||"application/octet-stream";L.push({type:"file",data:Fe,mimeType:tt,filename:lh(tt)})}}if(L.length>0){let Z=l(),se=A.toolCallId,Me={id:`agent-media-${typeof se=="string"&&se.length>0?`${se}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Me);let Fe=g;Fe&&(Fe.streaming=!1,f(Fe)),g=null,y.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,L={id:U,role:"assistant",content:($n=A.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(us=A.reflection)!=null?us:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(L)}else if(je==="agent_complete"){ne&&(ne.status=A.success?"complete":"error",ne.completedAt=He(A.completedAt),ne.stopReason=A.stopReason);let U=g;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Hr=(Wr=A.error)==null?void 0:Wr.message)!=null?Hr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(zs=A.approvalId)!=null?zs:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Fa=ne==null?void 0:ne.agentId)!=null?Fa:"virtual",executionId:(Ks=(Vs=A.executionId)!=null?Vs:ne==null?void 0:ne.executionId)!=null?Ks:"",toolName:(Wo=A.toolName)!=null?Wo:"",toolType:A.toolType,description:($a=A.description)!=null?$a:`Execute ${(_a=A.toolName)!=null?_a:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(Ua=A.approvalId)!=null?Ua:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ja=ne==null?void 0:ne.agentId)!=null?ja:"virtual",executionId:(Ho=(pl=A.executionId)!=null?pl:ne==null?void 0:ne.executionId)!=null?Ho:"",toolName:(po=A.toolName)!=null?po:"",toolType:A.toolType,description:(Gs=A.description)!=null?Gs:`Execute ${(qa=A.toolName)!=null?qa:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(uo=A.decision)!=null?uo:"approved",agentId:(za=ne==null?void 0:ne.agentId)!=null?za:"virtual",executionId:(mo=(Js=A.executionId)!=null?Js:ne==null?void 0:ne.executionId)!=null?mo:"",toolName:(Qs=A.toolName)!=null?Qs:"",description:(Va=A.description)!=null?Va:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,L=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:L,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),ce.set(L,{markdown:"",title:Z}),!re.has(L)){re.add(L);let se={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Z,artifactType:U,status:"streaming"}})};X.set(L,se),f(se)}}else if(je==="artifact_delta"){let U=String(A.id),L=typeof A.delta=="string"?A.delta:String((Vr=A.delta)!=null?Vr:"");n({type:"artifact_delta",id:U,artDelta:L});let Z=ce.get(U);Z&&(Z.markdown+=L)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let L=X.get(U);if(L){L.streaming=!1;try{let Z=JSON.parse((Ka=L.rawContent)!=null?Ka:"{}");if(Z.props){Z.props.status="complete";let se=ce.get(U);se!=null&&se.markdown&&(Z.props.markdown=se.markdown)}L.rawContent=JSON.stringify(Z)}catch{}ce.delete(U),f(L),X.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let L=String((go=U.id)!=null?go:`msg-${l()}`),Z=U.role,J={id:L,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(J),J.rawContent)try{let Me=JSON.parse(J.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}g=null,y.current=null,ee.delete(L),ie.delete(L)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let L=(ms=A.message)!=null?ms:A.error;L!=null&&L!==""&&(U=new Error(String(L)))}else if(je==="step_error"||je==="flow_error"){let L=A.error;typeof L=="string"&&L!==""?U=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(U=new Error(String((gs=L.message)!=null?gs:L)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let L=g;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}De.length=0};;){let{done:H,value:pe}=await o.read();if(H)break;a+=s.decode(pe,{stream:!0});let Oe=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 o=r.trim();if(!o.startsWith("{")&&!o.startsWith("["))return null;let s=n(r);return s!==null&&(e=s),t=r.length,e!==null?{text:e,raw:r}:null},close:async()=>{}}},Ko=e=>{try{let t=JSON.parse(e);if(t&&typeof t=="object"&&typeof t.text=="string")return t.text}catch{return null}return null},ci=()=>{let e={processChunk:t=>null,getExtractedText:()=>null};return e.__isPlainTextParser=!0,e},di=()=>{var t;let e=ah();return{processChunk:async n=>{let r=n.trim();return!r.startsWith("{")&&!r.startsWith("[")?null:e.processChunk(n)},getExtractedText:e.getExtractedText.bind(e),close:(t=e.close)==null?void 0:t.bind(e)}},pi=()=>{let e=null,t=0;return{getExtractedText:()=>e,processChunk:n=>{let r=n.trim();if(!r.startsWith("{")&&!r.startsWith("["))return null;if(n.length<=t)return e!==null||e===""?{text:e||"",raw:n}:null;try{let o=(0,Xr.parse)(n,Xr.STR|Xr.OBJ);o&&typeof o=="object"&&(o.component&&typeof o.component=="string"?e=typeof o.text=="string"?si(o.text):"":o.type==="init"&&o.form?e="":typeof o.text=="string"&&(e=si(o.text)))}catch{}return t=n.length,e!==null?{text:e,raw:n}:null},close:()=>{}}},am=e=>{let t=null,n=0,o=e||(s=>{if(!s||typeof s!="object")return null;let a=i=>typeof i=="string"?si(i):null;if(s.component&&typeof s.component=="string")return typeof s.text=="string"?si(s.text):"";if(s.type==="init"&&s.form)return"";if(s.action)switch(s.action){case"nav_then_click":return a(s.on_load_text)||a(s.text)||null;case"message":case"message_and_click":case"checkout":return a(s.text)||null;default:return a(s.text)||a(s.display_text)||a(s.message)||null}return a(s.text)||a(s.display_text)||a(s.message)||a(s.content)||null});return{getExtractedText:()=>t,processChunk:s=>{let a=s.trim();if(!a.startsWith("{")&&!a.startsWith("["))return null;if(s.length<=n)return t!==null?{text:t,raw:s}:null;try{let i=(0,Xr.parse)(s,Xr.STR|Xr.OBJ),d=o(i);d!==null&&(t=d)}catch{}return n=s.length,{text:t||"",raw:s}},close:()=>{}}},ui=()=>{let e=null;return{processChunk:t=>{if(!t.trim().startsWith("<"))return null;let r=t.match(/<text[^>]*>([\s\S]*?)<\/text>/);return r&&r[1]?(e=r[1],{text:e,raw:t}):null},getExtractedText:()=>e}};var mi=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 s,a,i;let r=(i=(s=n==null?void 0:n.seq)!=null?s: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 o=this.buffer.get(r);o!==void 0&&(typeof console!="undefined"&&typeof console.warn=="function"&&console.warn(`[persona] SequenceReorderBuffer: duplicate seq=${r} (${o.payloadType} vs ${t}); emitting earlier event out-of-order to avoid loss`),this.emitter(o.payloadType,o.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 ih="https://api.runtype.com/v1/dispatch",gi="https://api.runtype.com";function lh(e){var s,a;let t=e.toLowerCase(),r={"application/pdf":"pdf","application/json":"json","application/zip":"zip","text/plain":"txt","text/csv":"csv","text/markdown":"md"}[t];if(r)return`attachment.${r}`;let o=t.indexOf("/");if(o>0){let i=(a=(s=t.slice(o+1).split(";")[0])==null?void 0:s.trim())!=null?a:"";if(i&&i!=="octet-stream"&&/^[a-z0-9.+-]+$/i.test(i))return`attachment.${i}`}return"attachment"}var Il=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 ch(e){switch(e){case"json":return pi;case"regex-json":return di;case"xml":return ui;default:return ci}}var im=e=>e.startsWith("{")||e.startsWith("[")||e.startsWith("<");function dh(e,t){if(!e)return t;let n=e.trim(),r=t.trim();if(n.length===0)return t;if(r.length===0)return e;let o=im(n);if(!im(r))return e;if(!o||r===n||r.startsWith(n))return t;let a=Ko(e);return Ko(t)!==null&&a===null?t:e}var Go=class{constructor(t={}){this.config=t;this.clientSession=null;this.sessionInitPromise=null;this.lastSentClientToolsFingerprint=null;this.clientToolsFingerprintSessionId=null;var n,r,o,s;this.apiUrl=(n=t.apiUrl)!=null?n:ih,this.headers={"Content-Type":"application/json",...t.headers},this.debug=!!t.debug,this.createStreamParser=(r=t.streamParser)!=null?r:ch(t.parserType),this.contextProviders=(o=t.contextProviders)!=null?o:[],this.requestMiddleware=t.requestMiddleware,this.customFetch=t.customFetch,this.parseSSEEvent=t.parseSSEEvent,this.getHeaders=t.getHeaders,this.webMcpBridge=((s=t.webmcp)==null?void 0:s.enabled)===!0?new vs(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$/,""))||gi}/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 s,a;let t=((a=(s=this.config).getStoredSessionId)==null?void 0:a.call(s))||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 o=await r.json();return this.config.setStoredSessionId&&this.config.setStoredSessionId(o.sessionId),{sessionId:o.sessionId,expiresAt:new Date(o.expiresAt),flow:o.flow,config:{welcomeMessage:o.config.welcomeMessage,placeholder:o.config.placeholder,theme:o.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$/,""))||gi}/v1/client/feedback`}async sendFeedback(t){var a,i;if(!this.isClientTokenMode())throw new Error("sendFeedback() only available in client token mode");if(!this.getClientSession())throw new Error("No active session. Please initialize session first.");if(["upvote","downvote","copy"].includes(t.type)&&!t.messageId)throw new Error(`messageId is required for ${t.type} feedback type`);if(t.type==="csat"&&(t.rating===void 0||t.rating<1||t.rating>5))throw new Error("CSAT rating must be between 1 and 5");if(t.type==="nps"&&(t.rating===void 0||t.rating<0||t.rating>10))throw new Error("NPS rating must be between 0 and 10");this.debug&&console.debug("[AgentWidgetClient] sending feedback",t);let o={...t,...this.config.clientToken&&{token:this.config.clientToken}},s=await fetch(this.getFeedbackApiUrl(),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(o)});if(!s.ok){let d=await s.json().catch(()=>({error:"Feedback submission failed"}));throw s.status===401?(this.clientSession=null,(i=(a=this.config).onSessionExpired)==null||i.call(a),new Error("Session expired. Please refresh to continue.")):new Error(d.error||"Failed to submit feedback")}}async submitMessageFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,messageId:t,type:n})}async submitCSATFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"csat",rating:t,comment:n})}async submitNPSFeedback(t,n){let r=this.getClientSession();if(!r)throw new Error("No active session. Please initialize session first.");return this.sendFeedback({sessionId:r.sessionId,type:"nps",rating:t,comment:n})}async dispatch(t,n){return this.isAgentMode()?this.dispatchAgent(t,n):this.isClientTokenMode()?this.dispatchClientToken(t,n):this.dispatchProxy(t,n)}async dispatchClientToken(t,n){var o,s,a,i;let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});try{let d=await this.initSession();if(new Date>=new Date(d.expiresAt.getTime()-6e4)){this.clearClientSession(),(s=(o=this.config).onSessionExpired)==null||s.call(o);let I=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:I}),I}let l=await this.buildPayload(t.messages),p=l.metadata?Object.fromEntries(Object.entries(l.metadata).filter(([I])=>I!=="sessionId"&&I!=="session_id")):void 0,u={sessionId:d.sessionId,messages:t.messages.filter(Il).map(I=>{var R,T,W;return{id:I.id,role:I.role,content:(W=(T=(R=I.contentParts)!=null?R:I.llmContent)!=null?T:I.rawContent)!=null?W:I.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?ju(f):void 0,y=this.clientToolsFingerprintSessionId===d.sessionId,w=g&&y&&this.lastSentClientToolsFingerprint===v,S=!1,O=null,k;for(let I=0;;I++){let T={...u,...g&&(S||!w)&&f?{clientTools:f}:{},...v?{clientToolsFingerprint:v}:{}};if(this.debug&&console.debug("[AgentWidgetClient] client token dispatch",T),k=await fetch(this.getClientApiUrl("chat"),{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(T),signal:r.signal}),k.status===409&&I===0&&g){let W=await k.json().catch(()=>null);if((W==null?void 0:W.error)==="client_tools_resend_required"){S=!0,this.lastSentClientToolsFingerprint=null;continue}O=W!=null?W:{error:"Chat request failed"}}break}if(!k.ok){let I=O!=null?O:await k.json().catch(()=>({error:"Chat request failed"}));if(k.status===401){this.clearClientSession(),(i=(a=this.config).onSessionExpired)==null||i.call(a);let T=new Error("Session expired. Please refresh to continue.");throw n({type:"error",error:T}),T}if(k.status===429){let T=new Error(I.hint||"Message limit reached for this session.");throw n({type:"error",error:T}),T}let R=new Error(I.error||"Failed to send message");throw n({type:"error",error:R}),R}if(!k.body){let I=new Error("No response body received");throw n({type:"error",error:I}),I}this.lastSentClientToolsFingerprint=v!=null?v:null,this.clientToolsFingerprintSessionId=d.sessionId,n({type:"status",status:"connected"});try{await this.streamResponse(k.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 o=await this.buildPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Chat backend request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n)}finally{n({type:"status",status:"idle"})}}async dispatchAgent(t,n){let r=new AbortController;t.signal&&t.signal.addEventListener("abort",()=>r.abort()),n({type:"status",status:"connecting"});let o=await this.buildAgentPayload(t.messages);this.debug&&console.debug("[AgentWidgetClient] agent dispatch payload",o);let s={...this.headers};if(this.getHeaders)try{let i=await this.getHeaders();s={...s,...i}}catch(i){typeof console!="undefined"&&console.error("[AgentWidget] getHeaders error:",i)}let a;if(this.customFetch)try{a=await this.customFetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal},o)}catch(i){let d=i instanceof Error?i:new Error(String(i));throw n({type:"error",error:d}),d}else a=await fetch(this.apiUrl,{method:"POST",headers:s,body:JSON.stringify(o),signal:r.signal});if(!a.ok||!a.body){let i=new Error(`Agent execution request failed: ${a.status} ${a.statusText}`);throw n({type:"error",error:i}),i}n({type:"status",status:"connected"});try{await this.streamResponse(a.body,n,t.assistantMessageId)}finally{n({type:"status",status:"idle"})}}async processStream(t,n,r){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 o=`${((a=this.config.apiUrl)==null?void 0:a.replace(/\/+$/,"").replace(/\/v1\/dispatch$/,""))||gi}/v1/agents/${t.agentId}/approve`,s={"Content-Type":"application/json",...this.headers};return this.getHeaders&&Object.assign(s,await this.getHeaders()),fetch(o,{method:"POST",headers:s,body:JSON.stringify({executionId:t.executionId,approvalId:t.approvalId,decision:n,streamResponse:!0})})}async resumeFlow(t,n,r){var l,p;let o=this.isClientTokenMode(),s=o?this.getClientApiUrl("resume"):`${((l=this.config.apiUrl)==null?void 0:l.replace(/\/+$/,""))||gi}/resume`,a;o&&(a=(await this.initSession()).sessionId);let i={"Content-Type":"application/json",...this.headers};this.getHeaders&&Object.assign(i,await this.getHeaders());let d={executionId:t,toolOutputs:n,streamResponse:(p=r==null?void 0:r.streamResponse)!=null?p:!0};return a&&(d.sessionId=a),fetch(s,{method:"POST",headers:i,body:JSON.stringify(d),signal:r==null?void 0:r.signal})}async buildAgentPayload(t){var s,a;if(!this.config.agent)throw new Error("Agent configuration required for agent mode");let n=t.slice().filter(Il).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}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),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 s,a;let r={messages:t.slice().filter(Il).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}},o=[...la(this.config),...(a=await((s=this.webMcpBridge)==null?void 0:s.snapshotForDispatch()))!=null?a:[]];if(o.length>0&&(r.clientTools=o),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,o,s,a){if(!this.parseSSEEvent)return!1;try{let i=await this.parseSSEEvent(t);if(i===null)return!1;let d=p=>{let u={id:`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"assistant",sequence:s(),...p!==void 0&&{partId:p}};return r.current=u,o(u),u},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,o(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,o(p)}return i.done&&(r.current&&(r.current.streaming=!1,o(r.current)),a.current=null,n({type:"status",status:"idle"})),i.error&&(a.current=null,n({type:"error",error:new Error(i.error)})),!0}catch(i){return typeof console!="undefined"&&console.error("[AgentWidget] parseSSEEvent error:",i),!1}}async streamResponse(t,n,r){var Ht,cn,sr,Er;let o=t.getReader(),s=new TextDecoder,a="",i=Date.now(),d=0,l=()=>i+d++,p=H=>{let pe=H.reasoning?{...H.reasoning,chunks:[...H.reasoning.chunks]}:void 0,Oe=H.toolCall?{...H.toolCall,chunks:H.toolCall.chunks?[...H.toolCall.chunks]:void 0}:void 0,Qe=H.tools?H.tools.map(_e=>({..._e,chunks:_e.chunks?[..._e.chunks]:void 0})):void 0;return{...H,reasoning:pe,toolCall:Oe,tools:Qe}},u=H=>{if(H.role!=="assistant"||H.variant)return!0;let pe=Array.isArray(H.contentParts)&&H.contentParts.length>0,Oe=typeof H.rawContent=="string"&&H.rawContent.trim()!=="";return typeof H.content=="string"&&H.content.trim()!==""||pe||Oe||!!H.stopReason},f=H=>{u(H)&&n({type:"message",message:p(H)})},g=null,v=null,y={current:null},w={current:null},S=!1,O=new Map,k=new Map,I=new Map,R=new Map,T={lastId:null,byStep:new Map},W={lastId:null,byCall:new Map},_=(H,pe,Oe="")=>`${H}::${pe}::${Oe}`,F=(H,pe)=>`${H}::${pe}::`,M=(H,pe,Oe,Qe)=>{let _e=_(H,pe,Oe),Ue=I.get(_e);if(Ue)return Ue;let at=Oe?`-${Oe}`:"",Pt={id:`nested-${H}-${pe}${at}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),...Oe?{partId:Oe}:{},agentMetadata:{executionId:Qe,parentToolId:H,parentStepId:pe}};return I.set(_e,Pt),f(Pt),Pt},j=H=>{if(H==null)return null;try{return String(H)}catch{return null}},z=H=>{var pe,Oe,Qe,_e,Ue;return j((Ue=(_e=(Qe=(Oe=(pe=H.stepId)!=null?pe:H.step_id)!=null?Oe:H.step)!=null?Qe:H.parentId)!=null?_e:H.flowStepId)!=null?Ue:H.flow_step_id)},oe=H=>{var pe,Oe,Qe,_e,Ue,at,Pt;return j((Pt=(at=(Ue=(_e=(Qe=(Oe=(pe=H.callId)!=null?pe:H.call_id)!=null?Oe:H.requestId)!=null?Qe:H.request_id)!=null?_e:H.toolCallId)!=null?Ue:H.tool_call_id)!=null?at:H.stepId)!=null?Pt:H.step_id)},ke=r,ze=!1,Ae=()=>{if(g)return g;let H;return!ze&&ke?(H=ke,ze=!0):ke&&w.current?H=`${ke}_${w.current}`:H=`assistant-${Date.now()}-${Math.random().toString(16).slice(2)}`,g={id:H,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l()},f(g),g},Re=(H,pe)=>{T.lastId=pe,H&&T.byStep.set(H,pe)},be=(H,pe)=>{var Ue;let Oe=(Ue=H.reasoningId)!=null?Ue:H.id,Qe=z(H);if(Oe){let at=String(Oe);return Re(Qe,at),at}if(Qe){let at=T.byStep.get(Qe);if(at)return T.lastId=at,at}if(T.lastId&&!pe)return T.lastId;if(!pe)return null;let _e=`reason-${l()}`;return Re(Qe,_e),_e},Le=H=>{let pe=O.get(H);if(pe)return pe;let Oe={id:`reason-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"reasoning",sequence:l(),reasoning:{id:H,status:"streaming",chunks:[]}};return O.set(H,Oe),f(Oe),Oe},We=(H,pe)=>{W.lastId=pe,H&&W.byCall.set(H,pe)},de=new Set,X=new Map,re=new Set,ce=new Map,ge=H=>{if(!H)return!1;let pe=H.replace(/_+/g,"_").replace(/^_|_$/g,"");return pe==="emit_artifact_markdown"||pe==="emit_artifact_component"},K=(H,pe)=>{var Ue;let Oe=(Ue=H.toolId)!=null?Ue:H.id,Qe=oe(H);if(Oe){let at=String(Oe);return We(Qe,at),at}if(Qe){let at=W.byCall.get(Qe);if(at)return W.lastId=at,at}if(W.lastId&&!pe)return W.lastId;if(!pe)return null;let _e=`tool-${l()}`;return We(Qe,_e),_e},ae=H=>{let pe=k.get(H);if(pe)return pe;let Oe={id:`tool-${H}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,variant:"tool",sequence:l(),toolCall:{id:H,status:"pending"}};return k.set(H,Oe),f(Oe),Oe},He=H=>{if(typeof H=="number"&&Number.isFinite(H))return H;if(typeof H=="string"){let pe=Number(H);if(!Number.isNaN(pe)&&Number.isFinite(pe))return pe;let Oe=Date.parse(H);if(!Number.isNaN(Oe))return Oe}return Date.now()},Y=H=>{if(typeof H=="string")return H;if(H==null)return"";try{return JSON.stringify(H)}catch{return String(H)}},ee=new Map,ie=new Map,Se=new Map,Ze=new Map,ve=null,fe=(H,pe,Oe)=>{var Pt;let Qe=Se.get(H);Qe||(Qe=[],Se.set(H,Qe));let _e=0,Ue=Qe.length;for(;_e<Ue;){let Kt=_e+Ue>>>1;Qe[Kt].seq<pe?_e=Kt+1:Ue=Kt}((Pt=Qe[_e])==null?void 0:Pt.seq)===pe?Qe[_e]={seq:pe,text:Oe}:Qe.splice(_e,0,{seq:pe,text:Oe});let at="";for(let Kt=0;Kt<Qe.length;Kt++)at+=Qe[Kt].text;return at},Je=(H,pe)=>{let Oe=Y(pe),Qe=ie.get(H.id),_e=dh(Qe,Oe);H.rawContent=_e;let Ue=ee.get(H.id),at=xt=>{var we;let lt=(we=H.content)!=null?we:"";xt.trim()!==""&&(lt.trim().length===0||xt.startsWith(lt)||xt.trimStart().startsWith(lt.trim()))&&(H.content=xt)},Pt=()=>{var xt;if(Ue){let lt=(xt=Ue.close)==null?void 0:xt.call(Ue);lt instanceof Promise&<.catch(()=>{})}ee.delete(H.id),ie.delete(H.id),H.streaming=!1,f(H)};if(!Ue){at(Oe),Pt();return}let Kt=Ko(_e);if(Kt!==null&&Kt.trim()!==""){at(Kt),Pt();return}let Zt=xt=>{var le;let lt=typeof xt=="string"?xt:(le=xt==null?void 0:xt.text)!=null?le:null;if(lt!==null&<.trim()!=="")return lt;let we=Ue.getExtractedText();return we!==null&&we.trim()!==""?we:Oe},G;try{G=Ue.processChunk(_e)}catch{at(Oe),Pt();return}if(G instanceof Promise){G.then(xt=>{at(Zt(xt)),Pt()}).catch(()=>{at(Oe),Pt()});return}at(Zt(G)),Pt()},De=[],V=!1,ue,ot=()=>{V||(V=!0,queueMicrotask(()=>{V=!1,ue()}))},Et=new mi((H,pe)=>{De.push({payloadType:H,payload:pe}),ot()}),ne=null,Ve=new Map,Nn=(Ht=this.config.iterationDisplay)!=null?Ht:"separate";for(ue=()=>{var H,pe,Oe,Qe,_e,Ue,at,Pt,Kt,Zt,G,xt,lt,we,le,nt,tn,Gt,Pn,wn,mt,Mt,et,qt,dn,An,Sn,yn,Mr,At,jn,qn,Nr,fr,vt,Lo,kr,Po,Fn,ss,ro,Fr,St,zn,Vn,In,Lt,ar,ir,Kn,oo,_r,so,Gn,Bt,Rn,lr,ao,$r,io,Lr,Jn,hr,ft,nn,rn,Qn,lo,ye,br,cr,$,as,Pr,Ur,jr,Ir,yr,Ns,Xn,Yn,xr,vr,Io,qr,Tn,Rr,is,Ro,ls,Ba,cs,Da,ds,yt,Fs,dr,_n,Oa,Na,ps,zr,_s,co,$s,Us,js,qs,$n,us,Wr,Hr,zs,Fa,Vs,Ks,Wo,_a,$a,Ua,ja,pl,Ho,po,qa,Gs,uo,za,Js,mo,Qs,Va,Vr,Ka,go,Dt,ms,gs;for(let Bo=0;Bo<De.length;Bo++){let je=De[Bo].payloadType,A=De[Bo].payload;if(je==="reason_start"){let U=(H=be(A,!0))!=null?H:`reason-${l()}`,L=Le(U);L.reasoning=(pe=L.reasoning)!=null?pe:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Qe=L.reasoning.startedAt)!=null?Qe:He((Oe=A.startedAt)!=null?Oe:A.timestamp),L.reasoning.completedAt=void 0,L.reasoning.durationMs=void 0,L.streaming=!0,L.reasoning.status="streaming",f(L)}else if(je==="reason_delta"||je==="reason_chunk"){let U=(Ue=(_e=be(A,!1))!=null?_e:be(A,!0))!=null?Ue:`reason-${l()}`,L=Le(U);L.reasoning=(at=L.reasoning)!=null?at:{id:U,status:"streaming",chunks:[]},L.reasoning.startedAt=(Kt=L.reasoning.startedAt)!=null?Kt:He((Pt=A.startedAt)!=null?Pt:A.timestamp);let Z=(xt=(G=(Zt=A.reasoningText)!=null?Zt:A.text)!=null?G:A.delta)!=null?xt:"";if(Z&&A.hidden!==!0){let se=typeof A.sequenceIndex=="number"?A.sequenceIndex:void 0;if(se!==void 0){let J=fe(U,se,String(Z));L.reasoning.chunks=[J]}else L.reasoning.chunks.push(String(Z))}if(L.reasoning.status=A.done?"complete":"streaming",A.done){L.reasoning.completedAt=He((lt=A.completedAt)!=null?lt:A.timestamp);let se=(we=L.reasoning.startedAt)!=null?we:Date.now();L.reasoning.durationMs=Math.max(0,((le=L.reasoning.completedAt)!=null?le:Date.now())-se)}L.streaming=L.reasoning.status!=="complete",f(L)}else if(je==="reason_complete"){let U=(tn=(nt=be(A,!1))!=null?nt:be(A,!0))!=null?tn:`reason-${l()}`,L=O.get(U);if(L!=null&&L.reasoning){L.reasoning.status="complete",L.reasoning.completedAt=He((Gt=A.completedAt)!=null?Gt:A.timestamp);let se=(Pn=L.reasoning.startedAt)!=null?Pn:Date.now();L.reasoning.durationMs=Math.max(0,((wn=L.reasoning.completedAt)!=null?wn:Date.now())-se),L.streaming=!1,f(L)}let Z=z(A);Z&&T.byStep.delete(Z)}else if(je==="tool_start"){let U=(mt=K(A,!0))!=null?mt:`tool-${l()}`,L=(Mt=A.toolName)!=null?Mt:A.name;if(ge(L)){de.add(U);continue}let Z=ae(U),se=(et=Z.toolCall)!=null?et:{id:U,status:"pending"};se.name=L!=null?L:se.name,se.status="running",A.args!==void 0?se.args=A.args:A.parameters!==void 0&&(se.args=A.parameters),se.startedAt=(dn=se.startedAt)!=null?dn:He((qt=A.startedAt)!=null?qt:A.timestamp),se.completedAt=void 0,se.durationMs=void 0,Z.toolCall=se,Z.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(Z.agentMetadata={executionId:(An=J==null?void 0:J.executionId)!=null?An:A.executionId,iteration:(Sn=J==null?void 0:J.iteration)!=null?Sn:A.iteration}),f(Z)}else if(je==="tool_chunk"||je==="tool_delta"){let U=(Mr=(yn=K(A,!1))!=null?yn:K(A,!0))!=null?Mr:`tool-${l()}`;if(de.has(U))continue;let L=ae(U),Z=(At=L.toolCall)!=null?At:{id:U,status:"running"};Z.startedAt=(qn=Z.startedAt)!=null?qn:He((jn=A.startedAt)!=null?jn:A.timestamp);let se=(vt=(fr=(Nr=A.text)!=null?Nr:A.delta)!=null?fr:A.message)!=null?vt:"";se&&(Z.chunks=(Lo=Z.chunks)!=null?Lo:[],Z.chunks.push(String(se))),Z.status="running",L.toolCall=Z,L.streaming=!0;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(Fn=L.agentMetadata)!=null?Fn:{executionId:(kr=J==null?void 0:J.executionId)!=null?kr:A.executionId,iteration:(Po=J==null?void 0:J.iteration)!=null?Po:A.iteration}),f(L)}else if(je==="tool_complete"){let U=(ro=(ss=K(A,!1))!=null?ss:K(A,!0))!=null?ro:`tool-${l()}`;if(de.has(U)){de.delete(U);continue}let L=ae(U),Z=(Fr=L.toolCall)!=null?Fr:{id:U,status:"running"};Z.status="complete",A.result!==void 0&&(Z.result=A.result),typeof A.duration=="number"&&(Z.duration=A.duration),Z.completedAt=He((St=A.completedAt)!=null?St:A.timestamp);let se=(zn=A.duration)!=null?zn:A.executionTime;if(typeof se=="number")Z.durationMs=se;else{let Fe=(Vn=Z.startedAt)!=null?Vn:Date.now();Z.durationMs=Math.max(0,((In=Z.completedAt)!=null?In:Date.now())-Fe)}L.toolCall=Z,L.streaming=!1;let J=A.agentContext;(J||A.executionId)&&(L.agentMetadata=(ir=L.agentMetadata)!=null?ir:{executionId:(Lt=J==null?void 0:J.executionId)!=null?Lt:A.executionId,iteration:(ar=J==null?void 0:J.iteration)!=null?ar:A.iteration}),f(L);let Me=oe(A);Me&&W.byCall.delete(Me)}else if(je==="step_await"&&A.awaitReason==="local_tool_required"&&A.toolName){let U=typeof A.toolCallId=="string"&&A.toolCallId.length>0?A.toolCallId:void 0,L=(Kn=U!=null?U:A.toolId)!=null?Kn:`local-${l()}`,Z=ae(L),se=A.toolName,J=zo(se),Me=(oo=Z.toolCall)!=null?oo:{id:L,status:"pending"};Me.name=se,Me.args=A.parameters,Me.status=J?"running":"complete",Me.chunks=(_r=Me.chunks)!=null?_r:[],Me.startedAt=(Gn=Me.startedAt)!=null?Gn:He((so=A.startedAt)!=null?so:A.timestamp),J?(Me.completedAt=void 0,Me.duration=void 0,Me.durationMs=void 0):Me.completedAt=(Bt=Me.completedAt)!=null?Bt:Me.startedAt,Z.toolCall=Me,Z.streaming=!1,Z.agentMetadata={...Z.agentMetadata,executionId:(lr=A.executionId)!=null?lr:(Rn=Z.agentMetadata)==null?void 0:Rn.executionId,awaitingLocalTool:!0,...U?{webMcpToolCallId:U}:{}},f(Z)}else if(je==="text_start"){if((ao=A.toolContext)!=null&&ao.toolId)continue;let U=A.partId;if(U!==void 0&&w.current!==null&&U!==w.current){let L=g;L&&(L.streaming=!1,f(L),ve=L,g=null,S=!0)}U!==void 0&&(w.current=U)}else if(je==="text_end"){if(($r=A.toolContext)!=null&&$r.toolId)continue;let U=g;U&&(U.streaming=!1,f(U),ve=U,g=null,S=!0)}else if(je==="step_chunk"||je==="step_delta"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((Lr=(io=A.id)!=null?io:Z.stepId)!=null?Lr:`step-${l()}`),ct=A.partId!==void 0&&A.partId!==null?String(A.partId):"",tt=`${Z.toolId}::${Fe}`,Wt=R.get(tt);if(ct!==""&&Wt!==void 0&&Wt!==""&&Wt!==ct){let it=I.get(_(Z.toolId,Fe,Wt));it&&it.streaming!==!1&&(it.streaming=!1,f(it))}ct!==""&&R.set(tt,ct);let $t=M(Z.toolId,Fe,ct,Z.executionId),gn=(nn=(ft=(hr=(Jn=A.text)!=null?Jn:A.delta)!=null?hr:A.content)!=null?ft:A.chunk)!=null?nn:"";gn&&($t.content+=String(gn),$t.streaming=!0,f($t)),A.isComplete&&($t.streaming=!1,f($t));continue}let se=A.partId;if(se!==void 0&&w.current!==null&&se!==w.current){let Fe=g;Fe&&(Fe.streaming=!1,f(Fe),ve=Fe,g=null,S=!0)}se!==void 0&&(w.current=se);let J=se!==void 0&&(rn=Ze.get(se))!=null?rn:Ae();se!==void 0&&(J.partId||(J.partId=se),Ze.set(se,J));let Me=(br=(ye=(lo=(Qn=A.text)!=null?Qn:A.delta)!=null?lo:A.content)!=null?ye:A.chunk)!=null?br:"";if(Me){let Fe=typeof A.seq=="number"?A.seq:void 0,ct=se!=null?se:J.id,tt=Fe!==void 0?fe(ct,Fe,String(Me)):((cr=ie.get(J.id))!=null?cr:"")+Me;J.rawContent=tt,ee.has(J.id)||ee.set(J.id,this.createStreamParser());let Wt=ee.get(J.id),$t=tt.trim().startsWith("{")||tt.trim().startsWith("[");if($t&&ie.set(J.id,tt),Wt.__isPlainTextParser===!0){J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J);continue}let it=Wt.processChunk(tt);if(it instanceof Promise)it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null&&en.trim()!=="")J.content=en,f(J);else if(!$t&&!tt.trim().startsWith("<")){let Cn=g,Qt=Cn&&Cn.id===J.id?Cn:J;Qt.id===J.id&&(Qt.content=Fe!==void 0?tt:Qt.content+Me,ie.delete(Qt.id),ee.delete(Qt.id),Qt.rawContent=void 0,f(Qt))}}).catch(()=>{J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J)});else{let ht=typeof it=="string"?it:($=it==null?void 0:it.text)!=null?$:null;ht!==null&&ht.trim()!==""?(J.content=ht,f(J)):!$t&&!tt.trim().startsWith("<")&&(J.content=Fe!==void 0?tt:J.content+Me,ie.delete(J.id),ee.delete(J.id),J.rawContent=void 0,f(J))}}if(A.isComplete){let Fe=(Pr=(as=A.result)==null?void 0:as.response)!=null?Pr:J.content;if(Fe){let ct=ie.get(J.id),tt=ct!=null?ct:Y(Fe);J.rawContent=tt;let Wt=ee.get(J.id),$t=null,gn=!1;if(Wt&&($t=Wt.getExtractedText(),$t===null&&($t=Ko(tt)),$t===null)){let it=Wt.processChunk(tt);it instanceof Promise?(gn=!0,it.then(ht=>{var Ge;let en=typeof ht=="string"?ht:(Ge=ht==null?void 0:ht.text)!=null?Ge:null;if(en!==null){let Cn=g;Cn&&Cn.id===J.id&&(Cn.content=en,Cn.streaming=!1,ee.delete(Cn.id),ie.delete(Cn.id),f(Cn))}})):$t=typeof it=="string"?it:(Ur=it==null?void 0:it.text)!=null?Ur:null}if(!gn){$t!==null&&$t.trim()!==""?J.content=$t:ie.has(J.id)||(J.content=Y(Fe));let it=ee.get(J.id);if(it){let ht=(jr=it.close)==null?void 0:jr.call(it);ht instanceof Promise&&ht.catch(()=>{}),ee.delete(J.id)}ie.delete(J.id),J.streaming=!1,f(J)}}}}else if(je==="step_complete"){let U=A.stepType,L=A.executionType;if(U==="tool"||L==="context")continue;let Z=A.toolContext;if(Z!=null&&Z.toolId){let Fe=String((yr=(Ir=A.id)!=null?Ir:Z.stepId)!=null?yr:"");if(Fe){let ct=F(Z.toolId,Fe);for(let[tt,Wt]of I)tt.startsWith(ct)&&Wt.streaming!==!1&&(Wt.streaming=!1,f(Wt));R.delete(`${Z.toolId}::${Fe}`)}continue}let se=A.stopReason;if(S){if(g!==null){let tt=g;se&&(tt.stopReason=se),ee.delete(tt.id),ie.delete(tt.id),tt.streaming!==!1&&(tt.streaming=!1,f(tt))}let Fe=(Ns=A.result)==null?void 0:Ns.response,ct=ve;ct&&(se&&(ct.stopReason=se),Fe!=null?Je(ct,Fe):(ee.delete(ct.id),ie.delete(ct.id))),ve=null;continue}let J=(Xn=A.result)==null?void 0:Xn.response,Me=Ae();if(se&&(Me.stopReason=se),J!=null){let Fe=ee.get(Me.id),ct=!1,tt=!1;if(Fe){let Wt=Fe.getExtractedText(),$t=ie.get(Me.id),gn=$t!=null?$t:Y(J);if(Me.rawContent=gn,Wt!==null&&Wt.trim()!=="")Me.content=Wt,ct=!0;else{let it=Ko(gn);if(it!==null)Me.content=it,ct=!0;else{let ht=Fe.processChunk(gn);if(ht instanceof Promise)tt=!0,ht.then(en=>{var Cn;let Ge=typeof en=="string"?en:(Cn=en==null?void 0:en.text)!=null?Cn:null;if(Ge!==null&&Ge.trim()!==""){let Qt=g;Qt&&Qt.id===Me.id&&(Qt.content=Ge,Qt.streaming=!1,ee.delete(Qt.id),ie.delete(Qt.id),f(Qt))}else{let Qt=Fe.getExtractedText(),xn=g;xn&&xn.id===Me.id&&(Qt!==null&&Qt.trim()!==""?xn.content=Qt:ie.has(xn.id)||(xn.content=Y(J)),xn.streaming=!1,ee.delete(xn.id),ie.delete(xn.id),f(xn))}});else{let en=typeof ht=="string"?ht:(Yn=ht==null?void 0:ht.text)!=null?Yn:null;if(en!==null&&en.trim()!=="")Me.content=en,ct=!0;else{let Ge=Fe.getExtractedText();Ge!==null&&Ge.trim()!==""&&(Me.content=Ge,ct=!0)}}}}}if(!tt){if(!Me.rawContent){let Wt=ie.get(Me.id);Me.rawContent=Wt!=null?Wt:Y(J)}if(!ct&&!ie.has(Me.id)&&(Me.content=Y(J)),Fe){let Wt=(xr=Fe.close)==null?void 0:xr.call(Fe);Wt instanceof Promise&&Wt.catch(()=>{})}ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}}else ee.delete(Me.id),ie.delete(Me.id),Me.streaming=!1,f(Me)}else if(je==="flow_complete"){let U=(vr=A.result)==null?void 0:vr.response;if(S){if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}}else if(U!=null){let L=Ae(),Z=ie.get(L.id),se=Z!=null?Z:Y(U);L.rawContent=se;let J=Y(U),Me=ee.get(L.id);if(Me){let tt=Ko(se);if(tt!==null)J=tt;else{let Wt=Me.processChunk(se);Wt instanceof Promise&&Wt.then(gn=>{var ht;let it=typeof gn=="string"?gn:(ht=gn==null?void 0:gn.text)!=null?ht:null;it!==null&&(L.content=it,L.streaming=!1,f(L))});let $t=Me.getExtractedText();$t!==null&&(J=$t)}}ee.delete(L.id),ie.delete(L.id);let Fe=J!==L.content,ct=L.streaming!==!1;Fe&&(L.content=J),L.streaming=!1,(Fe||ct)&&f(L)}else if(g!==null){let L=g;ee.delete(L.id),ie.delete(L.id),L.streaming!==!1&&(L.streaming=!1,f(L))}n({type:"status",status:"idle"})}else if(je==="agent_start")ne={executionId:A.executionId,agentId:(Io=A.agentId)!=null?Io:"virtual",agentName:(qr=A.agentName)!=null?qr:"",status:"running",currentIteration:0,maxTurns:(Tn=A.maxTurns)!=null?Tn:1,startedAt:He(A.startedAt)};else if(je==="agent_iteration_start"){if(ne&&(ne.currentIteration=A.iteration),Nn==="separate"&&A.iteration>1){let U=g;U&&(U.streaming=!1,f(U),Ve.set(A.iteration-1,U),g=null)}}else if(je==="agent_turn_start")v=null;else if(je==="agent_turn_delta"){if(A.contentType==="text"){let U=Ae();U.content+=(Rr=A.delta)!=null?Rr:"",U.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId,agentName:ne==null?void 0:ne.agentName},v=U,f(U)}else if(A.contentType==="thinking"){let U=(is=A.turnId)!=null?is:`agent-think-${A.iteration}`,L=Le(U);L.reasoning=(Ro=L.reasoning)!=null?Ro:{id:U,status:"streaming",chunks:[]},L.reasoning.chunks.push((ls=A.delta)!=null?ls:""),L.agentMetadata={executionId:A.executionId,iteration:A.iteration,turnId:A.turnId},f(L)}else if(A.contentType==="tool_input"){let U=(Ba=A.toolCallId)!=null?Ba:W.lastId;if(U){let L=k.get(U);L!=null&&L.toolCall&&(L.toolCall.chunks=(cs=L.toolCall.chunks)!=null?cs:[],L.toolCall.chunks.push((Da=A.delta)!=null?Da:""),f(L))}}}else if(je==="agent_turn_complete"){let U=A.turnId;if(U){let se=O.get(U);if(se!=null&&se.reasoning){se.reasoning.status="complete",se.reasoning.completedAt=He(A.completedAt);let J=(ds=se.reasoning.startedAt)!=null?ds:Date.now();se.reasoning.durationMs=Math.max(0,((yt=se.reasoning.completedAt)!=null?yt:Date.now())-J),se.streaming=!1,f(se)}}let L=A.stopReason,Z=g!=null?g:v;if(L&&Z!==null){let se=A.turnId;(!se||((Fs=Z.agentMetadata)==null?void 0:Fs.turnId)===se)&&(Z.stopReason=L,f(Z))}}else if(je==="agent_tool_start"){g&&(g.streaming=!1,f(g),g=null);let U=(dr=A.toolCallId)!=null?dr:`agent-tool-${l()}`;We(oe(A),U);let L=ae(U),Z=(_n=L.toolCall)!=null?_n:{id:U,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};Z.name=(Na=(Oa=A.toolName)!=null?Oa:A.name)!=null?Na:Z.name,Z.status="running",A.parameters!==void 0&&(Z.args=A.parameters),Z.startedAt=He((ps=A.startedAt)!=null?ps:A.timestamp),L.toolCall=Z,L.streaming=!0,L.agentMetadata={executionId:A.executionId,iteration:A.iteration},f(L)}else if(je==="agent_tool_delta"){let U=(zr=A.toolCallId)!=null?zr:W.lastId;if(U){let L=(_s=k.get(U))!=null?_s:ae(U);L.toolCall&&(L.toolCall.chunks=(co=L.toolCall.chunks)!=null?co:[],L.toolCall.chunks.push(($s=A.delta)!=null?$s:""),L.toolCall.status="running",L.streaming=!0,f(L))}}else if(je==="agent_tool_complete"){let U=(Us=A.toolCallId)!=null?Us:W.lastId;if(U){let L=(js=k.get(U))!=null?js:ae(U);if(L.toolCall){L.toolCall.status="complete",A.result!==void 0&&(L.toolCall.result=A.result),typeof A.executionTime=="number"&&(L.toolCall.durationMs=A.executionTime),L.toolCall.completedAt=He((qs=A.completedAt)!=null?qs:A.timestamp),L.streaming=!1,f(L);let Z=oe(A);Z&&W.byCall.delete(Z)}}}else if(je==="agent_media"){let U=Array.isArray(A.media)?A.media:[],L=[];for(let Z of U){if(!Z||typeof Z!="object")continue;let se=Z,J=typeof se.type=="string"?se.type:void 0,Me=typeof se.mediaType=="string"?se.mediaType.toLowerCase():"",Fe=null,ct="";if(J==="media"){let tt=typeof se.data=="string"?se.data:void 0;if(!tt)continue;ct=Me.length>0?Me:"application/octet-stream",Fe=`data:${ct};base64,${tt}`}else if(J==="image-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else if(J==="file-url"){let tt=typeof se.url=="string"?se.url:void 0;if(!tt)continue;ct=Me,Fe=tt}else continue;if(Fe)if(J==="image-url"||ct.startsWith("image/"))L.push({type:"image",image:Fe,...ct?{mimeType:ct}:{}});else if(ct.startsWith("audio/"))L.push({type:"audio",audio:Fe,mimeType:ct});else if(ct.startsWith("video/"))L.push({type:"video",video:Fe,mimeType:ct});else{let tt=ct||"application/octet-stream";L.push({type:"file",data:Fe,mimeType:tt,filename:lh(tt)})}}if(L.length>0){let Z=l(),se=A.toolCallId,Me={id:`agent-media-${typeof se=="string"&&se.length>0?`${se}-${Z}`:String(Z)}`,role:"assistant",content:"",contentParts:L,createdAt:new Date().toISOString(),streaming:!1,sequence:Z,agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(Me);let Fe=g;Fe&&(Fe.streaming=!1,f(Fe)),g=null,y.current=null}}else if(je!=="agent_iteration_complete"){if(je==="agent_reflection"||je==="agent_reflect"){let U=`agent-reflection-${A.executionId}-${A.iteration}`,L={id:U,role:"assistant",content:($n=A.reflection)!=null?$n:"",createdAt:new Date().toISOString(),streaming:!1,variant:"reasoning",sequence:l(),reasoning:{id:U,status:"complete",chunks:[(us=A.reflection)!=null?us:""]},agentMetadata:{executionId:A.executionId,iteration:A.iteration}};f(L)}else if(je==="agent_complete"){ne&&(ne.status=A.success?"complete":"error",ne.completedAt=He(A.completedAt),ne.stopReason=A.stopReason);let U=g;U&&(U.streaming=!1,f(U)),n({type:"status",status:"idle"})}else if(je==="agent_error"){let U=typeof A.error=="string"?A.error:(Hr=(Wr=A.error)==null?void 0:Wr.message)!=null?Hr:"Agent execution error";A.recoverable?typeof console!="undefined"&&console.warn("[AgentWidget] Recoverable agent error:",U):n({type:"error",error:new Error(U)})}else if(je!=="agent_ping"){if(je==="agent_approval_start"){let U=(zs=A.approvalId)!=null?zs:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(Fa=ne==null?void 0:ne.agentId)!=null?Fa:"virtual",executionId:(Ks=(Vs=A.executionId)!=null?Vs:ne==null?void 0:ne.executionId)!=null?Ks:"",toolName:(Wo=A.toolName)!=null?Wo:"",toolType:A.toolType,description:($a=A.description)!=null?$a:`Execute ${(_a=A.toolName)!=null?_a:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="step_await"&&A.awaitReason==="approval_required"){let U=(Ua=A.approvalId)!=null?Ua:`approval-${l()}`,L={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:"pending",agentId:(ja=ne==null?void 0:ne.agentId)!=null?ja:"virtual",executionId:(Ho=(pl=A.executionId)!=null?pl:ne==null?void 0:ne.executionId)!=null?Ho:"",toolName:(po=A.toolName)!=null?po:"",toolType:A.toolType,description:(Gs=A.description)!=null?Gs:`Execute ${(qa=A.toolName)!=null?qa:"tool"}`,...typeof A.reason=="string"&&A.reason?{reason:A.reason}:{},parameters:A.parameters}};f(L)}else if(je==="agent_approval_complete"){let U=A.approvalId;if(U){let Z={id:`approval-${U}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!1,variant:"approval",sequence:l(),approval:{id:U,status:(uo=A.decision)!=null?uo:"approved",agentId:(za=ne==null?void 0:ne.agentId)!=null?za:"virtual",executionId:(mo=(Js=A.executionId)!=null?Js:ne==null?void 0:ne.executionId)!=null?mo:"",toolName:(Qs=A.toolName)!=null?Qs:"",description:(Va=A.description)!=null?Va:"",resolvedAt:Date.now()}};f(Z)}}else if(je==="artifact_start"||je==="artifact_delta"||je==="artifact_update"||je==="artifact_complete"){if(je==="artifact_start"){let U=A.artifactType,L=String(A.id),Z=typeof A.title=="string"?A.title:void 0;if(n({type:"artifact_start",id:L,artifactType:U,title:Z,component:typeof A.component=="string"?A.component:void 0}),ce.set(L,{markdown:"",title:Z}),!re.has(L)){re.add(L);let se={id:`artifact-ref-${L}`,role:"assistant",content:"",createdAt:new Date().toISOString(),streaming:!0,sequence:l(),rawContent:JSON.stringify({component:"PersonaArtifactCard",props:{artifactId:L,title:Z,artifactType:U,status:"streaming"}})};X.set(L,se),f(se)}}else if(je==="artifact_delta"){let U=String(A.id),L=typeof A.delta=="string"?A.delta:String((Vr=A.delta)!=null?Vr:"");n({type:"artifact_delta",id:U,artDelta:L});let Z=ce.get(U);Z&&(Z.markdown+=L)}else if(je==="artifact_update"){let U=A.props&&typeof A.props=="object"&&!Array.isArray(A.props)?A.props:{};n({type:"artifact_update",id:String(A.id),props:U,component:typeof A.component=="string"?A.component:void 0})}else if(je==="artifact_complete"){let U=String(A.id);n({type:"artifact_complete",id:U});let L=X.get(U);if(L){L.streaming=!1;try{let Z=JSON.parse((Ka=L.rawContent)!=null?Ka:"{}");if(Z.props){Z.props.status="complete";let se=ce.get(U);se!=null&&se.markdown&&(Z.props.markdown=se.markdown)}L.rawContent=JSON.stringify(Z)}catch{}ce.delete(U),f(L),X.delete(U)}}}else if(je==="transcript_insert"){let U=A.message;if(!U||typeof U!="object")continue;let L=String((go=U.id)!=null?go:`msg-${l()}`),Z=U.role,J={id:L,role:Z==="user"?"user":Z==="system"?"system":"assistant",content:typeof U.content=="string"?U.content:"",rawContent:typeof U.rawContent=="string"?U.rawContent:void 0,createdAt:typeof U.createdAt=="string"?U.createdAt:new Date().toISOString(),streaming:U.streaming===!0,...typeof U.variant=="string"?{variant:U.variant}:{},sequence:l()};if(f(J),J.rawContent)try{let Me=JSON.parse(J.rawContent),Fe=(Dt=Me==null?void 0:Me.props)==null?void 0:Dt.artifactId;typeof Fe=="string"&&re.add(Fe)}catch{}g=null,y.current=null,ee.delete(L),ie.delete(L)}else if(je==="error"||je==="step_error"||je==="dispatch_error"||je==="flow_error"){let U=null;if(A.error instanceof Error)U=A.error;else if(je==="dispatch_error"){let L=(ms=A.message)!=null?ms:A.error;L!=null&&L!==""&&(U=new Error(String(L)))}else if(je==="step_error"||je==="flow_error"){let L=A.error;typeof L=="string"&&L!==""?U=new Error(L):L!=null&&typeof L=="object"&&"message"in L&&(U=new Error(String((gs=L.message)!=null?gs:L)))}else je==="error"&&A.error!=null&&A.error!==""&&(U=new Error(String(A.error)));if(U){n({type:"error",error:U});let L=g;L&&L.streaming&&(L.streaming=!1,f(L)),n({type:"status",status:"idle"})}}}}}De.length=0};;){let{done:H,value:pe}=await o.read();if(H)break;a+=s.decode(pe,{stream:!0});let Oe=a.split(`
|
|
10
10
|
|
|
11
11
|
`);a=(cn=Oe.pop())!=null?cn:"";for(let Qe of Oe){let _e=Qe.split(`
|
|
12
12
|
`),Ue="message",at="";for(let Zt of _e)Zt.startsWith("event:")?Ue=Zt.replace("event:","").trim():Zt.startsWith("data:")&&(at+=Zt.replace("data:","").trim());if(!at)continue;let Pt;try{Pt=JSON.parse(at)}catch(Zt){n({type:"error",error:Zt instanceof Error?Zt:new Error("Failed to parse chat stream payload")});continue}let Kt=Ue!=="message"?Ue:(sr=Pt.type)!=null?sr:"message";if((Er=this.onSSEEvent)==null||Er.call(this,Kt,Pt),this.parseSSEEvent){y.current=g;let Zt=await this.handleCustomSSEEvent(Pt,n,y,f,l,w);if(y.current&&y.current!==g&&(g=y.current),Zt)continue}Et.push(Kt,Pt),ue()}}Et.flushPending(),ue(),Et.destroy()}};function lm(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`msg_${e}_${t}`}function Ts(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`usr_${e}_${t}`}function Jo(){let e=Date.now().toString(36),t=Math.random().toString(36).substring(2,10);return`ast_${e}_${t}`}var fi="[Image]";function cm(e){return typeof e=="string"?[{type:"text",text:e}]:e}function dm(e){return typeof e=="string"?e:e.filter(t=>t.type==="text").map(t=>t.text).join("")}function pm(e){return typeof e=="string"?!1:e.some(t=>t.type==="image")}function um(e){return typeof e=="string"?[]:e.filter(t=>t.type==="image")}function pa(e){return{type:"text",text:e}}function mm(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 gm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;t({type:"image",image:o,mimeType:e.type,alt:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function fm(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 hm=["image/png","image/jpeg","image/gif","image/webp","image/svg+xml","image/bmp"],ph=["application/pdf","text/plain","text/markdown","text/csv","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/json"],Yr=[...hm,...ph];function uh(e){return hm.includes(e)||e.startsWith("image/")}function hi(e){return uh(e.type)}async function bm(e){return new Promise((t,n)=>{let r=new FileReader;r.onload=()=>{let o=r.result;hi(e)?t({type:"image",image:o,mimeType:e.type,alt:e.name}):t({type:"file",data:o,mimeType:e.type,filename:e.name})},r.onerror=()=>n(new Error("Failed to read file")),r.readAsDataURL(e)})}function ym(e,t=Yr,n=10*1024*1024){return t.includes(e.type)?e.size>n?{valid:!1,error:`File too large. Maximum size: ${Math.round(n/1048576)}MB`}:{valid:!0}:{valid:!1,error:`Invalid file type "${e.type}". Accepted types: ${t.join(", ")}`}}function mh(e){let t=e.split(".");return t.length>1?t.pop().toLowerCase():""}function xm(e,t){let n=mh(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 bi=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(),o=this.pcmToFloat32(n),s=r.createBuffer(1,o.length,this.sampleRate);s.getChannelData(0).set(o);let a=r.createBufferSource();a.buffer=s,a.connect(r.destination);let i=r.currentTime;this.nextStartTime<i&&(this.nextStartTime=i),a.start(this.nextStartTime),this.nextStartTime+=s.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),o=new DataView(t.buffer,t.byteOffset,t.byteLength);for(let s=0;s<n;s++){let a=o.getInt16(s*2,!0);r[s]=a/32768}return r}};var yi=class{constructor(){this.sourceNode=null;this.analyserNode=null;this.interval=null;this.conditionStart=null;this.fired=!1}start(t,n,r,o,s){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<o.threshold:d>=o.threshold)?this.conditionStart===null?this.conditionStart=Date.now():Date.now()-this.conditionStart>=o.duration&&(this.fired=!0,s()):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 ua=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 yi;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 o=this.w;if(!o||!o.location)throw new Error("Window object or location not available");let s=o.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=`${s}//${a}/ws/agents/${i}/voice?token=${d}`;this.ws=new WebSocket(l),this.setupWebSocketHandlers();let p=`${s}//${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=S=>{v||(v=!0,clearTimeout(w),g(new Error(S)))},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",S=>{if(!S.wasClean&&!v){let O=S.code!==1006?` (code ${S.code})`:"";y("WebSocket connection failed"+O+"."+u)}},{once:!0})}),this.sendHeartbeat()}catch(o){throw this.ws=null,this.errorCallbacks.forEach(s=>s(o)),this.statusCallbacks.forEach(s=>s("error")),o}}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(o=>o({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(o=>o("speaking")),this.playAudio(t.response.audio).catch(o=>this.errorCallbacks.forEach(s=>s(o instanceof Error?o:new Error(String(o)))))):(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(o=>o("idle")));break;case"cancelled":this.isProcessing=!1;break;case"error":this.errorCallbacks.forEach(o=>o(new Error(t.error))),this.statusCallbacks.forEach(o=>o("error")),this.isProcessing=!1;break;case"pong":break}}handleAudioChunk(t){t.length!==0&&this.currentRequestId&&(this.playbackManager||(this.playbackManager=new bi(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,o;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 s=this.w;this.audioContext||(this.audioContext=new(s.AudioContext||s.webkitAudioContext));let a=this.audioContext,i=(n=(t=this.config)==null?void 0:t.pauseDuration)!=null?n:2e3,d=(o=(r=this.config)==null?void 0:r.silenceThreshold)!=null?o:.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(s){throw this.errorCallbacks.forEach(a=>a(s)),this.statusCallbacks.forEach(a=>a("error")),s}}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 s,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=(s=this.config)==null?void 0:s.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),o=this.getFormatFromMimeType(t.type),s=this.generateRequestId();this.currentRequestId=s,this.ws.send(JSON.stringify({type:"audio_input",audio:r,format:o,sampleRate:16e3,voiceId:(n=this.config)==null?void 0:n.voiceId,requestId:s}))}catch(r){this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error"))}}getFormatFromMimeType(t){return t.includes("wav")?"wav":t.includes("mpeg")||t.includes("mp3")?"mp3":"webm"}blobToBase64(t){return new Promise((n,r)=>{let o=new FileReader;o.onload=()=>{let a=o.result.split(",")[1];n(a)},o.onerror=r,o.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 o=t.format||"mp3",s=o==="mp3"?"audio/mpeg":`audio/${o}`,a=new Blob([r],{type:s}),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 Qo=class{constructor(t={}){this.config=t;this.type="browser";this.recognition=null;this.resultCallbacks=[];this.errorCallbacks=[];this.statusCallbacks=[];this.isListening=!1;this.w=typeof window!="undefined"?window:void 0}async connect(){this.statusCallbacks.forEach(t=>t("connected"))}async startListening(){var t,n;try{if(this.isListening)throw new Error("Already listening");if(!this.w)throw new Error("Window object not available");let r=this.w.SpeechRecognition||this.w.webkitSpeechRecognition;if(!r)throw new Error("Browser speech recognition not supported");this.recognition=new r,this.recognition.lang=((t=this.config)==null?void 0:t.language)||"en-US",this.recognition.continuous=((n=this.config)==null?void 0:n.continuous)||!1,this.recognition.interimResults=!0,this.recognition.onresult=o=>{var i;let s=Array.from(o.results).map(d=>d[0]).map(d=>d.transcript).join(""),a=o.results[o.results.length-1].isFinal;this.resultCallbacks.forEach(d=>d({text:s,confidence:a?.8:.5,provider:"browser"})),a&&!((i=this.config)!=null&&i.continuous)&&this.stopListening()},this.recognition.onerror=o=>{this.errorCallbacks.forEach(s=>s(new Error(o.error))),this.statusCallbacks.forEach(s=>s("error"))},this.recognition.onstart=()=>{this.isListening=!0,this.statusCallbacks.forEach(o=>o("listening"))},this.recognition.onend=()=>{this.isListening=!1,this.statusCallbacks.forEach(o=>o("idle"))},this.recognition.start()}catch(r){throw this.errorCallbacks.forEach(o=>o(r)),this.statusCallbacks.forEach(o=>o("error")),r}}async stopListening(){this.recognition&&(this.recognition.stop(),this.recognition=null),this.isListening=!1,this.statusCallbacks.forEach(t=>t("idle"))}onResult(t){this.resultCallbacks.push(t)}onError(t){this.errorCallbacks.push(t)}onStatusChange(t){this.statusCallbacks.push(t)}async disconnect(){await this.stopListening(),this.statusCallbacks.forEach(t=>t("disconnected"))}static isSupported(){return"SpeechRecognition"in window||"webkitSpeechRecognition"in window}};function Xo(e){switch(e.type){case"runtype":if(!e.runtype)throw new Error("Runtype voice provider requires configuration");return new ua(e.runtype);case"browser":if(!Qo.isSupported())throw new Error("Browser speech recognition not supported");return new Qo(e.browser||{});case"custom":throw new Error("Custom voice providers not yet implemented");default:throw new Error(`Unknown voice provider type: ${e.type}`)}}function xi(e){if((e==null?void 0:e.type)==="runtype"&&e.runtype)return Xo({type:"runtype",runtype:e.runtype});if(Qo.isSupported())return Xo({type:"browser",browser:(e==null?void 0:e.browser)||{language:"en-US"}});throw new Error("No supported voice providers available")}function ma(e){try{return xi(e),!0}catch{return!1}}var gh=["apiUrl","clientToken","flowId","agent","agentOptions","headers","getHeaders","webmcp","streamParser","parserType","contextProviders","requestMiddleware","customFetch","parseSSEEvent","onSessionInit","onSessionExpired","getStoredSessionId","setStoredSessionId"];function fh(e,t){return gh.some(n=>e[n]!==t[n])}function vm(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 ga=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 Ut="max-height: -moz-available !important; max-height: stretch !important;",_t=m?"":"padding-top: 1.25em !important;",bt=m?"":`z-index: ${(fn=(rt=r.launcher)==null?void 0:rt.zIndex)!=null?fn:Ln} !important;`;ve.style.cssText+=Ut+_t+bt}Xe()};hr(),Ao(e,r),Ki(e,r),Gi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",so)});let nn=null,rn=null;ft.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),zn&&ft.push(()=>{zn==null||zn.disconnect(),zn=null}),ft.push(()=>{Rn==null||Rn(),Rn=null,$r(),Bt&&(Bt.remove(),Bt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),Re&&ft.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),K==null||K.destroy(),K=null,ce==null||ce.destroy(),ce=null,X=null});let Qn=null,lo=()=>{Qn&&(Qn(),Qn=null),r.colorScheme==="auto"&&(Qn=Ti(()=>{Ao(e,r)}))};lo(),ft.push(()=>{Qn&&(Qn(),Qn=null)});let ye=(xd=r.features)==null?void 0:xd.streamAnimation;if(ye!=null&&ye.type&&ye.type!=="none"){let c=xa(ye.type,ye.plugins);c&&(Fl(c,e),ft.push(()=>jm(e)))}let br=rg(Et),cr=null,$,as=c=>{var x,E;if(!$)return;let m=c!=null?c:$.getMessages(),b=((E=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:E.enabled)!==!1?oi(m):null;b?br.render(b,$,ne,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?br.render([],$,ne,m):br.render(r.suggestionChips,$,ne,m,r.suggestionChipsConfig)},Pr=!1,Ur=Im(),jr=new Map,Ir=new Map,yr=new Map,Ns=0,Xn=ki(),Yn=0,xr=null,vr=!1,Io=!1,qr=0,Tn=null,Rr=null,is=!1,Ro=!1,ls=null,Ba=4,cs=24,Da=80,ds=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Fs=(wd=(vd=r.voiceRecognition)==null?void 0:vd.autoResume)!=null?wd:!1,dr=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},_n=()=>{g(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Oa=()=>{var x,E;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let c=rc(d.voiceState),m=!!c.active,b=Number((E=c.timestamp)!=null?E:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-b<$b&&setTimeout(()=>{var D,N;yt.active||(yt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("restore"),$.isVoiceActive()&&Xs()}):Qt("restore"))},1e3)},Na=()=>$?Cg($.getMessages()).filter(c=>!c.__skipPersist):[];function ps(c){if(!(i!=null&&i.save))return;let b={messages:c?Cg(c):$?Na():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let x=i.save(b);x instanceof Promise&&x.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let zr=null,_s=()=>ve.querySelector("#persona-scroll-container")||ue,co=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),vr=!1},$s=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!1,co()},Us=()=>{qr>0?(An.textContent=String(qr),An.style.display="",et.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${qr} new)`)):(An.textContent="",An.style.display="none",et.setAttribute("aria-label",Gt()||"Jump to latest"))},js=()=>{qr!==0&&(qr=0,Us())},qs=()=>mt()==="follow"?!Xn.isFollowing():!Zo(ue,cs),$n=()=>{if(!wn()||ae){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==V&&V.appendChild(et),yn();let m=Zr(ue)>0&&qs();m||js(),et.style.display=m?"":"none"},us=()=>{Xn.pause()&&($s(),$n())},Wr=()=>{Xn.resume(),js(),$n()},Hr=(c=!1)=>{mt()==="follow"&&Xn.isFollowing()&&(!c&&!Pr||(xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!0,xr=requestAnimationFrame(()=>{xr=null,Io=!1,Xn.isFollowing()&&Fa(_s(),c?220:140)})))},zs=(c,m,b,x=()=>!0)=>{let E=c.scrollTop,D=m(),N=D-E;co();let q=performance.now();vr=!0;let B=me=>1-Math.pow(1-me,3),xe=me=>{if(!x()){co();return}let te=m();te!==D&&(D=te,N=D-E);let Ee=me-q,$e=Math.min(Ee/b,1),Te=B($e),st=E+N*Te;c.scrollTop=st,Yn=c.scrollTop,$e<1?zr=requestAnimationFrame(xe):(c.scrollTop=D,Yn=c.scrollTop,zr=null,vr=!1)};zr=requestAnimationFrame(xe)},Fa=(c,m=500)=>{let b=Zr(c)-c.scrollTop;if(Math.abs(b)<1){Yn=c.scrollTop;return}if(Math.abs(b)>=Da){co(),vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1;return}zs(c,()=>Zr(c),m,()=>Xn.isFollowing())},Vs=()=>{let c=_s();vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1,$n()},Ks=c=>{Sn.style.height=`${Math.max(0,Math.round(c))}px`,Tn&&(Tn.spacerHeight=Math.max(0,c))},Wo=()=>{Rr!==null&&(cancelAnimationFrame(Rr),Rr=null),co(),Tn=null,Sn.style.height="0px"},_a=c=>{Rr!==null&&cancelAnimationFrame(Rr),Rr=requestAnimationFrame(()=>{var xe;Rr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${m}"]`);if(!b)return;let x=0,E=b;for(;E&&E!==ue;)x+=E.offsetTop,E=E.offsetParent;let D=(xe=Tn==null?void 0:Tn.spacerHeight)!=null?xe:0,N=ue.scrollHeight-D,{targetScrollTop:q,spacerHeight:B}=Dm({anchorOffsetTop:x,topOffset:Mt(),viewportHeight:ue.clientHeight,contentHeight:N});Tn={initialSpacerHeight:B,contentHeightAtAnchor:N,spacerHeight:B},Ks(B),zs(ue,()=>q,220)})},$a=()=>{if(mt()==="follow"){if(!Xn.isFollowing()||Zo(ue,1))return;Hr(!Pr);return}if(Tn&&Tn.initialSpacerHeight>0){let c=ue.scrollHeight-Tn.spacerHeight,m=Om({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:c});m!==Tn.spacerHeight&&Ks(m)}$n()},Ua=c=>{let m=mt();m==="follow"?(Wr(),Hr(!0)):m==="anchor-top"&&_a(c)},ja=c=>{let m=new Map;c.forEach(b=>{let x=ds.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(s.emit("assistant:message",b),!Ro&&mt()!=="anchor-top"&&qs()&&(qr+=1,Us(),$n())),b.role==="assistant"&&(x!=null&&x.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),ds.clear(),m.forEach((b,x)=>{ds.set(x,b)})},Ho=(c,m,b)=>{var pt,Ie,Pe,qe,Xe,wt;let x=document.createElement("div"),D=(()=>{var Be;let P=o.find(Ne=>Ne.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),N=(P,Be)=>Be==null?!1:typeof Be=="string"?(P.textContent=Be,!0):(P.appendChild(Be),!0),q=new Set,B=new Set,xe=o.some(P=>P.renderAskUserQuestion),me=[],te=[],Ee=r.enableComponentStreaming!==!1,$e=o.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(m.forEach(P=>{var Ye,It,un,ur,er,Do,Oo,bs,ys,Xt,No,bo,yo,Kr,Fo,wr;q.add(P.id);let Be=xe&&Jr(P),Ne=$e&&P.variant==="approval"&&!!P.approval,he=!Be&&P.role==="assistant"&&!P.variant&&Ee&&Yi(P);if(!Ne&&yr.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Ir.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Ir.delete(P.id)}let Ft=Jr(P)?`:${(Ye=P.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Pm(P,Ns)+Ft,Jt=Be||Ne||he?null:Rm(Ur,P.id,Ot);if(Jt){x.appendChild(Jt.cloneNode(!0)),Jr(P)&&((un=P.toolCall)!=null&&un.id)&&((ur=P.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((er=P.agentMetadata)!=null&&er.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Ct=null,zt=o.find(rt=>!!(P.variant==="reasoning"&&rt.renderReasoning||P.variant==="tool"&&rt.renderToolCall||!P.variant&&rt.renderMessage)),Zn=(Do=r.layout)==null?void 0:Do.messages;if(Jr(P)&&((Oo=P.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){jr.delete(P.id);let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(ia(P)&&((ys=(bs=r.features)==null?void 0:bs.suggestReplies)==null?void 0:ys.enabled)!==!1)return;if(Jr(P)&&((No=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:No.enabled)!==!1){let rt=o.find(fn=>typeof fn.renderAskUserQuestion=="function");if(rt&&Lt.current){let fn=jr.get(P.id),Ut=fn!==Ot,_t=null;if(Ut){let{payload:kt,complete:En}=Qr(P),Wn=P.id,Br=()=>{var vn;return(vn=Lt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Wn)};_t=rt.renderAskUserQuestion({message:P,payload:kt,complete:En,resolve:vn=>{var Bn;let Hn=Br();Hn&&((Bn=Lt.current)==null||Bn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Bn,_o;let vn=Br();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Bn=Lt.current)==null||Bn.markAskUserQuestionResolved(vn),(_o=Lt.current)==null||_o.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let bt=fn!=null;if(Ut&&_t===null&&!bt){((bo=P.agentMetadata)==null?void 0:bo.awaitingLocalTool)===!0&&!((yo=P.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),x.appendChild(Yt),me.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}else{((Kr=P.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Fo=P.agentMetadata)!=null&&Fo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}}else if(Ne){let rt=o.find(bt=>typeof bt.renderApproval=="function"),Ut=yr.get(P.id)!==Ot,_t=null;if(Ut&&(rt!=null&&rt.renderApproval)){let bt=P.id,Yt=(kt,En)=>{var Br,vn,Hn;let Wn=(Br=Lt.current)==null?void 0:Br.getMessages().find(Bn=>Bn.id===bt);Wn!=null&&Wn.approval&&(Wn.approval.toolType==="webmcp"?(vn=Lt.current)==null||vn.resolveWebMcpApproval(Wn.id,kt):(Hn=Lt.current)==null||Hn.resolveApproval(Wn.approval,kt,En))};_t=rt.renderApproval({message:P,defaultRenderer:()=>zi(P,r),config:r,approve:kt=>Yt("approved",kt),deny:kt=>Yt("denied",kt)})}if(Ut&&_t===null){let bt=c.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),yr.delete(P.id),Ct=zi(P,r)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${P.id}`,bt.setAttribute("data-wrapper-id",P.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),x.appendChild(bt),Te.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}}else if(zt)if(P.variant==="reasoning"&&P.reasoning&&zt.renderReasoning){if(!ze)return;Ct=zt.renderReasoning({message:P,defaultRenderer:()=>Jl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&zt.renderToolCall){if(!Ae)return;Ct=zt.renderToolCall({message:P,defaultRenderer:()=>Ql(P,r),config:r})}else zt.renderMessage&&(Ct=zt.renderMessage({message:P,defaultRenderer:()=>{let rt=Rs(P,b,Zn,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r});return P.role!=="user"&&ec(rt,P,r,$),rt},config:r}));if(!Ct&&he){let rt=Zi(P);if(rt){let fn=Ir.get(P.id),Ut=fn!==Ot,_t=r.wrapComponentDirectiveInBubble!==!1,bt=null;if(Ut){let Yt=Xi(rt,{config:r,message:P,transform:b});if(Yt)if(_t){let kt=document.createElement("div");if(kt.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(" "),kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-mb-3 persona-text-sm persona-leading-relaxed",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),kt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}}if(bt||fn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),_t||Yt.classList.add("persona-w-full"),x.appendChild(Yt),te.push({messageId:P.id,fingerprint:Ot,bubble:bt});return}}}if(!Ct)if(P.variant==="reasoning"&&P.reasoning){if(!ze)return;Ct=Jl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;Ct=Ql(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;Ct=zi(P,r)}else{let rt=(wr=r.layout)==null?void 0:wr.messages;rt!=null&&rt.renderUserMessage&&P.role==="user"?Ct=rt.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):rt!=null&&rt.renderAssistantMessage&&P.role==="assistant"?Ct=rt.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):Ct=Rs(P,b,rt,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r}),P.role!=="user"&&Ct&&ec(Ct,P,r,$)}let ln=document.createElement("div");ln.className="persona-flex",ln.id=`wrapper-${P.id}`,ln.setAttribute("data-wrapper-id",P.id),P.role==="user"&&ln.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&ln.classList.add("persona-w-full"),ln.appendChild(Ct),Wm(Ur,P.id,Ot,ln),x.appendChild(ln)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Ne=Be.getAttribute("data-persona-ask-sheet-for");Ne&&!B.has(Ne)&&wo(De.composerOverlay,Ne)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let P=[],Be=[];m.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Ae){Be.push(Ne);return}Be.length>1&&P.push(Be),Be=[]}),Be.length>1&&P.push(Be),P.forEach((Ne,he)=>{var Ye,It;let Ft=Ne.map(un=>Array.from(x.children).find(ur=>ur instanceof HTMLElement&&ur.getAttribute("data-wrapper-id")===un.id)).filter(un=>!!un);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${he}-${Ne[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${he}-${Ne[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Ne.length} tools`,Zn=(It=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:It.call(Ye,{messages:Ne,toolCalls:Ne.map(un=>un.toolCall).filter(un=>!!un),defaultSummary:zt,config:r});N(Ct,Zn)||(Ct.textContent=zt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,ln),Ot.appendChild(Jt),Ft[0].before(Ot),Ft.forEach((un,ur)=>{let er=document.createElement("div");er.className="persona-tool-group-item persona-relative",er.setAttribute("data-persona-tool-group-item","true"),ur<Ft.length-1&&er.setAttribute("data-persona-tool-group-connector","true"),er.appendChild(un),ln.appendChild(er)})})}Hm(Ur,q);let st=m.some(P=>P.role==="assistant"&&P.streaming),Ke=m[m.length-1],dt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(Pr&&m.some(P=>P.role==="user")&&!st&&!dt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:ts},Be=o.find(he=>he.renderLoadingIndicator),Ne=null;if(Be!=null&&Be.renderLoadingIndicator&&(Ne=Be.renderLoadingIndicator(P)),Ne===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(Ne=r.loadingIndicator.render(P)),Ne===null&&(Ne=ts()),Ne){let he=document.createElement("div"),Ft=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;he.className=Ft?["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(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Ne);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(he),x.appendChild(Ot)}}if(!Pr&&m.length>0){let P=m[m.length-1],Be={config:r,lastMessage:P,messageCount:m.length},Ne=o.find(Ft=>Ft.renderIdleIndicator),he=null;if(Ne!=null&&Ne.renderIdleIndicator&&(he=Ne.renderIdleIndicator(Be)),he===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(he=r.loadingIndicator.renderIdle(Be)),he){let Ft=document.createElement("div"),Ot=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;Ft.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-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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(he);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Ft),x.appendChild(Jt)}}if(Ei(c,x),me.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of me){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),jr.set(P,Be))}if(jr.size>0)for(let P of jr.keys())q.has(P)||jr.delete(P);if(te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),Ir.set(P,Be))}if(Ir.size>0)for(let P of Ir.keys())q.has(P)||Ir.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of Te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),yr.set(P,Be))}if(yr.size>0)for(let P of yr.keys())q.has(P)||yr.delete(P)},po=null,qa=()=>{var b;if(po)return;let c=x=>{let E=x.composedPath();E.includes(ve)||Je&&E.includes(Je)||Dt(!1,"user")};po=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Gs=()=>{var m;if(!po)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",po,!0),po=null};ft.push(()=>Gs());let uo=null,za=()=>{var b;if(uo)return;let c=x=>{x.key==="Escape"&&(x.isComposing||Dt(!1,"user"))};uo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Js=()=>{var m;if(!uo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",uo,!0),uo=null};ft.push(()=>Js());let mo=!1,Qs=new Set,Va=()=>{var m,b,x,E;let c=(x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.peek)==null?void 0:x.streamAnimation;return c||((E=r.features)==null?void 0:E.streamAnimation)},Vr=()=>{var dt,pt,Ie,Pe;if(!_())return;let c=De.peekBanner,m=De.peekTextNode;if(!c||!m)return;if(M){c.classList.remove("persona-pill-peek--visible");return}let b=(dt=$==null?void 0:$.getMessages())!=null?dt:[],x;for(let qe=b.length-1;qe>=0;qe--){let Xe=b[qe];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){c.classList.remove("persona-pill-peek--visible");return}let E=x.content,D=!!x.streaming,N=Va(),q=Ii(N),B=q.type!=="none"?xa(q.type,N==null?void 0:N.plugins):null,xe=((pt=B==null?void 0:B.isAnimating)==null?void 0:pt.call(B,x))===!0,me=B!==null&&(D||xe);me&&B&&!Qs.has(B.name)&&(Fl(B,e),Qs.add(B.name));let te=me&&(B!=null&&B.containerClass)?B.containerClass:null,Ee=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;Ee&&Ee!==te&&(m.classList.remove(Ee),delete m.dataset.personaPeekStreamClass),te&&Ee!==te&&(m.classList.add(te),m.dataset.personaPeekStreamClass=te),me?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let $e=me?Ri(E,q.buffer,B,x,D):E;if(me&&q.placeholder==="skeleton"&&D&&(!$e||!$e.trim())){let qe=document.createElement("div"),Xe=wa();Xe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Xe),Ei(m,qe)}else{let qe=Math.max(0,$e.length-100),Xe=$e.length>100?$e.slice(-100):$e,wt=qo(Xe);if(!me||!B){let P=$e.length>100?`\u2026${Xe}`:Xe;m.textContent!==P&&(m.textContent=P)}else{let P=wt;(B.wrap==="char"||B.wrap==="word")&&(P=va(wt,B.wrap,`peek-${x.id}`,{skipTags:B.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=P,B.useCaret&&Xe.length>0){let Ne=Wi(),he=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=he[he.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Ne,Ft.nextSibling):Be.appendChild(Ne)}Ei(m,Be),(Pe=B.onAfterRender)==null||Pe.call(B,{container:m,bubble:c,messageId:x.id,message:x,speed:q.speed,duration:q.duration})}}let Ke=Pr||mo;c.classList.toggle("persona-pill-peek--visible",Ke)};if(_()){let c=De.peekBanner;if(c){let x=E=>{E.preventDefault(),E.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",x),ft.push(()=>{c.removeEventListener("pointerdown",x)})}let m=()=>{mo||(mo=!0,Vr())},b=()=>{mo&&(mo=!1,Vr())};fe.addEventListener("pointerenter",m),fe.addEventListener("pointerleave",b),ft.push(()=>{fe.removeEventListener("pointerenter",m),fe.removeEventListener("pointerleave",b)}),Je&&(Je.addEventListener("pointerenter",m),Je.addEventListener("pointerleave",b),ft.push(()=>{Je.removeEventListener("pointerenter",m),Je.removeEventListener("pointerleave",b)}))}let Ka=c=>{var Ee,$e,Te,st,Ke,dt,pt,Ie;let m=($e=(Ee=r.launcher)==null?void 0:Ee.composerBar)!=null?$e:{},b=(Te=m.expandedSize)!=null?Te:"anchored",x=(st=m.bottomOffset)!=null?st:"16px",E=m.collapsedMaxWidth,D=(Ke=m.expandedMaxWidth)!=null?Ke:"880px",N=(dt=m.expandedTopOffset)!=null?dt:"5vh",q=(pt=m.modalMaxWidth)!=null?pt:"880px",B=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",xe="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",te=ve.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Je){let Pe=Je.style;Pe.bottom=x,Pe.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=xe,te.maxHeight=B,te.height=B;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${x} + ${me})`,te.top=N,te.width=D,te.maxWidth=xe}},go=()=>{var B,xe,me,te,Ee,$e,Te,st;if(!F())return;if(_()){let dt=(me=((xe=(B=r.launcher)==null?void 0:B.composerBar)!=null?xe:{}).expandedSize)!=null?me:"anchored",pt=M?"expanded":"collapsed";ve.dataset.state=pt,ve.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ka(M),V.style.display=M?"flex":"none",hr(),M?(qa(),za()):(Gs(),Js()),Vr();return}let c=mn(r),m=(te=e.ownerDocument.defaultView)!=null?te:window,b=($e=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?$e:640,x=(st=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?st:!0,E=m.innerWidth<=b,D=x&&E&&S,N=rr(r).reveal;M?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),on?on.element.style.display="none":sn&&(sn.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),on?on.element.style.display=c?"none":"":sn&&(sn.style.display=c?"none":""))},Dt=(c,m="user")=>{var D,N;if(!F()||M===c)return;let b=M;M=c,go();let x=(()=>{var Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt;let q=(st=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?st:!1,B=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,xe=(pt=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,me=(Pe=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Pe:640,te=B.innerWidth<=me,Ee=mn(r)&&xe&&te,$e=_()&&((wt=(Xe=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Xe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return q||xe&&te&&S||Ee||$e})();if(M&&x){if(!nn){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(nn=_l(B,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:Ln))}rn||(rn=$l(e.ownerDocument))}else M||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);M&&(Ys(),mt()==="follow"?Hr(!0):Vs());let E={open:M,source:m,timestamp:Date.now()};M&&!b?s.emit("widget:opened",E):!M&&b&&s.emit("widget:closed",E),s.emit("widget:state",{open:M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()})},ms=c=>{Zt(c?"stop":"send"),G&&(G.disabled=c),br.buttons.forEach(m=>{m.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},gs=()=>{yt.active||ne&&ne.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>gs(),200)});let Bo=()=>{var b,x,E,D,N,q,B,xe,me,te,Ee;sr.textContent=(x=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?x:"Hello \u{1F44B}",Er.textContent=(D=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ne.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let $e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=$e?"":"none",$e?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(xe=r.sendButton)==null?void 0:xe.useIcon)!=null&&me)&&!($!=null&&$.isStreaming())&&(Ve.textContent=(Ee=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?Ee:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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 je=null,A=()=>{je==null&&(je=setInterval(()=>{let c=ot.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(je),je=null;return}let m=Date.now();c.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ai(m-x))})},100))};if($=new Es(r,{onMessagesChanged(c){var x;Ho(ot,c,ke),A(),as(c),Hr(!Pr),ja(c);let m=[...c].reverse().find(E=>E.role==="user");c.length===0&&Wo(),!is||Ro?(is=!0,ls=(x=m==null?void 0:m.id)!=null?x:null):m&&m.id!==ls&&(ls=m.id,Ua(m.id));let b=yt.lastUserMessageId;m&&m.id!==b&&(yt.lastUserMessageId=m.id,s.emit("user:message",m)),yt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),ps(c),Vr()},onStatusChanged(c){var x;let m=(x=r.statusIndicator)!=null?x:{};Ze(cn,(E=>{var D,N,q,B;return E==="idle"?(D=m.idleText)!=null?D:kn.idle:E==="connecting"?(N=m.connectingText)!=null?N:kn.connecting:E==="connected"?(q=m.connectedText)!=null?q:kn.connected:E==="error"?(B=m.errorText)!=null?B:kn.error:kn[E]})(c),m,c)},onStreamingChanged(c){Pr=c,ms(c),$&&Ho(ot,$.getMessages(),ke),c||Hr(!0),Vr()},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":fo(),mf();break;case"speaking":fo(),gf();break;default:c==="idle"&&$.isBargeInActive()?(fo(),Xs(),G==null||G.setAttribute("aria-label","End voice session")):(yt.active=!1,fo(),dr("system"),_n());break}},onArtifactsState(c){Vn=c,Jn(),ps()}}),Lt.current=$,is=!0,((Ad=(Cd=r.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:Ad.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)}),(ce||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,m),ge==null||ge.processEvent(c,m),ce==null||ce.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=rc(c.metadata),w.syncFromMetadata()),(m=c.messages)!=null&&m.length){Ro=!0;try{$.hydrateMessages(c.messages)}finally{Ro=!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 U=()=>{var m,b,x;!_()||M||!((x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.expandOnSubmit)==null||x)||Dt(!0,"auto")},L=c=>{var E;if(c.preventDefault(),$.isStreaming()){$.cancel(),ge==null||ge.reset(),K==null||K.update();return}let m=ne.value.trim(),b=(E=At==null?void 0:At.hasAttachments())!=null?E:!1;if(!m&&!b)return;U();let x;b&&(x=[],x.push(...At.getContentParts()),m&&x.push(pa(m))),ne.value="",ne.style.height="auto",Me(),$.sendMessage(m,{contentParts:x}),b&&At.clearAttachments()},Z=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},se={...Mi},J=!1,Me=()=>{se={...Mi}},Fe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),ct=c=>{if(!ne)return;J=!0,ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),J=!1;let m=ne.value.length;ne.setSelectionRange(m,m)},tt=()=>{J||Me()},Wt=c=>{if(ne){if(Z()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ne.selectionStart===0&&ne.selectionEnd===0,b=Lm({direction:c.key==="ArrowUp"?"up":"down",history:Fe(),currentValue:ne.value,atStart:m,state:se});if(se=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ct(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Me(),c.preventDefault(),Ve.click()}}},$t=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(V)&&($.cancel(),ge==null||ge.reset(),K==null||K.update(),Me(),c.preventDefault(),c.stopImmediatePropagation())},gn=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!At)return;let m=jb(c.clipboardData);m.length!==0&&(c.preventDefault(),await At.handleFiles(m))},it=null,ht=!1,en=null,Ge=null,Cn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qt=(c="user")=>{var D,N,q,B,xe,me,te;if(ht||$.isStreaming())return;let m=Cn();if(!m)return;it=new m;let x=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;it.continuous=!0,it.interimResults=!0,it.lang="en-US";let E=ne.value;it.onresult=Ee=>{let $e="",Te="";for(let Ke=0;Ke<Ee.results.length;Ke++){let dt=Ee.results[Ke],pt=dt[0].transcript;dt.isFinal?$e+=pt+" ":Te=pt}let st=E+$e+Te;ne.value=st,en&&clearTimeout(en),($e||Te)&&(en=window.setTimeout(()=>{let Ke=ne.value.trim();Ke&&it&&ht&&(xn(),ne.value="",ne.style.height="auto",$.sendMessage(Ke,{viaVoice:!0}))},x))},it.onerror=Ee=>{Ee.error!=="no-speech"&&xn()},it.onend=()=>{if(ht){let Ee=ne.value.trim();Ee&&Ee!==E.trim()&&(ne.value="",ne.style.height="auto",$.sendMessage(Ee,{viaVoice:!0})),xn()}};try{if(it.start(),ht=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),dr(c),_n(),G){let Ee=(q=r.voiceRecognition)!=null?q:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(B=Ee.iconName)!=null?B:"mic",iconSize:parseFloat((te=(me=Ee.iconSize)!=null?me:(xe=r.sendButton)==null?void 0:xe.size)!=null?te:"40")||24};let $e=Ee.recordingBackgroundColor,Te=Ee.recordingIconColor,st=Ee.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=$e!=null?$e:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ke=G.querySelector("svg");Ke&&Ke.setAttribute("stroke",Te)}st&&(G.style.borderColor=st),G.setAttribute("aria-label","Stop voice recognition")}}catch{xn("system")}},xn=(c="user")=>{if(ht){if(ht=!1,en&&(clearTimeout(en),en=null),it){try{it.stop()}catch{}it=null}if(yt.active=!1,dr(c),_n(),G){if(G.classList.remove("persona-voice-recording"),Ge){G.style.backgroundColor=Ge.backgroundColor,G.style.color=Ge.color,G.style.borderColor=Ge.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",Ge.color||"currentColor"),Ge=null}G.setAttribute("aria-label","Start voice recognition")}}},uf=(c,m)=>{var dt,pt,Ie,Pe,qe,Xe,wt,P;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(b||x))return null;let D=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",B=(Ie=m==null?void 0:m.size)!=null?Ie:"40px",xe=(Pe=c==null?void 0:c.iconSize)!=null?Pe:B,me=parseFloat(xe)||24,te=(qe=c==null?void 0:c.backgroundColor)!=null?qe:m==null?void 0:m.backgroundColor,Ee=(Xe=c==null?void 0:c.iconColor)!=null?Xe:m==null?void 0:m.textColor;N.style.width=xe,N.style.height=xe,N.style.minWidth=xe,N.style.minHeight=xe,N.style.fontSize="18px",N.style.lineHeight="1",Ee?N.style.color=Ee:N.style.color="var(--persona-text, #111827)";let Te=Ce(q,me,Ee||"currentColor",1.5);Te?N.appendChild(Te):N.textContent="\u{1F3A4}",te?N.style.backgroundColor=te:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let st=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((P=c==null?void 0:c.showTooltip)!=null?P:!1)&&st){let Be=h("div","persona-send-button-tooltip");Be.textContent=st,D.appendChild(Be)}return{micButton:N,micButtonWrapper:D}},ul=()=>{var m,b,x,E,D;if(!G||Ge)return;let c=(m=r.voiceRecognition)!=null?m:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(E=c.iconSize)!=null?E:(x=r.sendButton)==null?void 0:x.size)!=null?D:"40")||24}},ml=(c,m)=>{var D,N,q,B,xe;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let x=(xe=Ge==null?void 0:Ge.iconSize)!=null?xe:parseFloat((B=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?B:"40")||24,E=Ce(c,x,m,1.5);E&&G.appendChild(E)},Ga=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xs=()=>{var E;if(!G)return;ul();let c=(E=r.voiceRecognition)!=null?E:{},m=c.recordingBackgroundColor,b=c.recordingIconColor,x=c.recordingBorderColor;if(Ga(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=G.querySelector("svg");D&&D.setAttribute("stroke",b)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},mf=()=>{var q,B,xe,me,te,Ee,$e,Te;if(!G)return;ul();let c=(q=r.voiceRecognition)!=null?q:{},m=$.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",x=(me=(xe=c.processingIconColor)!=null?xe:Ge==null?void 0:Ge.color)!=null?me:"",E=(Ee=(te=c.processingBackgroundColor)!=null?te:Ge==null?void 0:Ge.backgroundColor)!=null?Ee:"",D=(Te=($e=c.processingBorderColor)!=null?$e:Ge==null?void 0:Ge.borderColor)!=null?Te:"";Ga(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=E,G.style.borderColor=D;let N=x||"currentColor";G.style.color=N,ml(b,N),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},gf=()=>{var xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe;if(!G)return;ul();let c=(xe=r.voiceRecognition)!=null?xe:{},m=$.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(me=c.speakingIconName)!=null?me:b,E=(Te=c.speakingIconColor)!=null?Te:m==="barge-in"?(Ee=(te=c.recordingIconColor)!=null?te:Ge==null?void 0:Ge.color)!=null?Ee:"":($e=Ge==null?void 0:Ge.color)!=null?$e:"",D=(dt=c.speakingBackgroundColor)!=null?dt:m==="barge-in"?(st=c.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ge==null?void 0:Ge.backgroundColor)!=null?Ke:"",N=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=Ge==null?void 0:Ge.borderColor)!=null?Ie:"";Ga(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=D,G.style.borderColor=N;let q=E||"currentColor";G.style.color=q,ml(x,q);let B=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",B),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},fo=()=>{var c,m,b;G&&(Ga(),Ge&&(G.style.backgroundColor=(c=Ge.backgroundColor)!=null?c:"",G.style.color=(m=Ge.color)!=null?m:"",G.style.borderColor=(b=Ge.borderColor)!=null?b:"",ml(Ge.iconName,Ge.color||"currentColor"),Ge=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ja=()=>{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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),_n(),dr("user"),$.isVoiceActive()?Xs():fo()});return}if(ht){let b=ne.value.trim();yt.manuallyDeactivated=!0,_n(),xn("user"),b&&(ne.value="",ne.style.height="auto",$.sendMessage(b))}else yt.manuallyDeactivated=!1,_n(),Qt("user")};jn=Ja,G&&(G.addEventListener("click",Ja),ft.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),fo()):xn("system"),G&&G.removeEventListener("click",Ja)}));let ff=s.on("assistant:complete",()=>{Fs&&(yt.active||yt.manuallyDeactivated||Fs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!yt.active&&!yt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("auto"),$.isVoiceActive()&&Xs()}):Qt("auto"))},600))});ft.push(ff);let hf=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ft.push(hf);let fs=()=>{Dt(!M,"user")},on=null,sn=null;if(S&&!_()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});m&&(sn=m)}sn||(on=Sa(r,fs))}on?e.appendChild(on.element):sn&&e.appendChild(sn),go(),as(),Bo(),ms($.isStreaming()),mt()==="follow"?Hr(!0):Vs(),Oa(),k&&(!S||_()?setTimeout(()=>gs(),0):M&&setTimeout(()=>gs(),200));let Ys=()=>{var B,xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt,P,Be,Ne,he,Ft,Ot;if(_()){yn(),go();return}let c=mn(r),m=(xe=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?xe:!1,b=c||m||((te=(me=r.launcher)==null?void 0:me.fullHeight)!=null?te:!1),x=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,E=(Te=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?Te:!0,D=(Ke=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?Ke:640,N=x.innerWidth<=D,q=E&&N&&S;try{if(q){hr(),Ao(e,r);return}if(W&&(W=!1,hr(),Ao(e,r)),!S&&!c){fe.style.height="",fe.style.width="";return}if(!m&&!c){let Jt=(pt=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?pt:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:nr;fe.style.width=Ct,fe.style.maxWidth=Ct}if(Lr(),!b){let Jt=x.innerHeight,Ct=64,zt=(Pe=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Pe:0,Zn=Math.max(200,Jt-Ct),ln=Math.min(640,Zn),Ye=Math.max(200,ln-zt);fe.style.height=`${Ye}px`}}finally{if(yn(),go(),M&&S){let Ct=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((wt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?wt:640),zt=(Be=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Be:!1,Zn=(he=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?he:!0,ln=mn(r)&&Zn&&Ct,Ye=zt||Zn&&Ct&&S||ln;if(Ye&&!rn){let It=e.getRootNode(),un=It instanceof ShadowRoot?It.host:e.closest(".persona-host");un&&!nn&&(nn=_l(un,(Ot=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Ot:Ln)),rn=$l(e.ownerDocument)}else Ye||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Ys();let wc=(Sd=e.ownerDocument.defaultView)!=null?Sd:window;if(wc.addEventListener("resize",Ys),ft.push(()=>wc.removeEventListener("resize",Ys)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe(Ue),ft.push(()=>c.disconnect())}Yn=ue.scrollTop;let Cc=Zr(ue),bf=()=>{let c=ue.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ue.ownerDocument.getSelection()},gl=()=>Bm(bf(),ue),Ac=()=>{let c=ue.scrollTop,m=Zr(ue),b=m<Cc;if(Cc=m,mt()!=="follow"){Yn=c,$n();return}let{action:x,nextLastScrollTop:E}=Li({following:Xn.isFollowing(),currentScrollTop:c,lastScrollTop:Yn,nearBottom:Zo(ue,cs),userScrollThreshold:Ba,isAutoScrolling:vr||Io||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Yn=E,x==="resume"){gl()||Wr();return}x==="pause"&&us()};if(ue.addEventListener("scroll",Ac,{passive:!0}),ft.push(()=>ue.removeEventListener("scroll",Ac)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{$a()});c.observe(ot),c.observe(ue),ft.push(()=>c.disconnect())}let Sc=()=>{mt()==="follow"&&Xn.isFollowing()&&gl()&&us()},Tc=ue.ownerDocument;Tc.addEventListener("selectionchange",Sc),ft.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let Ec=c=>{if(mt()!=="follow")return;let m=Pi({following:Xn.isFollowing(),deltaY:c.deltaY,nearBottom:Zo(ue,cs),resumeWhenNearBottom:!0});m==="pause"?us():m==="resume"&&!gl()&&Wr()};ue.addEventListener("wheel",Ec,{passive:!0}),ft.push(()=>ue.removeEventListener("wheel",Ec)),et.addEventListener("click",()=>{Wo(),ue.scrollTop=ue.scrollHeight,Yn=ue.scrollTop,Wr(),Hr(!0),$n()}),ft.push(()=>et.remove()),ft.push(()=>{$s(),Wo()});let Mc=()=>{H&&(cr&&(H.removeEventListener("click",cr),cr=null),F()?(H.style.display="",cr=()=>{Dt(!1,"user")},H.addEventListener("click",cr)):H.style.display="none")};Mc(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{$.clearMessages(),Ur.clear(),Wr(),wo(De.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)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(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()})})(),Ht&&Ht.addEventListener("submit",L),ne==null||ne.addEventListener("keydown",Wt),ne==null||ne.addEventListener("input",tt),ne==null||ne.addEventListener("paste",gn);let kc=(Td=e.ownerDocument)!=null?Td:document;kc.addEventListener("keydown",$t,!0);let Lc="persona-attachment-drop-active",Zs=0,fl=()=>{Zs=0,V.classList.remove(Lc)},hs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&At!==null},Pc=c=>{!nl(c.dataTransfer)||!hs()||(Zs++,Zs===1&&V.classList.add(Lc))},Ic=c=>{!nl(c.dataTransfer)||!hs()||(Zs--,Zs<=0&&fl())},Rc=c=>{!nl(c.dataTransfer)||!hs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Wc=c=>{var b;if(!nl(c.dataTransfer)||!hs())return;c.preventDefault(),c.stopPropagation(),fl();let m=Array.from((b=c.dataTransfer.files)!=null?b:[]);m.length!==0&&At.handleFiles(m)},ho=!0;V.addEventListener("dragenter",Pc,ho),V.addEventListener("dragleave",Ic,ho),e.addEventListener("dragover",Rc,ho),e.addEventListener("drop",Wc,ho);let Qa=e.ownerDocument,Hc=c=>{hs()&&c.preventDefault()},Bc=c=>{hs()&&c.preventDefault()};Qa.addEventListener("dragover",Hc),Qa.addEventListener("drop",Bc),ft.push(()=>{Ht&&Ht.removeEventListener("submit",L),ne==null||ne.removeEventListener("keydown",Wt),ne==null||ne.removeEventListener("input",tt),ne==null||ne.removeEventListener("paste",gn),kc.removeEventListener("keydown",$t,!0)}),ft.push(()=>{V.removeEventListener("dragenter",Pc,ho),V.removeEventListener("dragleave",Ic,ho),e.removeEventListener("dragover",Rc,ho),e.removeEventListener("drop",Wc,ho),Qa.removeEventListener("dragover",Hc),Qa.removeEventListener("drop",Bc),fl()}),ft.push(()=>{$.cancel()}),on?ft.push(()=>{on==null||on.destroy()}):sn&&ft.push(()=>{sn==null||sn.remove()});let pn={update(c){var En,Wn,Br,vn,Hn,Bn,_o,ea,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,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu;let m=r.toolCall,b=r.messageActions,x=(En=r.layout)==null?void 0:En.messages,E=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,q=(Wn=r.features)==null?void 0:Wn.showReasoning,B=(Br=r.features)==null?void 0:Br.showToolCalls,xe=(vn=r.features)==null?void 0:vn.toolCallDisplay,me=(Hn=r.features)==null?void 0:Hn.reasoningDisplay;r={...r,...c},hr(),Ao(e,r),Ki(e,r),Gi(e,r),Jn(),r.colorScheme!==E&&lo();let te=Pa.getForInstance(r.plugins);o.length=0,o.push(...te),S=(_o=(Bn=r.launcher)==null?void 0:Bn.enabled)!=null?_o:!0,O=(Rd=(ea=r.launcher)==null?void 0:ea.autoExpand)!=null?Rd:!1,ze=(Hd=(Wd=r.features)==null?void 0:Wd.showReasoning)!=null?Hd:!0,Ae=(Dd=(Bd=r.features)==null?void 0:Bd.showToolCalls)!=null?Dd:!0,be=(Nd=(Od=r.features)==null?void 0:Od.scrollToBottom)!=null?Nd:{};let Ee=mt();Le=(_d=(Fd=r.features)==null?void 0:Fd.scrollBehavior)!=null?_d:{},Ee!==mt()&&(Wo(),Wr()),Mr(),$n();let $e=Re;if(Re=(Ud=($d=r.features)==null?void 0:$d.showEventStreamToggle)!=null?Ud:!1,Re&&!$e){if(ce||(X=new ka(de),ce=new Ma(re,X),ge=ge!=null?ge:new La,X.open().then(()=>ce==null?void 0:ce.restore()).catch(()=>{}),$.setSSEEventCallback((Q,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Q,Tt),ge==null||ge.processEvent(Q,Tt),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!vt&&_e){let Q=(qd=(jd=r.features)==null?void 0:jd.eventStream)==null?void 0:qd.classNames,Tt="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"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");vt=h("button",Tt),vt.style.width="28px",vt.style.height="28px",vt.style.color=On.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let jt=Ce("activity","18px","currentColor",1.5);jt&&vt.appendChild(jt);let ut=De.clearChatButtonWrapper,Rt=De.closeButtonWrapper,hn=ut||Rt;hn&&hn.parentNode===_e?_e.insertBefore(vt,hn):_e.appendChild(vt),vt.addEventListener("click",()=>{ae?fr():Nr()})}}else!Re&&$e&&(fr(),vt&&(vt.remove(),vt=null),ce==null||ce.clear(),X==null||X.destroy(),ce=null,X=null,ge==null||ge.reset(),ge=null);if(((zd=r.launcher)==null?void 0:zd.enabled)===!1&&on&&(on.destroy(),on=null),((Vd=r.launcher)==null?void 0:Vd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Kd=r.launcher)==null?void 0:Kd.enabled)!==!1&&!on&&!sn){let Q=o.find(Tt=>Tt.renderLauncher);if(Q!=null&&Q.renderLauncher){let Tt=Q.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});Tt&&(sn=Tt,e.appendChild(sn))}sn||(on=Sa(r,fs),e.appendChild(on.element))}on&&on.update(r),Oe&&((Gd=r.launcher)==null?void 0:Gd.title)!==void 0&&(Oe.textContent=r.launcher.title),Qe&&((Jd=r.launcher)==null?void 0:Jd.subtitle)!==void 0&&(Qe.textContent=r.launcher.subtitle);let Te=(Qd=r.layout)==null?void 0:Qd.header;if((Te==null?void 0:Te.layout)!==T&&_e){let Q=Te?Ps(r,Te,{showClose:F(),onClose:()=>Dt(!1,"user")}):eo({config:r,showClose:F(),onClose:()=>Dt(!1,"user")});_e.replaceWith(Q.header),_e=Q.header,pe=Q.iconHolder,Oe=Q.headerTitle,Qe=Q.headerSubtitle,H=Q.closeButton,T=Te==null?void 0:Te.layout}else if(Te&&(pe&&(pe.style.display=Te.showIcon===!1?"none":""),Oe&&(Oe.style.display=Te.showTitle===!1?"none":""),Qe&&(Qe.style.display=Te.showSubtitle===!1?"none":""),H&&(H.style.display=Te.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){De.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Tt}=De;Tt&&!Tt.classList.contains("persona-absolute")&&(Q?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let Ke=((Xd=r.layout)==null?void 0:Xd.showHeader)!==!1;_e&&(_e.style.display=Ke?"":"none");let dt=((Yd=r.layout)==null?void 0:Yd.showFooter)!==!1;Ue&&(Ue.style.display=dt?"":"none"),yn(),$n(),S!==R?S?Dt(O,"auto"):(M=!0,go()):O!==I&&Dt(O,"auto"),I=O,R=S,Ys(),Mc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),qe=JSON.stringify(r.messageActions)!==JSON.stringify(b),Xe=JSON.stringify((Zd=r.layout)==null?void 0:Zd.messages)!==JSON.stringify(x),wt=((ep=r.loadingIndicator)==null?void 0:ep.render)!==(D==null?void 0:D.render)||((tp=r.loadingIndicator)==null?void 0:tp.renderIdle)!==(D==null?void 0:D.renderIdle)||((np=r.loadingIndicator)==null?void 0:np.showBubble)!==(D==null?void 0:D.showBubble),P=r.iterationDisplay!==N,Be=((op=(rp=r.features)==null?void 0:rp.showReasoning)!=null?op:!0)!==(q!=null?q:!0)||((ap=(sp=r.features)==null?void 0:sp.showToolCalls)!=null?ap:!0)!==(B!=null?B:!0)||JSON.stringify((ip=r.features)==null?void 0:ip.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((lp=r.features)==null?void 0:lp.reasoningDisplay)!==JSON.stringify(me);(Pe||qe||Xe||wt||P||Be)&&$&&(Ns++,Ho(ot,$.getMessages(),ke));let he=(cp=r.launcher)!=null?cp:{},Ft=(dp=he.headerIconHidden)!=null?dp:!1,Ot=(up=(pp=r.layout)==null?void 0:pp.header)==null?void 0:up.showIcon,Jt=Ft||Ot===!1,Ct=he.headerIconName,zt=(mp=he.headerIconSize)!=null?mp:"48px";if(pe){let Q=V.querySelector(".persona-border-b-persona-divider"),Tt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Jt)pe.style.display="none",Q&&Tt&&!Q.contains(Tt)&&Q.insertBefore(Tt,Q.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,Q&&Tt&&(Q.contains(pe)?pe.nextSibling!==Tt&&(pe.remove(),Q.insertBefore(pe,Tt)):Q.insertBefore(pe,Tt)),Ct){let ut=parseFloat(zt)||24,Rt=Ce(Ct,ut*.6,"#ffffff",2);Rt?pe.replaceChildren(Rt):pe.textContent=(gp=he.agentIconText)!=null?gp:"\u{1F4AC}"}else if(he.iconUrl){let ut=pe.querySelector("img");if(ut)ut.src=he.iconUrl,ut.style.height=zt,ut.style.width=zt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=zt,Rt.style.width=zt,pe.replaceChildren(Rt)}}else{let ut=pe.querySelector("svg"),Rt=pe.querySelector("img");(ut||Rt)&&pe.replaceChildren(),pe.textContent=(fp=he.agentIconText)!=null?fp:"\u{1F4AC}"}let jt=pe.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let Zn=(bp=(hp=r.layout)==null?void 0:hp.header)==null?void 0:bp.showTitle,ln=(xp=(yp=r.layout)==null?void 0:yp.header)==null?void 0:xp.showSubtitle;if(Oe&&(Oe.style.display=Zn===!1?"none":""),Qe&&(Qe.style.display=ln===!1?"none":""),H){((wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showCloseButton)===!1?H.style.display="none":H.style.display="";let Tt=(Cp=he.closeButtonSize)!=null?Cp:"32px",jt=(Ap=he.closeButtonPlacement)!=null?Ap:"inline";H.style.height=Tt,H.style.width=Tt;let{closeButtonWrapper:ut}=De,Rt=jt==="top-right",hn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Rt!==hn)if(ut.remove(),Rt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",V.style.position="relative",V.appendChild(ut);else{let gt=(Tp=(Sp=he.clearChat)==null?void 0:Sp.placement)!=null?Tp:"inline",bn=(Mp=(Ep=he.clearChat)==null?void 0:Ep.enabled)!=null?Mp:!0;ut.className=bn&>==="inline"?"":"persona-ml-auto";let Un=V.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(ut)}if(H.style.color=he.closeButtonColor||On.actionIconColor,he.closeButtonBackgroundColor?(H.style.backgroundColor=he.closeButtonBackgroundColor,H.classList.remove("hover:persona-bg-gray-100")):(H.style.backgroundColor="",H.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let gt=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";H.style.border=`${gt} solid ${bn}`,H.classList.remove("persona-border-none")}else H.style.border="",H.classList.add("persona-border-none");he.closeButtonBorderRadius?(H.style.borderRadius=he.closeButtonBorderRadius,H.classList.remove("persona-rounded-full")):(H.style.borderRadius="",H.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(H.style.paddingLeft=he.closeButtonPaddingX,H.style.paddingRight=he.closeButtonPaddingX):(H.style.paddingLeft="",H.style.paddingRight=""),he.closeButtonPaddingY?(H.style.paddingTop=he.closeButtonPaddingY,H.style.paddingBottom=he.closeButtonPaddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Mn=(kp=he.closeButtonIconName)!=null?kp:"x",Cr=(Lp=he.closeButtonIconText)!=null?Lp:"\xD7";H.innerHTML="";let Dn=Ce(Mn,"28px","currentColor",1);Dn?H.appendChild(Dn):H.textContent=Cr;let an=(Pp=he.closeButtonTooltipText)!=null?Pp:"Close chat",tr=(Ip=he.closeButtonShowTooltip)!=null?Ip:!0;if(H.setAttribute("aria-label",an),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!H)return;let $o=H.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=H.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};ut.addEventListener("mouseenter",bn),ut.addEventListener("mouseleave",Un),H.addEventListener("focus",bn),H.addEventListener("blur",Un),ut._cleanupTooltip=()=>{Un(),ut&&(ut.removeEventListener("mouseenter",bn),ut.removeEventListener("mouseleave",Un)),H&&(H.removeEventListener("focus",bn),H.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:It}=De;if(Ye){let Q=(Rp=he.clearChat)!=null?Rp:{},Tt=(Wp=Q.enabled)!=null?Wp:!0,jt=(Bp=(Hp=r.layout)==null?void 0:Hp.header)==null?void 0:Bp.showClearChat,ut=jt!==void 0?jt:Tt,Rt=(Dp=Q.placement)!=null?Dp:"inline";if(It){It.style.display=ut?"":"none";let{closeButtonWrapper:hn}=De;!_()&&hn&&!hn.classList.contains("persona-absolute")&&(ut?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let Mn=Rt==="top-right",Cr=It.classList.contains("persona-absolute");if(!_()&&Mn!==Cr&&ut){if(It.remove(),Mn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",V.style.position="relative",V.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let an=V.querySelector(".persona-border-b-persona-divider"),tr=De.closeButtonWrapper;an&&tr&&tr.parentElement===an?an.insertBefore(It,tr):an&&an.appendChild(It)}let Dn=De.closeButtonWrapper;Dn&&!Dn.classList.contains("persona-absolute")&&(Mn?Dn.classList.add("persona-ml-auto"):Dn.classList.remove("persona-ml-auto"))}}if(ut){if(!_()){let gt=(Op=Q.size)!=null?Op:"32px";Ye.style.height=gt,Ye.style.width=gt}let hn=(Np=Q.iconName)!=null?Np:"refresh-cw",Mn=(Fp=Q.iconColor)!=null?Fp:"";Ye.style.color=Mn||On.actionIconColor,Ye.innerHTML="";let Cr=_()?"14px":"20px",Dn=Ce(hn,Cr,"currentColor",2);if(Dn&&Ye.appendChild(Dn),Q.backgroundColor?(Ye.style.backgroundColor=Q.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let gt=Q.borderWidth||"0px",bn=Q.borderColor||"transparent";Ye.style.border=`${gt} solid ${bn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Q.borderRadius?(Ye.style.borderRadius=Q.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Q.paddingX?(Ye.style.paddingLeft=Q.paddingX,Ye.style.paddingRight=Q.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Q.paddingY?(Ye.style.paddingTop=Q.paddingY,Ye.style.paddingBottom=Q.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let an=(_p=Q.tooltipText)!=null?_p:"Clear chat",tr=($p=Q.showTooltip)!=null?$p:!0;if(Ye.setAttribute("aria-label",an),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!Ye)return;let $o=Ye.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=Ye.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};It.addEventListener("mouseenter",bn),It.addEventListener("mouseleave",Un),Ye.addEventListener("focus",bn),Ye.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",bn),It.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",bn),Ye.removeEventListener("blur",Un))}}}}let un=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ia],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick];w=Ra({parsers:un,handlers:ur,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ke=Ag(r,w,oe),$.updateConfig(r),Ho(ot,$.getMessages(),ke),as(),Bo(),ms($.isStreaming());let er=((Up=r.voiceRecognition)==null?void 0:Up.enabled)===!0,Do=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((qp=(jp=r.voiceRecognition)==null?void 0:jp.provider)==null?void 0:qp.type)==="runtype";if(er&&(Do||Oo))if(!G||!xt){let Q=uf(r.voiceRecognition,r.sendButton);Q&&(G=Q.micButton,xt=Q.micButtonWrapper,Kt.insertBefore(xt,Nn),G.addEventListener("click",Ja),G.disabled=$.isStreaming())}else{let Q=(zp=r.voiceRecognition)!=null?zp:{},Tt=(Vp=r.sendButton)!=null?Vp:{},jt=(Kp=Q.iconName)!=null?Kp:"mic",ut=(Gp=Tt.size)!=null?Gp:"40px",Rt=(Jp=Q.iconSize)!=null?Jp:ut,hn=parseFloat(Rt)||24;G.style.width=Rt,G.style.height=Rt,G.style.minWidth=Rt,G.style.minHeight=Rt;let Mn=(Xp=(Qp=Q.iconColor)!=null?Qp:Tt.textColor)!=null?Xp:"currentColor";G.innerHTML="";let Cr=Ce(jt,hn,Mn,2);Cr?G.appendChild(Cr):G.textContent="\u{1F3A4}";let Dn=(Yp=Q.backgroundColor)!=null?Yp:Tt.backgroundColor;Dn?G.style.backgroundColor=Dn:G.style.backgroundColor="",Mn?G.style.color=Mn:G.style.color="var(--persona-text, #111827)",Q.borderWidth?(G.style.borderWidth=Q.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Q.borderColor?G.style.borderColor=Q.borderColor:G.style.borderColor="",Q.paddingX?(G.style.paddingLeft=Q.paddingX,G.style.paddingRight=Q.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Q.paddingY?(G.style.paddingTop=Q.paddingY,G.style.paddingBottom=Q.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let an=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),tr=(Zp=Q.tooltipText)!=null?Zp:"Start voice recognition";if(((eu=Q.showTooltip)!=null?eu:!1)&&tr)if(an)an.textContent=tr,an.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=tr,xt==null||xt.insertBefore(bn,G)}else an&&(an.style.display="none");xt.style.display="",G.disabled=$.isStreaming()}else G&&xt&&(xt.style.display="none",((nu=(tu=r.voiceRecognition)==null?void 0:tu.provider)==null?void 0:nu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ht&&xn());if(((ru=r.attachments)==null?void 0:ru.enabled)===!0)if(!we||!lt){let Q=(ou=r.attachments)!=null?ou:{},jt=(au=((su=r.sendButton)!=null?su:{}).size)!=null?au:"40px";nt||(nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),nt.style.display="none",Ht.insertBefore(nt,ne)),le||(le=document.createElement("input"),le.type="file",le.accept=((iu=Q.allowedTypes)!=null?iu:Yr).join(","),le.multiple=((lu=Q.maxFiles)!=null?lu:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Ht.insertBefore(le,ne)),we=h("div","persona-send-button-wrapper"),lt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),lt.type="button",lt.setAttribute("aria-label",(cu=Q.buttonTooltipText)!=null?cu:"Attach file");let ut=(du=Q.buttonIconName)!=null?du:"paperclip",Rt=jt,hn=parseFloat(Rt)||40,Mn=Math.round(hn*.6);lt.style.width=Rt,lt.style.height=Rt,lt.style.minWidth=Rt,lt.style.minHeight=Rt,lt.style.fontSize="18px",lt.style.lineHeight="1",lt.style.backgroundColor="transparent",lt.style.color="var(--persona-primary, #111827)",lt.style.border="none",lt.style.borderRadius="6px",lt.style.transition="background-color 0.15s ease",lt.addEventListener("mouseenter",()=>{lt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),lt.addEventListener("mouseleave",()=>{lt.style.backgroundColor="transparent"});let Cr=Ce(ut,Mn,"currentColor",1.5);Cr?lt.appendChild(Cr):lt.textContent="\u{1F4CE}",lt.addEventListener("click",tr=>{tr.preventDefault(),le==null||le.click()}),we.appendChild(lt);let Dn=(pu=Q.buttonTooltipText)!=null?pu:"Attach file",an=h("div","persona-send-button-tooltip");an.textContent=Dn,we.appendChild(an),Pt.append(we),!At&&le&&nt&&(At=Yo.fromConfig(Q),At.setPreviewsContainer(nt),le.addEventListener("change",async()=>{At&&(le!=null&&le.files)&&(await At.handleFileSelect(le.files),le.value="")})),V.querySelector(".persona-attachment-drop-overlay")||V.appendChild(Sg(Q.dropOverlay))}else{we.style.display="";let Q=(uu=r.attachments)!=null?uu:{};le&&(le.accept=((mu=Q.allowedTypes)!=null?mu:Yr).join(","),le.multiple=((gu=Q.maxFiles)!=null?gu:4)>1),At&&At.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else we&&(we.style.display="none"),At&&At.clearAttachments(),(fu=V.querySelector(".persona-attachment-drop-overlay"))==null||fu.remove();let Xt=(hu=r.sendButton)!=null?hu:{},No=(bu=Xt.useIcon)!=null?bu:!1,bo=(yu=Xt.iconText)!=null?yu:"\u2191",yo=Xt.iconName,Kr=(xu=Xt.tooltipText)!=null?xu:"Send message",Fo=(vu=Xt.showTooltip)!=null?vu:!1,wr=(wu=Xt.size)!=null?wu:"40px",rt=Xt.backgroundColor,fn=Xt.textColor;if(No){if(Ve.style.width=wr,Ve.style.height=wr,Ve.style.minWidth=wr,Ve.style.minHeight=wr,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",fn?Ve.style.color=fn:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let Q=parseFloat(wr)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",jt=Ce(yo,Q,Tt,2);jt?Ve.appendChild(jt):Ve.textContent=bo}else Ve.textContent=bo;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(Au=(Cu=r.copy)==null?void 0:Cu.sendButtonLabel)!=null?Au:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),fn?Ve.style.color=fn:Ve.classList.add("persona-text-white");Xt.borderWidth?(Ve.style.borderWidth=Xt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Xt.borderColor?Ve.style.borderColor=Xt.borderColor:Ve.style.borderColor="",Xt.paddingX?(Ve.style.paddingLeft=Xt.paddingX,Ve.style.paddingRight=Xt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Xt.paddingY?(Ve.style.paddingTop=Xt.paddingY,Ve.style.paddingBottom=Xt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ut=Nn==null?void 0:Nn.querySelector(".persona-send-button-tooltip");if(Fo&&Kr)if(Ut)Ut.textContent=Kr,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Kr,Nn==null||Nn.insertBefore(Q,Ve)}else Ut&&(Ut.style.display="none");let _t=(ku=(Su=r.layout)==null?void 0:Su.contentMaxWidth)!=null?ku:_()?(Mu=(Eu=(Tu=r.launcher)==null?void 0:Tu.composerBar)==null?void 0:Eu.contentMaxWidth)!=null?Mu:"720px":void 0;_t?(ot.style.maxWidth=_t,ot.style.marginLeft="auto",ot.style.marginRight="auto",ot.style.width="100%",Ht&&(Ht.style.maxWidth=_t,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Et&&(Et.style.maxWidth=_t,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(ot.style.maxWidth="",ot.style.marginLeft="",ot.style.marginRight="",ot.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let bt=(Lu=r.statusIndicator)!=null?Lu:{},Yt=(Pu=bt.visible)!=null?Pu:!0;if(cn.style.display=Yt?"":"none",$){let Q=$.getStatus();Ze(cn,(jt=>{var ut,Rt,hn,Mn;return jt==="idle"?(ut=bt.idleText)!=null?ut:kn.idle:jt==="connecting"?(Rt=bt.connectingText)!=null?Rt:kn.connecting:jt==="connected"?(hn=bt.connectedText)!=null?hn:kn.connected:jt==="error"?(Mn=bt.errorText)!=null?Mn:kn.error:kn[jt]})(Q),bt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=bt.align==="left"?"persona-text-left":bt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(kt)},open(){F()&&Dt(!0,"api")},close(){F()&&Dt(!1,"api")},toggle(){F()&&Dt(!M,"api")},clearChat(){In=!1,$.clearMessages(),Ur.clear(),Wr();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)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(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()},setMessage(c){return!ne||$.isStreaming()?!1:(!M&&F()&&Dt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ne.value.trim();return m?(!M&&F()&&Dt(!0,"system"),ne.value="",ne.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()||(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("user"),$.isVoiceActive()&&Xs()})),!0):ht?!0:Cn()?(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),Qt("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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()}),!0):!1:ht?(yt.manuallyDeactivated=!0,_n(),xn("user"),!0):!1},injectMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!M&&F()&&Dt(!0,"system");let m=$.injectAssistantMessage(c);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!M&&F()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!M&&F()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!M&&F()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){ce&&(ge==null||ge.processEvent(c.type,c.payload),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Re||!ce||Nr()},hideEventStream(){ae&&fr()},isEventStreamVisible(){return ae},showArtifacts(){gr(r)&&(In=!1,Jn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){gr(r)&&(In=!0,Jn())},upsertArtifact(c){return gr(r)?(In=!1,$.upsertArtifact(c)):null},selectArtifact(c){gr(r)&&$.selectArtifact(c)},clearArtifacts(){gr(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 S&&!M&&!_()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,m,b){let E=$.getMessages().find(D=>{var N;return D.variant==="approval"&&((N=D.approval)==null?void 0:N.id)===c});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${c}`);if(E.approval.toolType==="webmcp"){$.resolveWebMcpApproval(E.id,m);return}return $.resolveApproval(E.approval,m,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return F()&&M},isVoiceActive(){return yt.active},getState(){return{open:F()&&M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=el({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitCSATFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=tl({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitNPSFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.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(){je!=null&&(clearInterval(je),je=null),ft.forEach(c=>c()),ve.remove(),Je==null||Je.remove(),on==null||on.destroy(),sn==null||sn.remove(),cr&&H.removeEventListener("click",cr)}};if((((Ed=n==null?void 0:n.debugTools)!=null?Ed:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:pn,getMessages:pn.getMessages,getStatus:pn.getStatus,getMetadata:pn.getPersistentMetadata,updateMetadata:pn.updatePersistentMetadata,clearHistory:()=>pn.clearChat(),setVoiceActive:b=>b?pn.startVoiceRecognition():pn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ft.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=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),Re){let q=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.showEventStream()},B=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.showArtifacts()},x=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.hideArtifacts()},E=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&pn.upsertArtifact(B.artifact)},D=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&pn.selectArtifact(B.id)},N=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),ft.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let pr=qb(r.persistState);if(pr&&F()){let c=zb(pr.storage),m=`${pr.keyPrefix}widget-open`,b=`${pr.keyPrefix}widget-voice`,x=`${pr.keyPrefix}widget-voice-mode`;if(c){let E=((Md=pr.persist)==null?void 0:Md.openState)&&c.getItem(m)==="true",D=((kd=pr.persist)==null?void 0:kd.voiceState)&&c.getItem(b)==="true",N=((Ld=pr.persist)==null?void 0:Ld.voiceState)&&c.getItem(x)==="true";if(E&&setTimeout(()=>{pn.open(),setTimeout(()=>{var q;if(D||N)pn.startVoiceRecognition();else if((q=pr.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Pd=pr.persist)!=null&&Pd.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Id=pr.persist)!=null&&Id.voiceState&&(s.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(x,q.viaVoice?"true":"false")})),pr.clearOnChatClear){let q=()=>{c.removeItem(m),c.removeItem(b),c.removeItem(x)},B=()=>q();window.addEventListener("persona:clear-chat",B),ft.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&F()&&setTimeout(()=>{pn.open()},0),Vr(),pn};var Vb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Kb=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Gb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Jb=(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 o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&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.")},Tg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},ic=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=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ic(e)},oc=e=>{e.style.transition=""},sc=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=""},ac=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Qb=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Xb=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Mg=(e,t,n,r,o,s,a)=>{var v,y,w,S,O,k;let i=rr(s),d=i.reveal==="push";Qb(e,t,n,r,d),Xb(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(y=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?y:!0,u=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),sc(t),oc(r),Eg(r),ac(n),ol(o,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((k=(O=s==null?void 0:s.launcher)==null?void 0:O.zIndex)!=null?k:Ln),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"),Eg(r),Kb(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",sc(t),oc(r),ac(n),ol(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":R;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=I,r.style.transform=T,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",oc(r),ic(r),ol(o,r);let I=Vb(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),T=i.animate?"transform 180ms ease":"none",W=i.side==="right"?a?`translateX(-${I}px)`:"translateX(0)":a?"translateX(0)":`translateX(-${I}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=`${R+I}px`,t.style.transition=T,t.style.transform=W,n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}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="",sc(t),ic(r),ac(n),ol(o,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",T=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",Gb(r,i.maxHeight),r.style.overflow=I||W?"hidden":"visible",r.style.transition=T,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Yb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Tg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Tg(n,r)},destroy(){n.remove()}}},Zb=(e,t)=>{var k,I,R,T;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(I=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||I?(T=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?T:!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(),rr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Mg(a,i,d,l,p,t,u)}),f.observe(a))},y=!1,w=()=>{Mg(a,i,d,l,p,t,u),v(),u&&!y&&a.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,Jb(a,rr(t)))},S=a.ownerDocument.defaultView,O=()=>{w()};return S==null||S.addEventListener("resize",O),rr(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(W){let _=W.launcherEnabled?W.open:!0;u!==_&&(u=_,w())},updateConfig(W){var _,F;t=W,((F=(_=t==null?void 0:t.launcher)==null?void 0:_.enabled)!=null?F:!0)===!1&&(u=!0),w()},destroy(){S==null||S.removeEventListener("resize",O),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Wa=(e,t)=>mn(t)?Zb(e,t):Yb(e,t);var lc={},kg=!1,ey=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},ty=()=>{try{if(typeof lc!="undefined"&&lc.url)return new URL("../widget.css",lc.url).href}catch{}return null},Lg=(e,t)=>{let n=ty(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},cc=e=>{let t=ey(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Wa(t,o),a,i=[],d=(w,S)=>{var R,T;let k=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||mn(S),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),k&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let W=w.attachShadow({mode:"open"});W.appendChild(I),Lg(W,r)}else w.appendChild(I),Lg(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(s.host,o);a=rl(w,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(kg||(kg=!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(),s.destroy(),s=Wa(t,w),o=w,u()},v={update(w){var T,W,_,F,M,j;let S={...o,...w,launcher:{...(T=o==null?void 0:o.launcher)!=null?T:{},...(W=w==null?void 0:w.launcher)!=null?W:{},dock:{...(F=(_=o==null?void 0:o.launcher)==null?void 0:_.dock)!=null?F:{},...(j=(M=w==null?void 0:w.launcher)==null?void 0:M.dock)!=null?j:{}}}},O=mn(o),k=mn(S),I=Eo(o),R=Eo(S);if(O!==k||I!==R){g(S);return}o=S,s.updateConfig(o),a.update(w),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(v,{get(w,S,O){if(S==="host")return s.host;if(S in w)return Reflect.get(w,S,O);let k=a[S];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var Hg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ny=new Set(["button","a","input","select","textarea","details","summary"]),ry=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),dc=/\b(product|card|item|listing|result)\b/i,uc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,oy=3e3,sy=100;function Bg(e){let t=typeof e.className=="string"?e.className:"";if(dc.test(t)||e.id&&dc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&dc.test(r.value))return!0}return!1}function Dg(e){var t;return uc.test(((t=e.textContent)!=null?t:"").trim())}function Og(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function ay(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Pg(e){let t=e.match(uc);return t?t[0]:null}function Ig(e){var r,o,s;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&&((o=t.textContent)!=null&&o.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(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function iy(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var ly="commerce-card",cy="result-card";function Rg(e){return!Bg(e)||!Dg(e)||!Og(e)&&!ay(e)?0:5200}function Wg(e){var r;return!Bg(e)||Dg(e)||!Og(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 mc=[{id:ly,scoreElement(e){return Rg(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||uc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Rg(e)===0)return null;let{title:n,href:r}=Ig(e),o=(p=(l=Pg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Pg(t.text))!=null?p:"",s=iy(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
107
|
+
`}if(!x&&!c){let Ut="max-height: -moz-available !important; max-height: stretch !important;",_t=m?"":"padding-top: 1.25em !important;",bt=m?"":`z-index: ${(fn=(rt=r.launcher)==null?void 0:rt.zIndex)!=null?fn:Ln} !important;`;ve.style.cssText+=Ut+_t+bt}Xe()};hr(),Ao(e,r),Ki(e,r),Gi(e,r);let ft=[];ft.push(()=>{document.removeEventListener("keydown",so)});let nn=null,rn=null;ft.push(()=>{nn==null||nn(),nn=null,rn==null||rn(),rn=null}),zn&&ft.push(()=>{zn==null||zn.disconnect(),zn=null}),ft.push(()=>{Rn==null||Rn(),Rn=null,$r(),Bt&&(Bt.remove(),Bt=null),St==null||St.element.style.removeProperty("width"),St==null||St.element.style.removeProperty("maxWidth")}),Re&&ft.push(()=>{He!==null&&(cancelAnimationFrame(He),He=null),K==null||K.destroy(),K=null,ce==null||ce.destroy(),ce=null,X=null});let Qn=null,lo=()=>{Qn&&(Qn(),Qn=null),r.colorScheme==="auto"&&(Qn=Ti(()=>{Ao(e,r)}))};lo(),ft.push(()=>{Qn&&(Qn(),Qn=null)});let ye=(xd=r.features)==null?void 0:xd.streamAnimation;if(ye!=null&&ye.type&&ye.type!=="none"){let c=xa(ye.type,ye.plugins);c&&(Fl(c,e),ft.push(()=>jm(e)))}let br=rg(Et),cr=null,$,as=c=>{var x,E;if(!$)return;let m=c!=null?c:$.getMessages(),b=((E=(x=r.features)==null?void 0:x.suggestReplies)==null?void 0:E.enabled)!==!1?oi(m):null;b?br.render(b,$,ne,m,r.suggestionChipsConfig,{agentPushed:!0}):m.some(D=>D.role==="user")?br.render([],$,ne,m):br.render(r.suggestionChips,$,ne,m,r.suggestionChipsConfig)},Pr=!1,Ur=Im(),jr=new Map,Ir=new Map,yr=new Map,Ns=0,Xn=ki(),Yn=0,xr=null,vr=!1,Io=!1,qr=0,Tn=null,Rr=null,is=!1,Ro=!1,ls=null,Ba=4,cs=24,Da=80,ds=new Map,yt={active:!1,manuallyDeactivated:!1,lastUserMessageWasVoice:!1,lastUserMessageId:null},Fs=(wd=(vd=r.voiceRecognition)==null?void 0:vd.autoResume)!=null?wd:!1,dr=c=>{s.emit("voice:state",{active:yt.active,source:c,timestamp:Date.now()})},_n=()=>{g(c=>({...c,voiceState:{active:yt.active,timestamp:Date.now(),manuallyDeactivated:yt.manuallyDeactivated}}))},Oa=()=>{var x,E;if(((x=r.voiceRecognition)==null?void 0:x.enabled)===!1)return;let c=rc(d.voiceState),m=!!c.active,b=Number((E=c.timestamp)!=null?E:0);yt.manuallyDeactivated=!!c.manuallyDeactivated,m&&Date.now()-b<$b&&setTimeout(()=>{var D,N;yt.active||(yt.manuallyDeactivated=!1,((N=(D=r.voiceRecognition)==null?void 0:D.provider)==null?void 0:N.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("restore"),$.isVoiceActive()&&Xs()}):Qt("restore"))},1e3)},Na=()=>$?Cg($.getMessages()).filter(c=>!c.__skipPersist):[];function ps(c){if(!(i!=null&&i.save))return;let b={messages:c?Cg(c):$?Na():[],metadata:d,artifacts:Vn.artifacts,selectedArtifactId:Vn.selectedId};try{let x=i.save(b);x instanceof Promise&&x.catch(E=>{typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",E)})}catch(x){typeof console!="undefined"&&console.error("[AgentWidget] Failed to persist state:",x)}}let zr=null,_s=()=>ve.querySelector("#persona-scroll-container")||ue,co=()=>{zr!==null&&(cancelAnimationFrame(zr),zr=null),vr=!1},$s=()=>{xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!1,co()},Us=()=>{qr>0?(An.textContent=String(qr),An.style.display="",et.setAttribute("aria-label",`${Gt()||"Jump to latest"} (${qr} new)`)):(An.textContent="",An.style.display="none",et.setAttribute("aria-label",Gt()||"Jump to latest"))},js=()=>{qr!==0&&(qr=0,Us())},qs=()=>mt()==="follow"?!Xn.isFollowing():!Zo(ue,cs),$n=()=>{if(!wn()||ae){et.parentNode&&et.remove(),et.style.display="none";return}et.parentNode!==V&&V.appendChild(et),yn();let m=Zr(ue)>0&&qs();m||js(),et.style.display=m?"":"none"},us=()=>{Xn.pause()&&($s(),$n())},Wr=()=>{Xn.resume(),js(),$n()},Hr=(c=!1)=>{mt()==="follow"&&Xn.isFollowing()&&(!c&&!Pr||(xr!==null&&(cancelAnimationFrame(xr),xr=null),Io=!0,xr=requestAnimationFrame(()=>{xr=null,Io=!1,Xn.isFollowing()&&Fa(_s(),c?220:140)})))},zs=(c,m,b,x=()=>!0)=>{let E=c.scrollTop,D=m(),N=D-E;co();let q=performance.now();vr=!0;let B=me=>1-Math.pow(1-me,3),xe=me=>{if(!x()){co();return}let te=m();te!==D&&(D=te,N=D-E);let Ee=me-q,$e=Math.min(Ee/b,1),Te=B($e),st=E+N*Te;c.scrollTop=st,Yn=c.scrollTop,$e<1?zr=requestAnimationFrame(xe):(c.scrollTop=D,Yn=c.scrollTop,zr=null,vr=!1)};zr=requestAnimationFrame(xe)},Fa=(c,m=500)=>{let b=Zr(c)-c.scrollTop;if(Math.abs(b)<1){Yn=c.scrollTop;return}if(Math.abs(b)>=Da){co(),vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1;return}zs(c,()=>Zr(c),m,()=>Xn.isFollowing())},Vs=()=>{let c=_s();vr=!0,c.scrollTop=Zr(c),Yn=c.scrollTop,vr=!1,$n()},Ks=c=>{Sn.style.height=`${Math.max(0,Math.round(c))}px`,Tn&&(Tn.spacerHeight=Math.max(0,c))},Wo=()=>{Rr!==null&&(cancelAnimationFrame(Rr),Rr=null),co(),Tn=null,Sn.style.height="0px"},_a=c=>{Rr!==null&&cancelAnimationFrame(Rr),Rr=requestAnimationFrame(()=>{var xe;Rr=null;let m=typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(c):c.replace(/"/g,'\\"'),b=ue.querySelector(`[data-message-id="${m}"]`);if(!b)return;let x=0,E=b;for(;E&&E!==ue;)x+=E.offsetTop,E=E.offsetParent;let D=(xe=Tn==null?void 0:Tn.spacerHeight)!=null?xe:0,N=ue.scrollHeight-D,{targetScrollTop:q,spacerHeight:B}=Dm({anchorOffsetTop:x,topOffset:Mt(),viewportHeight:ue.clientHeight,contentHeight:N});Tn={initialSpacerHeight:B,contentHeightAtAnchor:N,spacerHeight:B},Ks(B),zs(ue,()=>q,220)})},$a=()=>{if(mt()==="follow"){if(!Xn.isFollowing()||Zo(ue,1))return;Hr(!Pr);return}if(Tn&&Tn.initialSpacerHeight>0){let c=ue.scrollHeight-Tn.spacerHeight,m=Om({initialSpacerHeight:Tn.initialSpacerHeight,contentHeightAtAnchor:Tn.contentHeightAtAnchor,currentContentHeight:c});m!==Tn.spacerHeight&&Ks(m)}$n()},Ua=c=>{let m=mt();m==="follow"?(Wr(),Hr(!0)):m==="anchor-top"&&_a(c)},ja=c=>{let m=new Map;c.forEach(b=>{let x=ds.get(b.id);m.set(b.id,{streaming:b.streaming,role:b.role}),!x&&b.role==="assistant"&&(s.emit("assistant:message",b),!Ro&&mt()!=="anchor-top"&&qs()&&(qr+=1,Us(),$n())),b.role==="assistant"&&(x!=null&&x.streaming)&&b.streaming===!1&&s.emit("assistant:complete",b),b.variant==="approval"&&b.approval&&(x?b.approval.status!=="pending"&&s.emit("approval:resolved",{approval:b.approval,decision:b.approval.status}):s.emit("approval:requested",{approval:b.approval,message:b}))}),ds.clear(),m.forEach((b,x)=>{ds.set(x,b)})},Ho=(c,m,b)=>{var pt,Ie,Pe,qe,Xe,wt;let x=document.createElement("div"),D=(()=>{var Be;let P=o.find(Ne=>Ne.renderLoadingIndicator);if(P!=null&&P.renderLoadingIndicator)return P.renderLoadingIndicator;if((Be=r.loadingIndicator)!=null&&Be.render)return r.loadingIndicator.render})(),N=(P,Be)=>Be==null?!1:typeof Be=="string"?(P.textContent=Be,!0):(P.appendChild(Be),!0),q=new Set,B=new Set,xe=o.some(P=>P.renderAskUserQuestion),me=[],te=[],Ee=r.enableComponentStreaming!==!1,$e=o.some(P=>P.renderApproval)&&r.approval!==!1,Te=[];if(m.forEach(P=>{var Ye,It,un,ur,er,Do,Oo,bs,ys,Xt,No,bo,yo,Kr,Fo,wr;q.add(P.id);let Be=xe&&Jr(P),Ne=$e&&P.variant==="approval"&&!!P.approval,he=!Be&&P.role==="assistant"&&!P.variant&&Ee&&Yi(P);if(!Ne&&yr.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),yr.delete(P.id)}if(!he&&Ir.has(P.id)){let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime"),Ir.delete(P.id)}let Ft=Jr(P)?`:${(Ye=P.agentMetadata)!=null&&Ye.askUserQuestionAnswered?"a":"u"}:${(It=P.agentMetadata)!=null&&It.askUserQuestionAnswers?Object.keys(P.agentMetadata.askUserQuestionAnswers).length:0}`:"",Ot=Pm(P,Ns)+Ft,Jt=Be||Ne||he?null:Rm(Ur,P.id,Ot);if(Jt){x.appendChild(Jt.cloneNode(!0)),Jr(P)&&((un=P.toolCall)!=null&&un.id)&&((ur=P.agentMetadata)==null?void 0:ur.awaitingLocalTool)===!0&&!((er=P.agentMetadata)!=null&&er.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Ct=null,zt=o.find(rt=>!!(P.variant==="reasoning"&&rt.renderReasoning||P.variant==="tool"&&rt.renderToolCall||!P.variant&&rt.renderMessage)),Zn=(Do=r.layout)==null?void 0:Do.messages;if(Jr(P)&&((Oo=P.agentMetadata)==null?void 0:Oo.askUserQuestionAnswered)===!0){jr.delete(P.id);let rt=c.querySelector(`#wrapper-${P.id}`);rt==null||rt.removeAttribute("data-preserve-runtime");return}if(ia(P)&&((ys=(bs=r.features)==null?void 0:bs.suggestReplies)==null?void 0:ys.enabled)!==!1)return;if(Jr(P)&&((No=(Xt=r.features)==null?void 0:Xt.askUserQuestion)==null?void 0:No.enabled)!==!1){let rt=o.find(fn=>typeof fn.renderAskUserQuestion=="function");if(rt&&Lt.current){let fn=jr.get(P.id),Ut=fn!==Ot,_t=null;if(Ut){let{payload:kt,complete:En}=Qr(P),Wn=P.id,Br=()=>{var vn;return(vn=Lt.current)==null?void 0:vn.getMessages().find(Hn=>Hn.id===Wn)};_t=rt.renderAskUserQuestion({message:P,payload:kt,complete:En,resolve:vn=>{var Bn;let Hn=Br();Hn&&((Bn=Lt.current)==null||Bn.resolveAskUserQuestion(Hn,vn))},dismiss:()=>{var Hn,Bn,_o;let vn=Br();(Hn=vn==null?void 0:vn.agentMetadata)!=null&&Hn.awaitingLocalTool&&((Bn=Lt.current)==null||Bn.markAskUserQuestionResolved(vn),(_o=Lt.current)==null||_o.resolveAskUserQuestion(vn,"(dismissed)"))},config:r})}let bt=fn!=null;if(Ut&&_t===null&&!bt){((bo=P.agentMetadata)==null?void 0:bo.awaitingLocalTool)===!0&&!((yo=P.agentMetadata)!=null&&yo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-ask-plugin-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),x.appendChild(Yt),me.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}else{((Kr=P.agentMetadata)==null?void 0:Kr.awaitingLocalTool)===!0&&!((Fo=P.agentMetadata)!=null&&Fo.askUserQuestionAnswered)&&(B.add(P.toolCall.id),As(P,r,De.composerOverlay));return}}else if(Ne){let rt=o.find(bt=>typeof bt.renderApproval=="function"),Ut=yr.get(P.id)!==Ot,_t=null;if(Ut&&(rt!=null&&rt.renderApproval)){let bt=P.id,Yt=(kt,En)=>{var Br,vn,Hn;let Wn=(Br=Lt.current)==null?void 0:Br.getMessages().find(Bn=>Bn.id===bt);Wn!=null&&Wn.approval&&(Wn.approval.toolType==="webmcp"?(vn=Lt.current)==null||vn.resolveWebMcpApproval(Wn.id,kt):(Hn=Lt.current)==null||Hn.resolveApproval(Wn.approval,kt,En))};_t=rt.renderApproval({message:P,defaultRenderer:()=>zi(P,r),config:r,approve:kt=>Yt("approved",kt),deny:kt=>Yt("denied",kt)})}if(Ut&&_t===null){let bt=c.querySelector(`#wrapper-${P.id}`);bt==null||bt.removeAttribute("data-preserve-runtime"),yr.delete(P.id),Ct=zi(P,r)}else{let bt=document.createElement("div");bt.className="persona-flex",bt.id=`wrapper-${P.id}`,bt.setAttribute("data-wrapper-id",P.id),bt.setAttribute("data-approval-plugin-stub","true"),bt.setAttribute("data-preserve-runtime","true"),x.appendChild(bt),Te.push({messageId:P.id,fingerprint:Ot,bubble:_t});return}}else if(zt)if(P.variant==="reasoning"&&P.reasoning&&zt.renderReasoning){if(!ze)return;Ct=zt.renderReasoning({message:P,defaultRenderer:()=>Jl(P,r),config:r})}else if(P.variant==="tool"&&P.toolCall&&zt.renderToolCall){if(!Ae)return;Ct=zt.renderToolCall({message:P,defaultRenderer:()=>Ql(P,r),config:r})}else zt.renderMessage&&(Ct=zt.renderMessage({message:P,defaultRenderer:()=>{let rt=Rs(P,b,Zn,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r});return P.role!=="user"&&ec(rt,P,r,$),rt},config:r}));if(!Ct&&he){let rt=Zi(P);if(rt){let fn=Ir.get(P.id),Ut=fn!==Ot,_t=r.wrapComponentDirectiveInBubble!==!1,bt=null;if(Ut){let Yt=Xi(rt,{config:r,message:P,transform:b});if(Yt)if(_t){let kt=document.createElement("div");if(kt.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(" "),kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-mb-3 persona-text-sm persona-leading-relaxed",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}else{let kt=document.createElement("div");if(kt.className="persona-flex persona-flex-col persona-w-full persona-max-w-full persona-gap-3 persona-items-stretch",kt.id=`bubble-${P.id}`,kt.setAttribute("data-message-id",P.id),kt.setAttribute("data-persona-component-directive","true"),P.content&&P.content.trim()){let En=document.createElement("div");En.className="persona-text-sm persona-leading-relaxed persona-text-persona-primary persona-w-full",En.innerHTML=b({text:P.content,message:P,streaming:!!P.streaming,raw:P.rawContent}),kt.appendChild(En)}kt.appendChild(Yt),bt=kt}}if(bt||fn!=null){let Yt=document.createElement("div");Yt.className="persona-flex",Yt.id=`wrapper-${P.id}`,Yt.setAttribute("data-wrapper-id",P.id),Yt.setAttribute("data-component-directive-stub","true"),Yt.setAttribute("data-preserve-runtime","true"),_t||Yt.classList.add("persona-w-full"),x.appendChild(Yt),te.push({messageId:P.id,fingerprint:Ot,bubble:bt});return}}}if(!Ct)if(P.variant==="reasoning"&&P.reasoning){if(!ze)return;Ct=Jl(P,r)}else if(P.variant==="tool"&&P.toolCall){if(!Ae)return;Ct=Ql(P,r)}else if(P.variant==="approval"&&P.approval){if(r.approval===!1)return;Ct=zi(P,r)}else{let rt=(wr=r.layout)==null?void 0:wr.messages;rt!=null&&rt.renderUserMessage&&P.role==="user"?Ct=rt.renderUserMessage({message:P,config:r,streaming:!!P.streaming}):rt!=null&&rt.renderAssistantMessage&&P.role==="assistant"?Ct=rt.renderAssistantMessage({message:P,config:r,streaming:!!P.streaming}):Ct=Rs(P,b,rt,r.messageActions,ee,{loadingIndicatorRenderer:D,widgetConfig:r}),P.role!=="user"&&Ct&&ec(Ct,P,r,$)}let ln=document.createElement("div");ln.className="persona-flex",ln.id=`wrapper-${P.id}`,ln.setAttribute("data-wrapper-id",P.id),P.role==="user"&&ln.classList.add("persona-justify-end"),(Ct==null?void 0:Ct.getAttribute("data-persona-component-directive"))==="true"&&ln.classList.add("persona-w-full"),ln.appendChild(Ct),Wm(Ur,P.id,Ot,ln),x.appendChild(ln)}),De.composerOverlay&&De.composerOverlay.querySelectorAll("[data-persona-ask-sheet-for]").forEach(Be=>{let Ne=Be.getAttribute("data-persona-ask-sheet-for");Ne&&!B.has(Ne)&&wo(De.composerOverlay,Ne)}),(Ie=(pt=r.features)==null?void 0:pt.toolCallDisplay)!=null&&Ie.grouped){let P=[],Be=[];m.forEach(Ne=>{if(Ne.variant==="tool"&&Ne.toolCall&&Ae){Be.push(Ne);return}Be.length>1&&P.push(Be),Be=[]}),Be.length>1&&P.push(Be),P.forEach((Ne,he)=>{var Ye,It;let Ft=Ne.map(un=>Array.from(x.children).find(ur=>ur instanceof HTMLElement&&ur.getAttribute("data-wrapper-id")===un.id)).filter(un=>!!un);if(Ft.length<2)return;let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id=`wrapper-tool-group-${he}-${Ne[0].id}`,Ot.setAttribute("data-wrapper-id",`tool-group-${he}-${Ne[0].id}`);let Jt=document.createElement("div");Jt.className="persona-tool-group persona-flex persona-w-full persona-flex-col persona-gap-2",Jt.setAttribute("data-persona-tool-group","true");let Ct=document.createElement("div");Ct.className="persona-tool-group-summary persona-text-xs persona-text-persona-muted";let zt=`Called ${Ne.length} tools`,Zn=(It=(Ye=r.toolCall)==null?void 0:Ye.renderGroupedSummary)==null?void 0:It.call(Ye,{messages:Ne,toolCalls:Ne.map(un=>un.toolCall).filter(un=>!!un),defaultSummary:zt,config:r});N(Ct,Zn)||(Ct.textContent=zt);let ln=document.createElement("div");ln.className="persona-tool-group-stack persona-flex persona-flex-col",Jt.append(Ct,ln),Ot.appendChild(Jt),Ft[0].before(Ot),Ft.forEach((un,ur)=>{let er=document.createElement("div");er.className="persona-tool-group-item persona-relative",er.setAttribute("data-persona-tool-group-item","true"),ur<Ft.length-1&&er.setAttribute("data-persona-tool-group-connector","true"),er.appendChild(un),ln.appendChild(er)})})}Hm(Ur,q);let st=m.some(P=>P.role==="assistant"&&P.streaming),Ke=m[m.length-1],dt=(Ke==null?void 0:Ke.role)==="assistant"&&!Ke.streaming&&Ke.variant!=="approval";if(Pr&&m.some(P=>P.role==="user")&&!st&&!dt){let P={config:r,streaming:!0,location:"standalone",defaultRenderer:ts},Be=o.find(he=>he.renderLoadingIndicator),Ne=null;if(Be!=null&&Be.renderLoadingIndicator&&(Ne=Be.renderLoadingIndicator(P)),Ne===null&&((Pe=r.loadingIndicator)!=null&&Pe.render)&&(Ne=r.loadingIndicator.render(P)),Ne===null&&(Ne=ts()),Ne){let he=document.createElement("div"),Ft=((qe=r.loadingIndicator)==null?void 0:qe.showBubble)!==!1;he.className=Ft?["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(" "),he.setAttribute("data-typing-indicator","true"),he.style.borderColor="var(--persona-message-assistant-border, var(--persona-border, #e5e7eb))",he.appendChild(Ne);let Ot=document.createElement("div");Ot.className="persona-flex",Ot.id="wrapper-typing-indicator",Ot.setAttribute("data-wrapper-id","typing-indicator"),Ot.appendChild(he),x.appendChild(Ot)}}if(!Pr&&m.length>0){let P=m[m.length-1],Be={config:r,lastMessage:P,messageCount:m.length},Ne=o.find(Ft=>Ft.renderIdleIndicator),he=null;if(Ne!=null&&Ne.renderIdleIndicator&&(he=Ne.renderIdleIndicator(Be)),he===null&&((Xe=r.loadingIndicator)!=null&&Xe.renderIdle)&&(he=r.loadingIndicator.renderIdle(Be)),he){let Ft=document.createElement("div"),Ot=((wt=r.loadingIndicator)==null?void 0:wt.showBubble)!==!1;Ft.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-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(" "),Ft.setAttribute("data-idle-indicator","true"),Ft.appendChild(he);let Jt=document.createElement("div");Jt.className="persona-flex",Jt.id="wrapper-idle-indicator",Jt.setAttribute("data-wrapper-id","idle-indicator"),Jt.appendChild(Ft),x.appendChild(Jt)}}if(Ei(c,x),me.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of me){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),jr.set(P,Be))}if(jr.size>0)for(let P of jr.keys())q.has(P)||jr.delete(P);if(te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),Ir.set(P,Be))}if(Ir.size>0)for(let P of Ir.keys())q.has(P)||Ir.delete(P);if(Te.length>0)for(let{messageId:P,fingerprint:Be,bubble:Ne}of Te){let he=c.querySelector(`#wrapper-${P}`);he&&Ne!==null&&(he.replaceChildren(Ne),he.setAttribute("data-bubble-fp",Be),yr.set(P,Be))}if(yr.size>0)for(let P of yr.keys())q.has(P)||yr.delete(P)},po=null,qa=()=>{var b;if(po)return;let c=x=>{let E=x.composedPath();E.includes(ve)||Je&&E.includes(Je)||Dt(!1,"user")};po=c,((b=e.ownerDocument)!=null?b:document).addEventListener("pointerdown",c,!0)},Gs=()=>{var m;if(!po)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("pointerdown",po,!0),po=null};ft.push(()=>Gs());let uo=null,za=()=>{var b;if(uo)return;let c=x=>{x.key==="Escape"&&(x.isComposing||Dt(!1,"user"))};uo=c,((b=e.ownerDocument)!=null?b:document).addEventListener("keydown",c,!0)},Js=()=>{var m;if(!uo)return;((m=e.ownerDocument)!=null?m:document).removeEventListener("keydown",uo,!0),uo=null};ft.push(()=>Js());let mo=!1,Qs=new Set,Va=()=>{var m,b,x,E;let c=(x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.peek)==null?void 0:x.streamAnimation;return c||((E=r.features)==null?void 0:E.streamAnimation)},Vr=()=>{var dt,pt,Ie,Pe;if(!_())return;let c=De.peekBanner,m=De.peekTextNode;if(!c||!m)return;if(M){c.classList.remove("persona-pill-peek--visible");return}let b=(dt=$==null?void 0:$.getMessages())!=null?dt:[],x;for(let qe=b.length-1;qe>=0;qe--){let Xe=b[qe];if(Xe.role==="assistant"&&Xe.content){x=Xe;break}}if(!x){c.classList.remove("persona-pill-peek--visible");return}let E=x.content,D=!!x.streaming,N=Va(),q=Ii(N),B=q.type!=="none"?xa(q.type,N==null?void 0:N.plugins):null,xe=((pt=B==null?void 0:B.isAnimating)==null?void 0:pt.call(B,x))===!0,me=B!==null&&(D||xe);me&&B&&!Qs.has(B.name)&&(Fl(B,e),Qs.add(B.name));let te=me&&(B!=null&&B.containerClass)?B.containerClass:null,Ee=(Ie=m.dataset.personaPeekStreamClass)!=null?Ie:null;Ee&&Ee!==te&&(m.classList.remove(Ee),delete m.dataset.personaPeekStreamClass),te&&Ee!==te&&(m.classList.add(te),m.dataset.personaPeekStreamClass=te),me?(m.style.setProperty("--persona-stream-step",`${q.speed}ms`),m.style.setProperty("--persona-stream-duration",`${q.duration}ms`)):(m.style.removeProperty("--persona-stream-step"),m.style.removeProperty("--persona-stream-duration"));let $e=me?Ri(E,q.buffer,B,x,D):E;if(me&&q.placeholder==="skeleton"&&D&&(!$e||!$e.trim())){let qe=document.createElement("div"),Xe=wa();Xe.classList.add("persona-pill-peek__skeleton"),qe.appendChild(Xe),Ei(m,qe)}else{let qe=Math.max(0,$e.length-100),Xe=$e.length>100?$e.slice(-100):$e,wt=qo(Xe);if(!me||!B){let P=$e.length>100?`\u2026${Xe}`:Xe;m.textContent!==P&&(m.textContent=P)}else{let P=wt;(B.wrap==="char"||B.wrap==="word")&&(P=va(wt,B.wrap,`peek-${x.id}`,{skipTags:B.skipTags,startIndex:qe}));let Be=document.createElement("div");if(Be.innerHTML=P,B.useCaret&&Xe.length>0){let Ne=Wi(),he=Be.querySelectorAll(".persona-stream-char, .persona-stream-word"),Ft=he[he.length-1];Ft!=null&&Ft.parentNode?Ft.parentNode.insertBefore(Ne,Ft.nextSibling):Be.appendChild(Ne)}Ei(m,Be),(Pe=B.onAfterRender)==null||Pe.call(B,{container:m,bubble:c,messageId:x.id,message:x,speed:q.speed,duration:q.duration})}}let Ke=Pr||mo;c.classList.toggle("persona-pill-peek--visible",Ke)};if(_()){let c=De.peekBanner;if(c){let x=E=>{E.preventDefault(),E.stopPropagation(),Dt(!0,"user")};c.addEventListener("pointerdown",x),ft.push(()=>{c.removeEventListener("pointerdown",x)})}let m=()=>{mo||(mo=!0,Vr())},b=()=>{mo&&(mo=!1,Vr())};fe.addEventListener("pointerenter",m),fe.addEventListener("pointerleave",b),ft.push(()=>{fe.removeEventListener("pointerenter",m),fe.removeEventListener("pointerleave",b)}),Je&&(Je.addEventListener("pointerenter",m),Je.addEventListener("pointerleave",b),ft.push(()=>{Je.removeEventListener("pointerenter",m),Je.removeEventListener("pointerleave",b)}))}let Ka=c=>{var Ee,$e,Te,st,Ke,dt,pt,Ie;let m=($e=(Ee=r.launcher)==null?void 0:Ee.composerBar)!=null?$e:{},b=(Te=m.expandedSize)!=null?Te:"anchored",x=(st=m.bottomOffset)!=null?st:"16px",E=m.collapsedMaxWidth,D=(Ke=m.expandedMaxWidth)!=null?Ke:"880px",N=(dt=m.expandedTopOffset)!=null?dt:"5vh",q=(pt=m.modalMaxWidth)!=null?pt:"880px",B=(Ie=m.modalMaxHeight)!=null?Ie:"min(90vh, 800px)",xe="calc(100vw - 32px)",me="var(--persona-pill-area-height, 80px)",te=ve.style;if(te.left="",te.right="",te.top="",te.bottom="",te.transform="",te.width="",te.maxWidth="",te.height="",te.maxHeight="",Je){let Pe=Je.style;Pe.bottom=x,Pe.width=E!=null?E:""}if(c&&b!=="fullscreen"){if(b==="modal"){te.top="50%",te.left="50%",te.transform="translate(-50%, -50%)",te.bottom="auto",te.right="auto",te.width=q,te.maxWidth=xe,te.maxHeight=B,te.height=B;return}te.left="50%",te.transform="translateX(-50%)",te.bottom=`calc(${x} + ${me})`,te.top=N,te.width=D,te.maxWidth=xe}},go=()=>{var B,xe,me,te,Ee,$e,Te,st;if(!F())return;if(_()){let dt=(me=((xe=(B=r.launcher)==null?void 0:B.composerBar)!=null?xe:{}).expandedSize)!=null?me:"anchored",pt=M?"expanded":"collapsed";ve.dataset.state=pt,ve.dataset.expandedSize=dt,Je&&(Je.dataset.state=pt,Je.dataset.expandedSize=dt),ve.style.removeProperty("display"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0","persona-scale-100","persona-opacity-100"),Ka(M),V.style.display=M?"flex":"none",hr(),M?(qa(),za()):(Gs(),Js()),Vr();return}let c=mn(r),m=(te=e.ownerDocument.defaultView)!=null?te:window,b=($e=(Ee=r.launcher)==null?void 0:Ee.mobileBreakpoint)!=null?$e:640,x=(st=(Te=r.launcher)==null?void 0:Te.mobileFullscreen)!=null?st:!0,E=m.innerWidth<=b,D=x&&E&&S,N=rr(r).reveal;M?(ve.style.removeProperty("display"),ve.style.display=c?"flex":"",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-95","persona-opacity-0"),fe.classList.add("persona-scale-100","persona-opacity-100"),on?on.element.style.display="none":sn&&(sn.style.display="none")):(c?c&&(N==="overlay"||N==="push")&&!D?(ve.style.removeProperty("display"),ve.style.display="flex",ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.setProperty("display","none","important"),ve.classList.remove("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100","persona-scale-95","persona-opacity-0")):(ve.style.display="",ve.classList.add("persona-pointer-events-none","persona-opacity-0"),fe.classList.remove("persona-scale-100","persona-opacity-100"),fe.classList.add("persona-scale-95","persona-opacity-0")),on?on.element.style.display=c?"none":"":sn&&(sn.style.display=c?"none":""))},Dt=(c,m="user")=>{var D,N;if(!F()||M===c)return;let b=M;M=c,go();let x=(()=>{var Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt;let q=(st=(Te=r.launcher)==null?void 0:Te.sidebarMode)!=null?st:!1,B=(Ke=e.ownerDocument.defaultView)!=null?Ke:window,xe=(pt=(dt=r.launcher)==null?void 0:dt.mobileFullscreen)!=null?pt:!0,me=(Pe=(Ie=r.launcher)==null?void 0:Ie.mobileBreakpoint)!=null?Pe:640,te=B.innerWidth<=me,Ee=mn(r)&&xe&&te,$e=_()&&((wt=(Xe=(qe=r.launcher)==null?void 0:qe.composerBar)==null?void 0:Xe.expandedSize)!=null?wt:"fullscreen")==="fullscreen";return q||xe&&te&&S||Ee||$e})();if(M&&x){if(!nn){let q=e.getRootNode(),B=q instanceof ShadowRoot?q.host:e.closest(".persona-host");B&&(nn=_l(B,(N=(D=r.launcher)==null?void 0:D.zIndex)!=null?N:Ln))}rn||(rn=$l(e.ownerDocument))}else M||(nn==null||nn(),nn=null,rn==null||rn(),rn=null);M&&(Ys(),mt()==="follow"?Hr(!0):Vs());let E={open:M,source:m,timestamp:Date.now()};M&&!b?s.emit("widget:opened",E):!M&&b&&s.emit("widget:closed",E),s.emit("widget:state",{open:M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()})},ms=c=>{Zt(c?"stop":"send"),G&&(G.disabled=c),br.buttons.forEach(m=>{m.disabled=c}),Ue.dataset.personaComposerStreaming=c?"true":"false",Ue.querySelectorAll("[data-persona-composer-disable-when-streaming]").forEach(m=>{(m instanceof HTMLButtonElement||m instanceof HTMLInputElement||m instanceof HTMLTextAreaElement||m instanceof HTMLSelectElement)&&(m.disabled=c)})},gs=()=>{yt.active||ne&&ne.focus()};s.on("widget:opened",()=>{r.autoFocusInput&&setTimeout(()=>gs(),200)});let Bo=()=>{var b,x,E,D,N,q,B,xe,me,te,Ee;sr.textContent=(x=(b=r.copy)==null?void 0:b.welcomeTitle)!=null?x:"Hello \u{1F44B}",Er.textContent=(D=(E=r.copy)==null?void 0:E.welcomeSubtitle)!=null?D:"Ask anything about your account or products.",ne.placeholder=(q=(N=r.copy)==null?void 0:N.inputPlaceholder)!=null?q:"How can I help...";let c=ue.querySelector("[data-persona-intro-card]");if(c){let $e=((B=r.copy)==null?void 0:B.showWelcomeCard)!==!1;c.style.display=$e?"":"none",$e?(ue.classList.remove("persona-gap-3"),ue.classList.add("persona-gap-6")):(ue.classList.remove("persona-gap-6"),ue.classList.add("persona-gap-3"))}!((me=(xe=r.sendButton)==null?void 0:xe.useIcon)!=null&&me)&&!($!=null&&$.isStreaming())&&(Ve.textContent=(Ee=(te=r.copy)==null?void 0:te.sendButtonLabel)!=null?Ee:"Send"),ne.style.fontFamily='var(--persona-input-font-family, var(--persona-font-family, -apple-system, BlinkMacSystemFont, "Segoe UI", "Helvetica Neue", Arial, sans-serif))',ne.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 je=null,A=()=>{je==null&&(je=setInterval(()=>{let c=ot.querySelectorAll("[data-tool-elapsed]");if(c.length===0){clearInterval(je),je=null;return}let m=Date.now();c.forEach(b=>{let x=Number(b.getAttribute("data-tool-elapsed"));x&&(b.textContent=ai(m-x))})},100))};if($=new Es(r,{onMessagesChanged(c){var x;Ho(ot,c,ke),A(),as(c),Hr(!Pr),ja(c);let m=[...c].reverse().find(E=>E.role==="user");c.length===0&&Wo(),!is||Ro?(is=!0,ls=(x=m==null?void 0:m.id)!=null?x:null):m&&m.id!==ls&&(ls=m.id,Ua(m.id));let b=yt.lastUserMessageId;m&&m.id!==b&&(yt.lastUserMessageId=m.id,s.emit("user:message",m)),yt.lastUserMessageWasVoice=!!(m!=null&&m.viaVoice),ps(c),Vr()},onStatusChanged(c){var x;let m=(x=r.statusIndicator)!=null?x:{};Ze(cn,(E=>{var D,N,q,B;return E==="idle"?(D=m.idleText)!=null?D:kn.idle:E==="connecting"?(N=m.connectingText)!=null?N:kn.connecting:E==="connected"?(q=m.connectedText)!=null?q:kn.connected:E==="error"?(B=m.errorText)!=null?B:kn.error:kn[E]})(c),m,c)},onStreamingChanged(c){Pr=c,ms(c),$&&Ho(ot,$.getMessages(),ke),c||Hr(!0),Vr()},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":fo(),mf();break;case"speaking":fo(),gf();break;default:c==="idle"&&$.isBargeInActive()?(fo(),Xs(),G==null||G.setAttribute("aria-label","End voice session")):(yt.active=!1,fo(),dr("system"),_n());break}},onArtifactsState(c){Vn=c,Jn(),ps()}}),Lt.current=$,is=!0,((Ad=(Cd=r.voiceRecognition)==null?void 0:Cd.provider)==null?void 0:Ad.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)}),(ce||r.onSSEEvent)&&$.setSSEEventCallback((c,m)=>{var b;(b=r.onSSEEvent)==null||b.call(r,c,m),ge==null||ge.processEvent(c,m),ce==null||ce.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=rc(c.metadata),w.syncFromMetadata()),(m=c.messages)!=null&&m.length){Ro=!0;try{$.hydrateMessages(c.messages)}finally{Ro=!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 U=()=>{var m,b,x;!_()||M||!((x=(b=(m=r.launcher)==null?void 0:m.composerBar)==null?void 0:b.expandOnSubmit)==null||x)||Dt(!0,"auto")},L=c=>{var E;if(c.preventDefault(),$.isStreaming()){$.cancel(),ge==null||ge.reset(),K==null||K.update();return}let m=ne.value.trim(),b=(E=At==null?void 0:At.hasAttachments())!=null?E:!1;if(!m&&!b)return;U();let x;b&&(x=[],x.push(...At.getContentParts()),m&&x.push(pa(m))),ne.value="",ne.style.height="auto",Me(),$.sendMessage(m,{contentParts:x}),b&&At.clearAttachments()},Z=()=>{var c;return((c=r.features)==null?void 0:c.composerHistory)!==!1},se={...Mi},J=!1,Me=()=>{se={...Mi}},Fe=()=>$.getMessages().filter(c=>c.role==="user").map(c=>{var m;return(m=c.content)!=null?m:""}).filter(c=>c.length>0),ct=c=>{if(!ne)return;J=!0,ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),J=!1;let m=ne.value.length;ne.setSelectionRange(m,m)},tt=()=>{J||Me()},Wt=c=>{if(ne){if(Z()&&(c.key==="ArrowUp"||c.key==="ArrowDown")&&!c.shiftKey&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&!c.isComposing){let m=ne.selectionStart===0&&ne.selectionEnd===0,b=Lm({direction:c.key==="ArrowUp"?"up":"down",history:Fe(),currentValue:ne.value,atStart:m,state:se});if(se=b.state,b.handled){c.preventDefault(),b.value!==void 0&&ct(b.value);return}}if(c.key==="Enter"&&!c.shiftKey){if($.isStreaming()){c.preventDefault();return}Me(),c.preventDefault(),Ve.click()}}},$t=c=>{c.key!=="Escape"||c.isComposing||$.isStreaming()&&c.composedPath().includes(V)&&($.cancel(),ge==null||ge.reset(),K==null||K.update(),Me(),c.preventDefault(),c.stopImmediatePropagation())},gn=async c=>{var b;if(((b=r.attachments)==null?void 0:b.enabled)!==!0||!At)return;let m=jb(c.clipboardData);m.length!==0&&(c.preventDefault(),await At.handleFiles(m))},it=null,ht=!1,en=null,Ge=null,Cn=()=>typeof window=="undefined"?null:window.webkitSpeechRecognition||window.SpeechRecognition||null,Qt=(c="user")=>{var D,N,q,B,xe,me,te;if(ht||$.isStreaming())return;let m=Cn();if(!m)return;it=new m;let x=(N=((D=r.voiceRecognition)!=null?D:{}).pauseDuration)!=null?N:2e3;it.continuous=!0,it.interimResults=!0,it.lang="en-US";let E=ne.value;it.onresult=Ee=>{let $e="",Te="";for(let Ke=0;Ke<Ee.results.length;Ke++){let dt=Ee.results[Ke],pt=dt[0].transcript;dt.isFinal?$e+=pt+" ":Te=pt}let st=E+$e+Te;ne.value=st,en&&clearTimeout(en),($e||Te)&&(en=window.setTimeout(()=>{let Ke=ne.value.trim();Ke&&it&&ht&&(xn(),ne.value="",ne.style.height="auto",$.sendMessage(Ke,{viaVoice:!0}))},x))},it.onerror=Ee=>{Ee.error!=="no-speech"&&xn()},it.onend=()=>{if(ht){let Ee=ne.value.trim();Ee&&Ee!==E.trim()&&(ne.value="",ne.style.height="auto",$.sendMessage(Ee,{viaVoice:!0})),xn()}};try{if(it.start(),ht=!0,yt.active=!0,c!=="system"&&(yt.manuallyDeactivated=!1),dr(c),_n(),G){let Ee=(q=r.voiceRecognition)!=null?q:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(B=Ee.iconName)!=null?B:"mic",iconSize:parseFloat((te=(me=Ee.iconSize)!=null?me:(xe=r.sendButton)==null?void 0:xe.size)!=null?te:"40")||24};let $e=Ee.recordingBackgroundColor,Te=Ee.recordingIconColor,st=Ee.recordingBorderColor;if(G.classList.add("persona-voice-recording"),G.style.backgroundColor=$e!=null?$e:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=Te!=null?Te:"var(--persona-voice-recording-indicator, #ffffff)",Te){let Ke=G.querySelector("svg");Ke&&Ke.setAttribute("stroke",Te)}st&&(G.style.borderColor=st),G.setAttribute("aria-label","Stop voice recognition")}}catch{xn("system")}},xn=(c="user")=>{if(ht){if(ht=!1,en&&(clearTimeout(en),en=null),it){try{it.stop()}catch{}it=null}if(yt.active=!1,dr(c),_n(),G){if(G.classList.remove("persona-voice-recording"),Ge){G.style.backgroundColor=Ge.backgroundColor,G.style.color=Ge.color,G.style.borderColor=Ge.borderColor;let m=G.querySelector("svg");m&&m.setAttribute("stroke",Ge.color||"currentColor"),Ge=null}G.setAttribute("aria-label","Start voice recognition")}}},uf=(c,m)=>{var dt,pt,Ie,Pe,qe,Xe,wt,P;let b=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),x=((dt=c==null?void 0:c.provider)==null?void 0:dt.type)==="runtype";if(!(b||x))return null;let D=h("div","persona-send-button-wrapper"),N=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer");N.type="button",N.setAttribute("aria-label","Start voice recognition");let q=(pt=c==null?void 0:c.iconName)!=null?pt:"mic",B=(Ie=m==null?void 0:m.size)!=null?Ie:"40px",xe=(Pe=c==null?void 0:c.iconSize)!=null?Pe:B,me=parseFloat(xe)||24,te=(qe=c==null?void 0:c.backgroundColor)!=null?qe:m==null?void 0:m.backgroundColor,Ee=(Xe=c==null?void 0:c.iconColor)!=null?Xe:m==null?void 0:m.textColor;N.style.width=xe,N.style.height=xe,N.style.minWidth=xe,N.style.minHeight=xe,N.style.fontSize="18px",N.style.lineHeight="1",Ee?N.style.color=Ee:N.style.color="var(--persona-text, #111827)";let Te=Ce(q,me,Ee||"currentColor",1.5);Te?N.appendChild(Te):N.textContent="\u{1F3A4}",te?N.style.backgroundColor=te:N.style.backgroundColor="",c!=null&&c.borderWidth&&(N.style.borderWidth=c.borderWidth,N.style.borderStyle="solid"),c!=null&&c.borderColor&&(N.style.borderColor=c.borderColor),c!=null&&c.paddingX&&(N.style.paddingLeft=c.paddingX,N.style.paddingRight=c.paddingX),c!=null&&c.paddingY&&(N.style.paddingTop=c.paddingY,N.style.paddingBottom=c.paddingY),D.appendChild(N);let st=(wt=c==null?void 0:c.tooltipText)!=null?wt:"Start voice recognition";if(((P=c==null?void 0:c.showTooltip)!=null?P:!1)&&st){let Be=h("div","persona-send-button-tooltip");Be.textContent=st,D.appendChild(Be)}return{micButton:N,micButtonWrapper:D}},ul=()=>{var m,b,x,E,D;if(!G||Ge)return;let c=(m=r.voiceRecognition)!=null?m:{};Ge={backgroundColor:G.style.backgroundColor,color:G.style.color,borderColor:G.style.borderColor,iconName:(b=c.iconName)!=null?b:"mic",iconSize:parseFloat((D=(E=c.iconSize)!=null?E:(x=r.sendButton)==null?void 0:x.size)!=null?D:"40")||24}},ml=(c,m)=>{var D,N,q,B,xe;if(!G)return;let b=G.querySelector("svg");b&&b.remove();let x=(xe=Ge==null?void 0:Ge.iconSize)!=null?xe:parseFloat((B=(q=(D=r.voiceRecognition)==null?void 0:D.iconSize)!=null?q:(N=r.sendButton)==null?void 0:N.size)!=null?B:"40")||24,E=Ce(c,x,m,1.5);E&&G.appendChild(E)},Ga=()=>{G&&G.classList.remove("persona-voice-recording","persona-voice-processing","persona-voice-speaking")},Xs=()=>{var E;if(!G)return;ul();let c=(E=r.voiceRecognition)!=null?E:{},m=c.recordingBackgroundColor,b=c.recordingIconColor,x=c.recordingBorderColor;if(Ga(),G.classList.add("persona-voice-recording"),G.style.backgroundColor=m!=null?m:"var(--persona-voice-recording-bg, #ef4444)",G.style.color=b!=null?b:"var(--persona-voice-recording-indicator, #ffffff)",b){let D=G.querySelector("svg");D&&D.setAttribute("stroke",b)}x&&(G.style.borderColor=x),G.setAttribute("aria-label","Stop voice recognition")},mf=()=>{var q,B,xe,me,te,Ee,$e,Te;if(!G)return;ul();let c=(q=r.voiceRecognition)!=null?q:{},m=$.getVoiceInterruptionMode(),b=(B=c.processingIconName)!=null?B:"loader",x=(me=(xe=c.processingIconColor)!=null?xe:Ge==null?void 0:Ge.color)!=null?me:"",E=(Ee=(te=c.processingBackgroundColor)!=null?te:Ge==null?void 0:Ge.backgroundColor)!=null?Ee:"",D=(Te=($e=c.processingBorderColor)!=null?$e:Ge==null?void 0:Ge.borderColor)!=null?Te:"";Ga(),G.classList.add("persona-voice-processing"),G.style.backgroundColor=E,G.style.borderColor=D;let N=x||"currentColor";G.style.color=N,ml(b,N),G.setAttribute("aria-label","Processing voice input"),m==="none"&&(G.style.cursor="default")},gf=()=>{var xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe;if(!G)return;ul();let c=(xe=r.voiceRecognition)!=null?xe:{},m=$.getVoiceInterruptionMode(),b=m==="cancel"?"square":m==="barge-in"?"mic":"volume-2",x=(me=c.speakingIconName)!=null?me:b,E=(Te=c.speakingIconColor)!=null?Te:m==="barge-in"?(Ee=(te=c.recordingIconColor)!=null?te:Ge==null?void 0:Ge.color)!=null?Ee:"":($e=Ge==null?void 0:Ge.color)!=null?$e:"",D=(dt=c.speakingBackgroundColor)!=null?dt:m==="barge-in"?(st=c.recordingBackgroundColor)!=null?st:"var(--persona-voice-recording-bg, #ef4444)":(Ke=Ge==null?void 0:Ge.backgroundColor)!=null?Ke:"",N=(Pe=c.speakingBorderColor)!=null?Pe:m==="barge-in"?(pt=c.recordingBorderColor)!=null?pt:"":(Ie=Ge==null?void 0:Ge.borderColor)!=null?Ie:"";Ga(),G.classList.add("persona-voice-speaking"),G.style.backgroundColor=D,G.style.borderColor=N;let q=E||"currentColor";G.style.color=q,ml(x,q);let B=m==="cancel"?"Stop playback and re-record":m==="barge-in"?"Speak to interrupt":"Agent is speaking";G.setAttribute("aria-label",B),m==="none"&&(G.style.cursor="default"),m==="barge-in"&&G.classList.add("persona-voice-recording")},fo=()=>{var c,m,b;G&&(Ga(),Ge&&(G.style.backgroundColor=(c=Ge.backgroundColor)!=null?c:"",G.style.color=(m=Ge.color)!=null?m:"",G.style.borderColor=(b=Ge.borderColor)!=null?b:"",ml(Ge.iconName,Ge.color||"currentColor"),Ge=null),G.style.cursor="",G.setAttribute("aria-label","Start voice recognition"))},Ja=()=>{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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()});return}$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),yt.manuallyDeactivated=!$.isVoiceActive(),_n(),dr("user"),$.isVoiceActive()?Xs():fo()});return}if(ht){let b=ne.value.trim();yt.manuallyDeactivated=!0,_n(),xn("user"),b&&(ne.value="",ne.style.height="auto",$.sendMessage(b))}else yt.manuallyDeactivated=!1,_n(),Qt("user")};jn=Ja,G&&(G.addEventListener("click",Ja),ft.push(()=>{var c,m;((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?($.isVoiceActive()&&$.toggleVoice(),fo()):xn("system"),G&&G.removeEventListener("click",Ja)}));let ff=s.on("assistant:complete",()=>{Fs&&(yt.active||yt.manuallyDeactivated||Fs==="assistant"&&!yt.lastUserMessageWasVoice||setTimeout(()=>{var c,m;!yt.active&&!yt.manuallyDeactivated&&(((m=(c=r.voiceRecognition)==null?void 0:c.provider)==null?void 0:m.type)==="runtype"?$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("auto"),$.isVoiceActive()&&Xs()}):Qt("auto"))},600))});ft.push(ff);let hf=s.on("action:resubmit",()=>{setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)});ft.push(hf);let fs=()=>{Dt(!M,"user")},on=null,sn=null;if(S&&!_()){let c=o.find(m=>m.renderLauncher);if(c!=null&&c.renderLauncher){let m=c.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});m&&(sn=m)}sn||(on=Sa(r,fs))}on?e.appendChild(on.element):sn&&e.appendChild(sn),go(),as(),Bo(),ms($.isStreaming()),mt()==="follow"?Hr(!0):Vs(),Oa(),k&&(!S||_()?setTimeout(()=>gs(),0):M&&setTimeout(()=>gs(),200));let Ys=()=>{var B,xe,me,te,Ee,$e,Te,st,Ke,dt,pt,Ie,Pe,qe,Xe,wt,P,Be,Ne,he,Ft,Ot;if(_()){yn(),go();return}let c=mn(r),m=(xe=(B=r.launcher)==null?void 0:B.sidebarMode)!=null?xe:!1,b=c||m||((te=(me=r.launcher)==null?void 0:me.fullHeight)!=null?te:!1),x=(Ee=e.ownerDocument.defaultView)!=null?Ee:window,E=(Te=($e=r.launcher)==null?void 0:$e.mobileFullscreen)!=null?Te:!0,D=(Ke=(st=r.launcher)==null?void 0:st.mobileBreakpoint)!=null?Ke:640,N=x.innerWidth<=D,q=E&&N&&S;try{if(q){hr(),Ao(e,r);return}if(W&&(W=!1,hr(),Ao(e,r)),!S&&!c){fe.style.height="",fe.style.width="";return}if(!m&&!c){let Jt=(pt=(dt=r==null?void 0:r.launcher)==null?void 0:dt.width)!=null?pt:r==null?void 0:r.launcherWidth,Ct=Jt!=null?Jt:nr;fe.style.width=Ct,fe.style.maxWidth=Ct}if(Lr(),!b){let Jt=x.innerHeight,Ct=64,zt=(Pe=(Ie=r.launcher)==null?void 0:Ie.heightOffset)!=null?Pe:0,Zn=Math.max(200,Jt-Ct),ln=Math.min(640,Zn),Ye=Math.max(200,ln-zt);fe.style.height=`${Ye}px`}}finally{if(yn(),go(),M&&S){let Ct=((qe=e.ownerDocument.defaultView)!=null?qe:window).innerWidth<=((wt=(Xe=r.launcher)==null?void 0:Xe.mobileBreakpoint)!=null?wt:640),zt=(Be=(P=r.launcher)==null?void 0:P.sidebarMode)!=null?Be:!1,Zn=(he=(Ne=r.launcher)==null?void 0:Ne.mobileFullscreen)!=null?he:!0,ln=mn(r)&&Zn&&Ct,Ye=zt||Zn&&Ct&&S||ln;if(Ye&&!rn){let It=e.getRootNode(),un=It instanceof ShadowRoot?It.host:e.closest(".persona-host");un&&!nn&&(nn=_l(un,(Ot=(Ft=r.launcher)==null?void 0:Ft.zIndex)!=null?Ot:Ln)),rn=$l(e.ownerDocument)}else Ye||(nn==null||nn(),nn=null,rn==null||rn(),rn=null)}}};Ys();let wc=(Sd=e.ownerDocument.defaultView)!=null?Sd:window;if(wc.addEventListener("resize",Ys),ft.push(()=>wc.removeEventListener("resize",Ys)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{yn()});c.observe(Ue),ft.push(()=>c.disconnect())}Yn=ue.scrollTop;let Cc=Zr(ue),bf=()=>{let c=ue.getRootNode(),m=typeof c.getSelection=="function"?c.getSelection():null;return m!=null?m:ue.ownerDocument.getSelection()},gl=()=>Bm(bf(),ue),Ac=()=>{let c=ue.scrollTop,m=Zr(ue),b=m<Cc;if(Cc=m,mt()!=="follow"){Yn=c,$n();return}let{action:x,nextLastScrollTop:E}=Li({following:Xn.isFollowing(),currentScrollTop:c,lastScrollTop:Yn,nearBottom:Zo(ue,cs),userScrollThreshold:Ba,isAutoScrolling:vr||Io||b,pauseOnUpwardScroll:!0,pauseWhenAwayFromBottom:!1,resumeRequiresDownwardScroll:!0});if(Yn=E,x==="resume"){gl()||Wr();return}x==="pause"&&us()};if(ue.addEventListener("scroll",Ac,{passive:!0}),ft.push(()=>ue.removeEventListener("scroll",Ac)),typeof ResizeObserver!="undefined"){let c=new ResizeObserver(()=>{$a()});c.observe(ot),c.observe(ue),ft.push(()=>c.disconnect())}let Sc=()=>{mt()==="follow"&&Xn.isFollowing()&&gl()&&us()},Tc=ue.ownerDocument;Tc.addEventListener("selectionchange",Sc),ft.push(()=>{Tc.removeEventListener("selectionchange",Sc)});let Ec=c=>{if(mt()!=="follow")return;let m=Pi({following:Xn.isFollowing(),deltaY:c.deltaY,nearBottom:Zo(ue,cs),resumeWhenNearBottom:!0});m==="pause"?us():m==="resume"&&!gl()&&Wr()};ue.addEventListener("wheel",Ec,{passive:!0}),ft.push(()=>ue.removeEventListener("wheel",Ec)),et.addEventListener("click",()=>{Wo(),ue.scrollTop=ue.scrollHeight,Yn=ue.scrollTop,Wr(),Hr(!0),$n()}),ft.push(()=>et.remove()),ft.push(()=>{$s(),Wo()});let Mc=()=>{H&&(cr&&(H.removeEventListener("click",cr),cr=null),F()?(H.style.display="",cr=()=>{Dt(!1,"user")},H.addEventListener("click",cr)):H.style.display="none")};Mc(),(()=>{let{clearChatButton:c}=De;c&&c.addEventListener("click",()=>{$.clearMessages(),Ur.clear(),Wr(),wo(De.composerOverlay);try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(b){console.error("[AgentWidget] Failed to clear default localStorage:",b)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)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(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()})})(),Ht&&Ht.addEventListener("submit",L),ne==null||ne.addEventListener("keydown",Wt),ne==null||ne.addEventListener("input",tt),ne==null||ne.addEventListener("paste",gn);let kc=(Td=e.ownerDocument)!=null?Td:document;kc.addEventListener("keydown",$t,!0);let Lc="persona-attachment-drop-active",Zs=0,fl=()=>{Zs=0,V.classList.remove(Lc)},hs=()=>{var c;return((c=r.attachments)==null?void 0:c.enabled)===!0&&At!==null},Pc=c=>{!nl(c.dataTransfer)||!hs()||(Zs++,Zs===1&&V.classList.add(Lc))},Ic=c=>{!nl(c.dataTransfer)||!hs()||(Zs--,Zs<=0&&fl())},Rc=c=>{!nl(c.dataTransfer)||!hs()||(c.preventDefault(),c.dataTransfer.dropEffect="copy")},Wc=c=>{var b;if(!nl(c.dataTransfer)||!hs())return;c.preventDefault(),c.stopPropagation(),fl();let m=Array.from((b=c.dataTransfer.files)!=null?b:[]);m.length!==0&&At.handleFiles(m)},ho=!0;V.addEventListener("dragenter",Pc,ho),V.addEventListener("dragleave",Ic,ho),e.addEventListener("dragover",Rc,ho),e.addEventListener("drop",Wc,ho);let Qa=e.ownerDocument,Hc=c=>{hs()&&c.preventDefault()},Bc=c=>{hs()&&c.preventDefault()};Qa.addEventListener("dragover",Hc),Qa.addEventListener("drop",Bc),ft.push(()=>{Ht&&Ht.removeEventListener("submit",L),ne==null||ne.removeEventListener("keydown",Wt),ne==null||ne.removeEventListener("input",tt),ne==null||ne.removeEventListener("paste",gn),kc.removeEventListener("keydown",$t,!0)}),ft.push(()=>{V.removeEventListener("dragenter",Pc,ho),V.removeEventListener("dragleave",Ic,ho),e.removeEventListener("dragover",Rc,ho),e.removeEventListener("drop",Wc,ho),Qa.removeEventListener("dragover",Hc),Qa.removeEventListener("drop",Bc),fl()}),ft.push(()=>{$.cancel()}),on?ft.push(()=>{on==null||on.destroy()}):sn&&ft.push(()=>{sn==null||sn.remove()});let pn={update(c){var En,Wn,Br,vn,Hn,Bn,_o,ea,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,ru,ou,su,au,iu,lu,cu,du,pu,uu,mu,gu,fu,hu,bu,yu,xu,vu,wu,Cu,Au,Su,Tu,Eu,Mu,ku,Lu,Pu;let m=r.toolCall,b=r.messageActions,x=(En=r.layout)==null?void 0:En.messages,E=r.colorScheme,D=r.loadingIndicator,N=r.iterationDisplay,q=(Wn=r.features)==null?void 0:Wn.showReasoning,B=(Br=r.features)==null?void 0:Br.showToolCalls,xe=(vn=r.features)==null?void 0:vn.toolCallDisplay,me=(Hn=r.features)==null?void 0:Hn.reasoningDisplay;r={...r,...c},hr(),Ao(e,r),Ki(e,r),Gi(e,r),Jn(),r.colorScheme!==E&&lo();let te=Pa.getForInstance(r.plugins);o.length=0,o.push(...te),S=(_o=(Bn=r.launcher)==null?void 0:Bn.enabled)!=null?_o:!0,O=(Rd=(ea=r.launcher)==null?void 0:ea.autoExpand)!=null?Rd:!1,ze=(Hd=(Wd=r.features)==null?void 0:Wd.showReasoning)!=null?Hd:!0,Ae=(Dd=(Bd=r.features)==null?void 0:Bd.showToolCalls)!=null?Dd:!0,be=(Nd=(Od=r.features)==null?void 0:Od.scrollToBottom)!=null?Nd:{};let Ee=mt();Le=(_d=(Fd=r.features)==null?void 0:Fd.scrollBehavior)!=null?_d:{},Ee!==mt()&&(Wo(),Wr()),Mr(),$n();let $e=Re;if(Re=(Ud=($d=r.features)==null?void 0:$d.showEventStreamToggle)!=null?Ud:!1,Re&&!$e){if(ce||(X=new ka(de),ce=new Ma(re,X),ge=ge!=null?ge:new La,X.open().then(()=>ce==null?void 0:ce.restore()).catch(()=>{}),$.setSSEEventCallback((Q,Tt)=>{var jt;(jt=r.onSSEEvent)==null||jt.call(r,Q,Tt),ge==null||ge.processEvent(Q,Tt),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:Q,timestamp:Date.now(),payload:JSON.stringify(Tt)})})),!vt&&_e){let Q=(qd=(jd=r.features)==null?void 0:jd.eventStream)==null?void 0:qd.classNames,Tt="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"+(Q!=null&&Q.toggleButton?" "+Q.toggleButton:"");vt=h("button",Tt),vt.style.width="28px",vt.style.height="28px",vt.style.color=On.actionIconColor,vt.type="button",vt.setAttribute("aria-label","Event Stream"),vt.title="Event Stream";let jt=Ce("activity","18px","currentColor",1.5);jt&&vt.appendChild(jt);let ut=De.clearChatButtonWrapper,Rt=De.closeButtonWrapper,hn=ut||Rt;hn&&hn.parentNode===_e?_e.insertBefore(vt,hn):_e.appendChild(vt),vt.addEventListener("click",()=>{ae?fr():Nr()})}}else!Re&&$e&&(fr(),vt&&(vt.remove(),vt=null),ce==null||ce.clear(),X==null||X.destroy(),ce=null,X=null,ge==null||ge.reset(),ge=null);if(((zd=r.launcher)==null?void 0:zd.enabled)===!1&&on&&(on.destroy(),on=null),((Vd=r.launcher)==null?void 0:Vd.enabled)===!1&&sn&&(sn.remove(),sn=null),((Kd=r.launcher)==null?void 0:Kd.enabled)!==!1&&!on&&!sn){let Q=o.find(Tt=>Tt.renderLauncher);if(Q!=null&&Q.renderLauncher){let Tt=Q.renderLauncher({config:r,defaultRenderer:()=>Sa(r,fs).element,onToggle:fs});Tt&&(sn=Tt,e.appendChild(sn))}sn||(on=Sa(r,fs),e.appendChild(on.element))}on&&on.update(r),Oe&&((Gd=r.launcher)==null?void 0:Gd.title)!==void 0&&(Oe.textContent=r.launcher.title),Qe&&((Jd=r.launcher)==null?void 0:Jd.subtitle)!==void 0&&(Qe.textContent=r.launcher.subtitle);let Te=(Qd=r.layout)==null?void 0:Qd.header;if((Te==null?void 0:Te.layout)!==T&&_e){let Q=Te?Ps(r,Te,{showClose:F(),onClose:()=>Dt(!1,"user")}):eo({config:r,showClose:F(),onClose:()=>Dt(!1,"user")});_e.replaceWith(Q.header),_e=Q.header,pe=Q.iconHolder,Oe=Q.headerTitle,Qe=Q.headerSubtitle,H=Q.closeButton,T=Te==null?void 0:Te.layout}else if(Te&&(pe&&(pe.style.display=Te.showIcon===!1?"none":""),Oe&&(Oe.style.display=Te.showTitle===!1?"none":""),Qe&&(Qe.style.display=Te.showSubtitle===!1?"none":""),H&&(H.style.display=Te.showCloseButton===!1?"none":""),De.clearChatButtonWrapper)){let Q=Te.showClearChat;if(Q!==void 0){De.clearChatButtonWrapper.style.display=Q?"":"none";let{closeButtonWrapper:Tt}=De;Tt&&!Tt.classList.contains("persona-absolute")&&(Q?Tt.classList.remove("persona-ml-auto"):Tt.classList.add("persona-ml-auto"))}}let Ke=((Xd=r.layout)==null?void 0:Xd.showHeader)!==!1;_e&&(_e.style.display=Ke?"":"none");let dt=((Yd=r.layout)==null?void 0:Yd.showFooter)!==!1;Ue&&(Ue.style.display=dt?"":"none"),yn(),$n(),S!==R?S?Dt(O,"auto"):(M=!0,go()):O!==I&&Dt(O,"auto"),I=O,R=S,Ys(),Mc();let Pe=JSON.stringify(c.toolCall)!==JSON.stringify(m),qe=JSON.stringify(r.messageActions)!==JSON.stringify(b),Xe=JSON.stringify((Zd=r.layout)==null?void 0:Zd.messages)!==JSON.stringify(x),wt=((ep=r.loadingIndicator)==null?void 0:ep.render)!==(D==null?void 0:D.render)||((tp=r.loadingIndicator)==null?void 0:tp.renderIdle)!==(D==null?void 0:D.renderIdle)||((np=r.loadingIndicator)==null?void 0:np.showBubble)!==(D==null?void 0:D.showBubble),P=r.iterationDisplay!==N,Be=((op=(rp=r.features)==null?void 0:rp.showReasoning)!=null?op:!0)!==(q!=null?q:!0)||((ap=(sp=r.features)==null?void 0:sp.showToolCalls)!=null?ap:!0)!==(B!=null?B:!0)||JSON.stringify((ip=r.features)==null?void 0:ip.toolCallDisplay)!==JSON.stringify(xe)||JSON.stringify((lp=r.features)==null?void 0:lp.reasoningDisplay)!==JSON.stringify(me);(Pe||qe||Xe||wt||P||Be)&&$&&(Ns++,Ho(ot,$.getMessages(),ke));let he=(cp=r.launcher)!=null?cp:{},Ft=(dp=he.headerIconHidden)!=null?dp:!1,Ot=(up=(pp=r.layout)==null?void 0:pp.header)==null?void 0:up.showIcon,Jt=Ft||Ot===!1,Ct=he.headerIconName,zt=(mp=he.headerIconSize)!=null?mp:"48px";if(pe){let Q=V.querySelector(".persona-border-b-persona-divider"),Tt=Q==null?void 0:Q.querySelector(".persona-flex-col");if(Jt)pe.style.display="none",Q&&Tt&&!Q.contains(Tt)&&Q.insertBefore(Tt,Q.firstChild);else{if(pe.style.display="",pe.style.height=zt,pe.style.width=zt,Q&&Tt&&(Q.contains(pe)?pe.nextSibling!==Tt&&(pe.remove(),Q.insertBefore(pe,Tt)):Q.insertBefore(pe,Tt)),Ct){let ut=parseFloat(zt)||24,Rt=Ce(Ct,ut*.6,"#ffffff",2);Rt?pe.replaceChildren(Rt):pe.textContent=(gp=he.agentIconText)!=null?gp:"\u{1F4AC}"}else if(he.iconUrl){let ut=pe.querySelector("img");if(ut)ut.src=he.iconUrl,ut.style.height=zt,ut.style.width=zt;else{let Rt=document.createElement("img");Rt.src=he.iconUrl,Rt.alt="",Rt.className="persona-rounded-xl persona-object-cover",Rt.style.height=zt,Rt.style.width=zt,pe.replaceChildren(Rt)}}else{let ut=pe.querySelector("svg"),Rt=pe.querySelector("img");(ut||Rt)&&pe.replaceChildren(),pe.textContent=(fp=he.agentIconText)!=null?fp:"\u{1F4AC}"}let jt=pe.querySelector("img");jt&&(jt.style.height=zt,jt.style.width=zt)}}let Zn=(bp=(hp=r.layout)==null?void 0:hp.header)==null?void 0:bp.showTitle,ln=(xp=(yp=r.layout)==null?void 0:yp.header)==null?void 0:xp.showSubtitle;if(Oe&&(Oe.style.display=Zn===!1?"none":""),Qe&&(Qe.style.display=ln===!1?"none":""),H){((wp=(vp=r.layout)==null?void 0:vp.header)==null?void 0:wp.showCloseButton)===!1?H.style.display="none":H.style.display="";let Tt=(Cp=he.closeButtonSize)!=null?Cp:"32px",jt=(Ap=he.closeButtonPlacement)!=null?Ap:"inline";H.style.height=Tt,H.style.width=Tt;let{closeButtonWrapper:ut}=De,Rt=jt==="top-right",hn=ut==null?void 0:ut.classList.contains("persona-absolute");if(ut&&Rt!==hn)if(ut.remove(),Rt)ut.className="persona-absolute persona-top-4 persona-right-4 persona-z-50",V.style.position="relative",V.appendChild(ut);else{let gt=(Tp=(Sp=he.clearChat)==null?void 0:Sp.placement)!=null?Tp:"inline",bn=(Mp=(Ep=he.clearChat)==null?void 0:Ep.enabled)!=null?Mp:!0;ut.className=bn&>==="inline"?"":"persona-ml-auto";let Un=V.querySelector(".persona-border-b-persona-divider");Un&&Un.appendChild(ut)}if(H.style.color=he.closeButtonColor||On.actionIconColor,he.closeButtonBackgroundColor?(H.style.backgroundColor=he.closeButtonBackgroundColor,H.classList.remove("hover:persona-bg-gray-100")):(H.style.backgroundColor="",H.classList.add("hover:persona-bg-gray-100")),he.closeButtonBorderWidth||he.closeButtonBorderColor){let gt=he.closeButtonBorderWidth||"0px",bn=he.closeButtonBorderColor||"transparent";H.style.border=`${gt} solid ${bn}`,H.classList.remove("persona-border-none")}else H.style.border="",H.classList.add("persona-border-none");he.closeButtonBorderRadius?(H.style.borderRadius=he.closeButtonBorderRadius,H.classList.remove("persona-rounded-full")):(H.style.borderRadius="",H.classList.add("persona-rounded-full")),he.closeButtonPaddingX?(H.style.paddingLeft=he.closeButtonPaddingX,H.style.paddingRight=he.closeButtonPaddingX):(H.style.paddingLeft="",H.style.paddingRight=""),he.closeButtonPaddingY?(H.style.paddingTop=he.closeButtonPaddingY,H.style.paddingBottom=he.closeButtonPaddingY):(H.style.paddingTop="",H.style.paddingBottom="");let Mn=(kp=he.closeButtonIconName)!=null?kp:"x",Cr=(Lp=he.closeButtonIconText)!=null?Lp:"\xD7";H.innerHTML="";let Dn=Ce(Mn,"28px","currentColor",1);Dn?H.appendChild(Dn):H.textContent=Cr;let an=(Pp=he.closeButtonTooltipText)!=null?Pp:"Close chat",tr=(Ip=he.closeButtonShowTooltip)!=null?Ip:!0;if(H.setAttribute("aria-label",an),ut&&(ut._cleanupTooltip&&(ut._cleanupTooltip(),delete ut._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!H)return;let $o=H.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=H.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};ut.addEventListener("mouseenter",bn),ut.addEventListener("mouseleave",Un),H.addEventListener("focus",bn),H.addEventListener("blur",Un),ut._cleanupTooltip=()=>{Un(),ut&&(ut.removeEventListener("mouseenter",bn),ut.removeEventListener("mouseleave",Un)),H&&(H.removeEventListener("focus",bn),H.removeEventListener("blur",Un))}}}let{clearChatButton:Ye,clearChatButtonWrapper:It}=De;if(Ye){let Q=(Rp=he.clearChat)!=null?Rp:{},Tt=(Wp=Q.enabled)!=null?Wp:!0,jt=(Bp=(Hp=r.layout)==null?void 0:Hp.header)==null?void 0:Bp.showClearChat,ut=jt!==void 0?jt:Tt,Rt=(Dp=Q.placement)!=null?Dp:"inline";if(It){It.style.display=ut?"":"none";let{closeButtonWrapper:hn}=De;!_()&&hn&&!hn.classList.contains("persona-absolute")&&(ut?hn.classList.remove("persona-ml-auto"):hn.classList.add("persona-ml-auto"));let Mn=Rt==="top-right",Cr=It.classList.contains("persona-absolute");if(!_()&&Mn!==Cr&&ut){if(It.remove(),Mn)It.className="persona-absolute persona-top-4 persona-z-50",It.style.right="48px",V.style.position="relative",V.appendChild(It);else{It.className="persona-relative persona-ml-auto persona-clear-chat-button-wrapper",It.style.right="";let an=V.querySelector(".persona-border-b-persona-divider"),tr=De.closeButtonWrapper;an&&tr&&tr.parentElement===an?an.insertBefore(It,tr):an&&an.appendChild(It)}let Dn=De.closeButtonWrapper;Dn&&!Dn.classList.contains("persona-absolute")&&(Mn?Dn.classList.add("persona-ml-auto"):Dn.classList.remove("persona-ml-auto"))}}if(ut){if(!_()){let gt=(Op=Q.size)!=null?Op:"32px";Ye.style.height=gt,Ye.style.width=gt}let hn=(Np=Q.iconName)!=null?Np:"refresh-cw",Mn=(Fp=Q.iconColor)!=null?Fp:"";Ye.style.color=Mn||On.actionIconColor,Ye.innerHTML="";let Cr=_()?"14px":"20px",Dn=Ce(hn,Cr,"currentColor",2);if(Dn&&Ye.appendChild(Dn),Q.backgroundColor?(Ye.style.backgroundColor=Q.backgroundColor,Ye.classList.remove("hover:persona-bg-gray-100")):(Ye.style.backgroundColor="",Ye.classList.add("hover:persona-bg-gray-100")),Q.borderWidth||Q.borderColor){let gt=Q.borderWidth||"0px",bn=Q.borderColor||"transparent";Ye.style.border=`${gt} solid ${bn}`,Ye.classList.remove("persona-border-none")}else Ye.style.border="",Ye.classList.add("persona-border-none");Q.borderRadius?(Ye.style.borderRadius=Q.borderRadius,Ye.classList.remove("persona-rounded-full")):(Ye.style.borderRadius="",Ye.classList.add("persona-rounded-full")),Q.paddingX?(Ye.style.paddingLeft=Q.paddingX,Ye.style.paddingRight=Q.paddingX):(Ye.style.paddingLeft="",Ye.style.paddingRight=""),Q.paddingY?(Ye.style.paddingTop=Q.paddingY,Ye.style.paddingBottom=Q.paddingY):(Ye.style.paddingTop="",Ye.style.paddingBottom="");let an=(_p=Q.tooltipText)!=null?_p:"Clear chat",tr=($p=Q.showTooltip)!=null?$p:!0;if(Ye.setAttribute("aria-label",an),It&&(It._cleanupTooltip&&(It._cleanupTooltip(),delete It._cleanupTooltip),tr&&an)){let gt=null,bn=()=>{if(gt||!Ye)return;let $o=Ye.ownerDocument,ta=$o.body;if(!ta)return;gt=Dr($o,"div","persona-clear-chat-tooltip"),gt.textContent=an;let na=Dr($o,"div");na.className="persona-clear-chat-tooltip-arrow",gt.appendChild(na);let Uo=Ye.getBoundingClientRect();gt.style.position="fixed",gt.style.zIndex=String(So),gt.style.left=`${Uo.left+Uo.width/2}px`,gt.style.top=`${Uo.top-8}px`,gt.style.transform="translate(-50%, -100%)",ta.appendChild(gt)},Un=()=>{gt&>.parentNode&&(gt.parentNode.removeChild(gt),gt=null)};It.addEventListener("mouseenter",bn),It.addEventListener("mouseleave",Un),Ye.addEventListener("focus",bn),Ye.addEventListener("blur",Un),It._cleanupTooltip=()=>{Un(),It&&(It.removeEventListener("mouseenter",bn),It.removeEventListener("mouseleave",Un)),Ye&&(Ye.removeEventListener("focus",bn),Ye.removeEventListener("blur",Un))}}}}let un=r.actionParsers&&r.actionParsers.length?r.actionParsers:[Ia],ur=r.actionHandlers&&r.actionHandlers.length?r.actionHandlers:[rs.message,rs.messageAndClick];w=Ra({parsers:un,handlers:ur,getSessionMetadata:f,updateSessionMetadata:g,emit:s.emit,documentRef:typeof document!="undefined"?document:null}),ke=Ag(r,w,oe),$.updateConfig(r),Ho(ot,$.getMessages(),ke),as(),Bo(),ms($.isStreaming());let er=((Up=r.voiceRecognition)==null?void 0:Up.enabled)===!0,Do=typeof window!="undefined"&&(typeof window.webkitSpeechRecognition!="undefined"||typeof window.SpeechRecognition!="undefined"),Oo=((qp=(jp=r.voiceRecognition)==null?void 0:jp.provider)==null?void 0:qp.type)==="runtype";if(er&&(Do||Oo))if(!G||!xt){let Q=uf(r.voiceRecognition,r.sendButton);Q&&(G=Q.micButton,xt=Q.micButtonWrapper,Kt.insertBefore(xt,Nn),G.addEventListener("click",Ja),G.disabled=$.isStreaming())}else{let Q=(zp=r.voiceRecognition)!=null?zp:{},Tt=(Vp=r.sendButton)!=null?Vp:{},jt=(Kp=Q.iconName)!=null?Kp:"mic",ut=(Gp=Tt.size)!=null?Gp:"40px",Rt=(Jp=Q.iconSize)!=null?Jp:ut,hn=parseFloat(Rt)||24;G.style.width=Rt,G.style.height=Rt,G.style.minWidth=Rt,G.style.minHeight=Rt;let Mn=(Xp=(Qp=Q.iconColor)!=null?Qp:Tt.textColor)!=null?Xp:"currentColor";G.innerHTML="";let Cr=Ce(jt,hn,Mn,2);Cr?G.appendChild(Cr):G.textContent="\u{1F3A4}";let Dn=(Yp=Q.backgroundColor)!=null?Yp:Tt.backgroundColor;Dn?G.style.backgroundColor=Dn:G.style.backgroundColor="",Mn?G.style.color=Mn:G.style.color="var(--persona-text, #111827)",Q.borderWidth?(G.style.borderWidth=Q.borderWidth,G.style.borderStyle="solid"):(G.style.borderWidth="",G.style.borderStyle=""),Q.borderColor?G.style.borderColor=Q.borderColor:G.style.borderColor="",Q.paddingX?(G.style.paddingLeft=Q.paddingX,G.style.paddingRight=Q.paddingX):(G.style.paddingLeft="",G.style.paddingRight=""),Q.paddingY?(G.style.paddingTop=Q.paddingY,G.style.paddingBottom=Q.paddingY):(G.style.paddingTop="",G.style.paddingBottom="");let an=xt==null?void 0:xt.querySelector(".persona-send-button-tooltip"),tr=(Zp=Q.tooltipText)!=null?Zp:"Start voice recognition";if(((eu=Q.showTooltip)!=null?eu:!1)&&tr)if(an)an.textContent=tr,an.style.display="";else{let bn=document.createElement("div");bn.className="persona-send-button-tooltip",bn.textContent=tr,xt==null||xt.insertBefore(bn,G)}else an&&(an.style.display="none");xt.style.display="",G.disabled=$.isStreaming()}else G&&xt&&(xt.style.display="none",((nu=(tu=r.voiceRecognition)==null?void 0:tu.provider)==null?void 0:nu.type)==="runtype"?$.isVoiceActive()&&$.toggleVoice():ht&&xn());if(((ru=r.attachments)==null?void 0:ru.enabled)===!0)if(!we||!lt){let Q=(ou=r.attachments)!=null?ou:{},jt=(au=((su=r.sendButton)!=null?su:{}).size)!=null?au:"40px";nt||(nt=h("div","persona-attachment-previews persona-flex persona-flex-wrap persona-gap-2 persona-mb-2"),nt.style.display="none",Ht.insertBefore(nt,ne)),le||(le=document.createElement("input"),le.type="file",le.accept=((iu=Q.allowedTypes)!=null?iu:Yr).join(","),le.multiple=((lu=Q.maxFiles)!=null?lu:4)>1,le.style.display="none",le.setAttribute("aria-label","Attach files"),Ht.insertBefore(le,ne)),we=h("div","persona-send-button-wrapper"),lt=h("button","persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer persona-attachment-button"),lt.type="button",lt.setAttribute("aria-label",(cu=Q.buttonTooltipText)!=null?cu:"Attach file");let ut=(du=Q.buttonIconName)!=null?du:"paperclip",Rt=jt,hn=parseFloat(Rt)||40,Mn=Math.round(hn*.6);lt.style.width=Rt,lt.style.height=Rt,lt.style.minWidth=Rt,lt.style.minHeight=Rt,lt.style.fontSize="18px",lt.style.lineHeight="1",lt.style.backgroundColor="transparent",lt.style.color="var(--persona-primary, #111827)",lt.style.border="none",lt.style.borderRadius="6px",lt.style.transition="background-color 0.15s ease",lt.addEventListener("mouseenter",()=>{lt.style.backgroundColor="var(--persona-palette-colors-black-alpha-50, rgba(0, 0, 0, 0.05))"}),lt.addEventListener("mouseleave",()=>{lt.style.backgroundColor="transparent"});let Cr=Ce(ut,Mn,"currentColor",1.5);Cr?lt.appendChild(Cr):lt.textContent="\u{1F4CE}",lt.addEventListener("click",tr=>{tr.preventDefault(),le==null||le.click()}),we.appendChild(lt);let Dn=(pu=Q.buttonTooltipText)!=null?pu:"Attach file",an=h("div","persona-send-button-tooltip");an.textContent=Dn,we.appendChild(an),Pt.append(we),!At&&le&&nt&&(At=Yo.fromConfig(Q),At.setPreviewsContainer(nt),le.addEventListener("change",async()=>{At&&(le!=null&&le.files)&&(await At.handleFileSelect(le.files),le.value="")})),V.querySelector(".persona-attachment-drop-overlay")||V.appendChild(Sg(Q.dropOverlay))}else{we.style.display="";let Q=(uu=r.attachments)!=null?uu:{};le&&(le.accept=((mu=Q.allowedTypes)!=null?mu:Yr).join(","),le.multiple=((gu=Q.maxFiles)!=null?gu:4)>1),At&&At.updateConfig({allowedTypes:Q.allowedTypes,maxFileSize:Q.maxFileSize,maxFiles:Q.maxFiles})}else we&&(we.style.display="none"),At&&At.clearAttachments(),(fu=V.querySelector(".persona-attachment-drop-overlay"))==null||fu.remove();let Xt=(hu=r.sendButton)!=null?hu:{},No=(bu=Xt.useIcon)!=null?bu:!1,bo=(yu=Xt.iconText)!=null?yu:"\u2191",yo=Xt.iconName,Kr=(xu=Xt.tooltipText)!=null?xu:"Send message",Fo=(vu=Xt.showTooltip)!=null?vu:!1,wr=(wu=Xt.size)!=null?wu:"40px",rt=Xt.backgroundColor,fn=Xt.textColor;if(No){if(Ve.style.width=wr,Ve.style.height=wr,Ve.style.minWidth=wr,Ve.style.minHeight=wr,Ve.style.fontSize="18px",Ve.style.lineHeight="1",Ve.innerHTML="",fn?Ve.style.color=fn:Ve.style.color="var(--persona-button-primary-fg, #ffffff)",yo){let Q=parseFloat(wr)||24,Tt=(fn==null?void 0:fn.trim())||"currentColor",jt=Ce(yo,Q,Tt,2);jt?Ve.appendChild(jt):Ve.textContent=bo}else Ve.textContent=bo;Ve.className="persona-rounded-button persona-flex persona-items-center persona-justify-center disabled:persona-opacity-50 persona-cursor-pointer",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-primary")):(Ve.style.backgroundColor="",Ve.classList.add("persona-bg-persona-primary"))}else Ve.textContent=(Au=(Cu=r.copy)==null?void 0:Cu.sendButtonLabel)!=null?Au:"Send",Ve.style.width="",Ve.style.height="",Ve.style.minWidth="",Ve.style.minHeight="",Ve.style.fontSize="",Ve.style.lineHeight="",Ve.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",rt?(Ve.style.backgroundColor=rt,Ve.classList.remove("persona-bg-persona-accent")):Ve.classList.add("persona-bg-persona-accent"),fn?Ve.style.color=fn:Ve.classList.add("persona-text-white");Xt.borderWidth?(Ve.style.borderWidth=Xt.borderWidth,Ve.style.borderStyle="solid"):(Ve.style.borderWidth="",Ve.style.borderStyle=""),Xt.borderColor?Ve.style.borderColor=Xt.borderColor:Ve.style.borderColor="",Xt.paddingX?(Ve.style.paddingLeft=Xt.paddingX,Ve.style.paddingRight=Xt.paddingX):(Ve.style.paddingLeft="",Ve.style.paddingRight=""),Xt.paddingY?(Ve.style.paddingTop=Xt.paddingY,Ve.style.paddingBottom=Xt.paddingY):(Ve.style.paddingTop="",Ve.style.paddingBottom="");let Ut=Nn==null?void 0:Nn.querySelector(".persona-send-button-tooltip");if(Fo&&Kr)if(Ut)Ut.textContent=Kr,Ut.style.display="";else{let Q=document.createElement("div");Q.className="persona-send-button-tooltip",Q.textContent=Kr,Nn==null||Nn.insertBefore(Q,Ve)}else Ut&&(Ut.style.display="none");let _t=(ku=(Su=r.layout)==null?void 0:Su.contentMaxWidth)!=null?ku:_()?(Mu=(Eu=(Tu=r.launcher)==null?void 0:Tu.composerBar)==null?void 0:Eu.contentMaxWidth)!=null?Mu:"720px":void 0;_t?(ot.style.maxWidth=_t,ot.style.marginLeft="auto",ot.style.marginRight="auto",ot.style.width="100%",Ht&&(Ht.style.maxWidth=_t,Ht.style.marginLeft="auto",Ht.style.marginRight="auto"),Et&&(Et.style.maxWidth=_t,Et.style.marginLeft="auto",Et.style.marginRight="auto")):(ot.style.maxWidth="",ot.style.marginLeft="",ot.style.marginRight="",ot.style.width="",Ht&&(Ht.style.maxWidth="",Ht.style.marginLeft="",Ht.style.marginRight=""),Et&&(Et.style.maxWidth="",Et.style.marginLeft="",Et.style.marginRight=""));let bt=(Lu=r.statusIndicator)!=null?Lu:{},Yt=(Pu=bt.visible)!=null?Pu:!0;if(cn.style.display=Yt?"":"none",$){let Q=$.getStatus();Ze(cn,(jt=>{var ut,Rt,hn,Mn;return jt==="idle"?(ut=bt.idleText)!=null?ut:kn.idle:jt==="connecting"?(Rt=bt.connectingText)!=null?Rt:kn.connecting:jt==="connected"?(hn=bt.connectedText)!=null?hn:kn.connected:jt==="error"?(Mn=bt.errorText)!=null?Mn:kn.error:kn[jt]})(Q),bt,Q)}cn.classList.remove("persona-text-left","persona-text-center","persona-text-right");let kt=bt.align==="left"?"persona-text-left":bt.align==="center"?"persona-text-center":"persona-text-right";cn.classList.add(kt)},open(){F()&&Dt(!0,"api")},close(){F()&&Dt(!1,"api")},toggle(){F()&&Dt(!M,"api")},clearChat(){In=!1,$.clearMessages(),Ur.clear(),Wr();try{localStorage.removeItem(Os),r.debug&&console.log(`[AgentWidget] Cleared default localStorage key: ${Os}`)}catch(m){console.error("[AgentWidget] Failed to clear default localStorage:",m)}if(r.clearChatHistoryStorageKey&&r.clearChatHistoryStorageKey!==Os)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(),ce==null||ce.clear(),ge==null||ge.reset(),K==null||K.update()},setMessage(c){return!ne||$.isStreaming()?!1:(!M&&F()&&Dt(!0,"system"),ne.value=c,ne.dispatchEvent(new Event("input",{bubbles:!0})),!0)},submitMessage(c){if($.isStreaming())return!1;let m=(c==null?void 0:c.trim())||ne.value.trim();return m?(!M&&F()&&Dt(!0,"system"),ne.value="",ne.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()||(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),$.toggleVoice().then(()=>{yt.active=$.isVoiceActive(),dr("user"),$.isVoiceActive()&&Xs()})),!0):ht?!0:Cn()?(!M&&F()&&Dt(!0,"system"),yt.manuallyDeactivated=!1,_n(),Qt("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(()=>{yt.active=!1,yt.manuallyDeactivated=!0,_n(),dr("user"),fo()}),!0):!1:ht?(yt.manuallyDeactivated=!0,_n(),xn("user"),!0):!1},injectMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectMessage(c)},injectAssistantMessage(c){!M&&F()&&Dt(!0,"system");let m=$.injectAssistantMessage(c);return j&&(j=!1,z&&(clearTimeout(z),z=null),setTimeout(()=>{$&&!$.isStreaming()&&$.continueConversation()},100)),m},injectUserMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectUserMessage(c)},injectSystemMessage(c){return!M&&F()&&Dt(!0,"system"),$.injectSystemMessage(c)},injectMessageBatch(c){return!M&&F()&&Dt(!0,"system"),$.injectMessageBatch(c)},injectComponentDirective(c){return!M&&F()&&Dt(!0,"system"),$.injectComponentDirective(c)},injectTestMessage(c){!M&&F()&&Dt(!0,"system"),$.injectTestEvent(c)},async connectStream(c,m){return $.connectStream(c,m)},__pushEventStreamEvent(c){ce&&(ge==null||ge.processEvent(c.type,c.payload),ce.push({id:`evt-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,type:c.type,timestamp:Date.now(),payload:JSON.stringify(c.payload)}))},showEventStream(){!Re||!ce||Nr()},hideEventStream(){ae&&fr()},isEventStreamVisible(){return ae},showArtifacts(){gr(r)&&(In=!1,Jn(),St==null||St.setMobileOpen(!0))},hideArtifacts(){gr(r)&&(In=!0,Jn())},upsertArtifact(c){return gr(r)?(In=!1,$.upsertArtifact(c)):null},selectArtifact(c){gr(r)&&$.selectArtifact(c)},clearArtifacts(){gr(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 S&&!M&&!_()||!ne?!1:(ne.focus(),!0)},async resolveApproval(c,m,b){let E=$.getMessages().find(D=>{var N;return D.variant==="approval"&&((N=D.approval)==null?void 0:N.id)===c});if(!(E!=null&&E.approval))throw new Error(`Approval not found: ${c}`);if(E.approval.toolType==="webmcp"){$.resolveWebMcpApproval(E.id,m);return}return $.resolveApproval(E.approval,m,b)},getMessages(){return $.getMessages()},getStatus(){return $.getStatus()},getPersistentMetadata(){return{...d}},updatePersistentMetadata(c){g(c)},on(c,m){return s.on(c,m)},off(c,m){s.off(c,m)},isOpen(){return F()&&M},isVoiceActive(){return yt.active},getState(){return{open:F()&&M,launcherEnabled:S,voiceActive:yt.active,streaming:$.isStreaming()}},showCSATFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=el({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitCSATFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.appendChild(b),b.scrollIntoView({behavior:"smooth",block:"end"})},showNPSFeedback(c){!M&&F()&&Dt(!0,"system");let m=ot.querySelector(".persona-feedback-container");m&&m.remove();let b=tl({onSubmit:async(x,E)=>{var D;$.isClientTokenMode()&&await $.submitNPSFeedback(x,E),(D=c==null?void 0:c.onSubmit)==null||D.call(c,x,E)},onDismiss:c==null?void 0:c.onDismiss,...c});ot.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(){je!=null&&(clearInterval(je),je=null),ft.forEach(c=>c()),ve.remove(),Je==null||Je.remove(),on==null||on.destroy(),sn==null||sn.remove(),cr&&H.removeEventListener("click",cr)}};if((((Ed=n==null?void 0:n.debugTools)!=null?Ed:!1)||!!r.debug)&&typeof window!="undefined"){let c=window.AgentWidgetBrowser,m={controller:pn,getMessages:pn.getMessages,getStatus:pn.getStatus,getMetadata:pn.getPersistentMetadata,updateMetadata:pn.updatePersistentMetadata,clearHistory:()=>pn.clearChat(),setVoiceActive:b=>b?pn.startVoiceRecognition():pn.stopVoiceRecognition()};window.AgentWidgetBrowser=m,ft.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=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.focusInput()};if(window.addEventListener("persona:focusInput",m),ft.push(()=>{window.removeEventListener("persona:focusInput",m)}),Re){let q=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.showEventStream()},B=xe=>{let me=xe.detail;(!(me!=null&&me.instanceId)||me.instanceId===c)&&pn.hideEventStream()};window.addEventListener("persona:showEventStream",q),window.addEventListener("persona:hideEventStream",B),ft.push(()=>{window.removeEventListener("persona:showEventStream",q),window.removeEventListener("persona:hideEventStream",B)})}let b=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.showArtifacts()},x=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.hideArtifacts()},E=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||B!=null&&B.artifact&&pn.upsertArtifact(B.artifact)},D=q=>{let B=q.detail;B!=null&&B.instanceId&&B.instanceId!==c||typeof(B==null?void 0:B.id)=="string"&&pn.selectArtifact(B.id)},N=q=>{let B=q.detail;(!(B!=null&&B.instanceId)||B.instanceId===c)&&pn.clearArtifacts()};window.addEventListener("persona:showArtifacts",b),window.addEventListener("persona:hideArtifacts",x),window.addEventListener("persona:upsertArtifact",E),window.addEventListener("persona:selectArtifact",D),window.addEventListener("persona:clearArtifacts",N),ft.push(()=>{window.removeEventListener("persona:showArtifacts",b),window.removeEventListener("persona:hideArtifacts",x),window.removeEventListener("persona:upsertArtifact",E),window.removeEventListener("persona:selectArtifact",D),window.removeEventListener("persona:clearArtifacts",N)})}let pr=qb(r.persistState);if(pr&&F()){let c=zb(pr.storage),m=`${pr.keyPrefix}widget-open`,b=`${pr.keyPrefix}widget-voice`,x=`${pr.keyPrefix}widget-voice-mode`;if(c){let E=((Md=pr.persist)==null?void 0:Md.openState)&&c.getItem(m)==="true",D=((kd=pr.persist)==null?void 0:kd.voiceState)&&c.getItem(b)==="true",N=((Ld=pr.persist)==null?void 0:Ld.voiceState)&&c.getItem(x)==="true";if(E&&setTimeout(()=>{pn.open(),setTimeout(()=>{var q;if(D||N)pn.startVoiceRecognition();else if((q=pr.persist)!=null&&q.focusInput){let B=e.querySelector("textarea");B&&B.focus()}},100)},0),(Pd=pr.persist)!=null&&Pd.openState&&(s.on("widget:opened",()=>{c.setItem(m,"true")}),s.on("widget:closed",()=>{c.setItem(m,"false")})),(Id=pr.persist)!=null&&Id.voiceState&&(s.on("voice:state",q=>{c.setItem(b,q.active?"true":"false")}),s.on("user:message",q=>{c.setItem(x,q.viaVoice?"true":"false")})),pr.clearOnChatClear){let q=()=>{c.removeItem(m),c.removeItem(b),c.removeItem(x)},B=()=>q();window.addEventListener("persona:clear-chat",B),ft.push(()=>{window.removeEventListener("persona:clear-chat",B)})}}}return p&&F()&&setTimeout(()=>{pn.open()},0),Vr(),pn};var Vb=(e,t)=>{let n=e.trim(),r=/^(\d+(?:\.\d+)?)px$/i.exec(n);if(r)return Math.max(0,parseFloat(r[1]));let o=/^(\d+(?:\.\d+)?)%$/i.exec(n);return o?Math.max(0,t*parseFloat(o[1])/100):420},Kb=(e,t)=>{if(t===!1){e.style.maxHeight="";return}e.style.maxHeight="100vh",e.style.maxHeight=t},Gb=(e,t)=>{t===!1?(e.style.position="relative",e.style.top=""):(e.style.position="sticky",e.style.top="0")},Jb=(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 o=r.offsetHeight>0;r.style.height="100%";let s=r.offsetHeight>0;r.remove(),!(!o||s)&&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.")},Tg=(e,t)=>{var r,o;let n=(o=(r=t==null?void 0:t.launcher)==null?void 0:r.enabled)!=null?o:!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"},ic=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=""},Eg=e=>{e.style.inset="",e.style.width="",e.style.height="",e.style.maxWidth="",e.style.maxHeight="",e.style.minWidth="",ic(e)},oc=e=>{e.style.transition=""},sc=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=""},ac=e=>{e.style.width="",e.style.maxWidth="",e.style.minWidth="",e.style.flex="1 1 auto"},ol=(e,t)=>{e.style.width="",e.style.minWidth="",e.style.maxWidth="",e.style.boxSizing="",t.style.alignItems=""},Qb=(e,t,n,r,o)=>{o?n.parentElement!==t&&(e.replaceChildren(),t.replaceChildren(n,r),e.appendChild(t)):n.parentElement===t&&(t.replaceChildren(),e.appendChild(n),e.appendChild(r))},Xb=(e,t,n,r,o,s)=>{let a=s?t:e;o==="left"?a.firstElementChild!==r&&a.replaceChildren(r,n):a.lastElementChild!==r&&a.replaceChildren(n,r)},Mg=(e,t,n,r,o,s,a)=>{var v,y,w,S,O,k;let i=rr(s),d=i.reveal==="push";Qb(e,t,n,r,d),Xb(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",o.className="persona-host",o.style.height="100%",o.style.minHeight="0",o.style.display="flex",o.style.flexDirection="column",o.style.flex="1 1 auto";let l=e.ownerDocument.defaultView,p=(y=(v=s==null?void 0:s.launcher)==null?void 0:v.mobileFullscreen)!=null?y:!0,u=(S=(w=s==null?void 0:s.launcher)==null?void 0:w.mobileBreakpoint)!=null?S:640,f=l!=null?l.innerWidth<=u:!1;if(p&&f&&a){e.dataset.personaDockMobileFullscreen="true",e.removeAttribute("data-persona-dock-reveal"),sc(t),oc(r),Eg(r),ac(n),ol(o,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((k=(O=s==null?void 0:s.launcher)==null?void 0:O.zIndex)!=null?k:Ln),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"),Eg(r),Kb(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",sc(t),oc(r),ac(n),ol(o,r);let I=i.animate?"transform 180ms ease":"none",R=i.side==="right"?"translateX(100%)":"translateX(-100%)",T=a?"translateX(0)":R;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=I,r.style.transform=T,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",oc(r),ic(r),ol(o,r);let I=Vb(i.width,e.clientWidth),R=Math.max(0,e.clientWidth),T=i.animate?"margin-left 180ms ease":"none",W=i.side==="right"?a?-I:0:a?0:-I;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=`${R+I}px`,t.style.transition=T,t.style.marginLeft=`${W}px`,t.style.transform="",n.style.flex="0 0 auto",n.style.flexGrow="0",n.style.flexShrink="0",n.style.width=`${R}px`,n.style.maxWidth=`${R}px`,n.style.minWidth=`${R}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="",sc(t),ic(r),ac(n),ol(o,r);let I=i.reveal==="emerge";I?e.dataset.personaDockReveal="emerge":e.removeAttribute("data-persona-dock-reveal");let R=a?i.width:"0px",T=i.animate?"width 180ms ease, min-width 180ms ease, max-width 180ms ease, flex-basis 180ms ease":"none",W=!a;r.style.display="flex",r.style.flexDirection="column",r.style.flex=`0 0 ${R}`,r.style.width=R,r.style.maxWidth=R,r.style.minWidth=R,r.style.minHeight="0",Gb(r,i.maxHeight),r.style.overflow=I||W?"hidden":"visible",r.style.transition=T,I&&(r.style.alignItems=i.side==="right"?"flex-start":"flex-end",o.style.width=i.width,o.style.minWidth=i.width,o.style.maxWidth=i.width,o.style.boxSizing="border-box")}},Yb=(e,t)=>{let n=e.ownerDocument.createElement("div");return Tg(n,t),e.appendChild(n),{mode:"direct",host:n,shell:null,syncWidgetState:()=>{},updateConfig(r){Tg(n,r)},destroy(){n.remove()}}},Zb=(e,t)=>{var k,I,R,T;let{ownerDocument:n}=e,r=e.parentElement;if(!r)throw new Error("Docked widget target must be attached to the DOM");let o=e.tagName.toUpperCase();if(o==="BODY"||o==="HTML")throw new Error('Docked widget target must be a concrete container element, not "body" or "html"');let s=e.nextSibling,a=n.createElement("div"),i=n.createElement("div"),d=n.createElement("div"),l=n.createElement("aside"),p=n.createElement("div"),u=(I=(k=t==null?void 0:t.launcher)==null?void 0:k.enabled)==null||I?(T=(R=t==null?void 0:t.launcher)==null?void 0:R.autoExpand)!=null?T:!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(),rr(t).reveal==="push"&&typeof ResizeObserver!="undefined"&&(f=new ResizeObserver(()=>{Mg(a,i,d,l,p,t,u)}),f.observe(a))},y=!1,w=()=>{Mg(a,i,d,l,p,t,u),v(),u&&!y&&a.dataset.personaDockMobileFullscreen!=="true"&&(y=!0,Jb(a,rr(t)))},S=a.ownerDocument.defaultView,O=()=>{w()};return S==null||S.addEventListener("resize",O),rr(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(W){let _=W.launcherEnabled?W.open:!0;u!==_&&(u=_,w())},updateConfig(W){var _,F;t=W,((F=(_=t==null?void 0:t.launcher)==null?void 0:_.enabled)!=null?F:!0)===!1&&(u=!0),w()},destroy(){S==null||S.removeEventListener("resize",O),g(),r.isConnected&&(s&&s.parentNode===r?r.insertBefore(e,s):r.appendChild(e)),a.remove()}}},Wa=(e,t)=>mn(t)?Zb(e,t):Yb(e,t);var lc={},kg=!1,ey=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},ty=()=>{try{if(typeof lc!="undefined"&&lc.url)return new URL("../widget.css",lc.url).href}catch{}return null},Lg=(e,t)=>{let n=ty(),r=()=>{if(!(e instanceof ShadowRoot)||e.querySelector("link[data-persona]"))return;let o=t.head.querySelector("link[data-persona]");if(!o)return;let s=o.cloneNode(!0);e.insertBefore(s,e.firstChild)};if(e instanceof ShadowRoot)if(n){let o=t.createElement("link");o.rel="stylesheet",o.href=n,o.setAttribute("data-persona","true"),e.insertBefore(o,e.firstChild)}else r();else if(!t.head.querySelector("link[data-persona]")&&n){let s=t.createElement("link");s.rel="stylesheet",s.href=n,s.setAttribute("data-persona","true"),t.head.appendChild(s)}},cc=e=>{let t=ey(e.target),n=e.useShadowDom===!0,r=t.ownerDocument,o=e.config,s=Wa(t,o),a,i=[],d=(w,S)=>{var R,T;let k=!((T=(R=S==null?void 0:S.launcher)==null?void 0:R.enabled)!=null?T:!0)||mn(S),I=r.createElement("div");if(I.setAttribute("data-persona-root","true"),k&&(I.style.height="100%",I.style.display="flex",I.style.flexDirection="column",I.style.flex="1",I.style.minHeight="0"),n){let W=w.attachShadow({mode:"open"});W.appendChild(I),Lg(W,r)}else w.appendChild(I),Lg(w,r);return t.id&&I.setAttribute("data-persona-instance",t.id),I},l=()=>{s.syncWidgetState(a.getState())},p=()=>{i.forEach(w=>w()),i=[a.on("widget:opened",l),a.on("widget:closed",l)],l()},u=()=>{let w=d(s.host,o);a=rl(w,o,{debugTools:e.debugTools}),p()},f=()=>{i.forEach(w=>w()),i=[],a.destroy()};u(),e.onChatReady?e.onChatReady():e.onReady&&(kg||(kg=!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(),s.destroy(),s=Wa(t,w),o=w,u()},v={update(w){var T,W,_,F,M,j;let S={...o,...w,launcher:{...(T=o==null?void 0:o.launcher)!=null?T:{},...(W=w==null?void 0:w.launcher)!=null?W:{},dock:{...(F=(_=o==null?void 0:o.launcher)==null?void 0:_.dock)!=null?F:{},...(j=(M=w==null?void 0:w.launcher)==null?void 0:M.dock)!=null?j:{}}}},O=mn(o),k=mn(S),I=Eo(o),R=Eo(S);if(O!==k||I!==R){g(S);return}o=S,s.updateConfig(o),a.update(w),l()},destroy(){f(),s.destroy(),e.windowKey&&typeof window!="undefined"&&delete window[e.windowKey]}},y=new Proxy(v,{get(w,S,O){if(S==="host")return s.host;if(S in w)return Reflect.get(w,S,O);let k=a[S];return typeof k=="function"?k.bind(a):k}});return e.windowKey&&typeof window!="undefined"&&(window[e.windowKey]=y),y};var Hg=new Set(["script","style","noscript","svg","path","meta","link","br","hr"]),ny=new Set(["button","a","input","select","textarea","details","summary"]),ry=new Set(["button","link","menuitem","tab","option","switch","checkbox","radio","combobox","listbox","slider","spinbutton","textbox"]),dc=/\b(product|card|item|listing|result)\b/i,uc=/\$[\d,]+(?:\.\d{2})?|€[\d,]+(?:\.\d{2})?|£[\d,]+(?:\.\d{2})?|USD\s*[\d,]+(?:\.\d{2})?/i,oy=3e3,sy=100;function Bg(e){let t=typeof e.className=="string"?e.className:"";if(dc.test(t)||e.id&&dc.test(e.id))return!0;for(let n=0;n<e.attributes.length;n++){let r=e.attributes[n];if(r.name.startsWith("data-")&&dc.test(r.value))return!0}return!1}function Dg(e){var t;return uc.test(((t=e.textContent)!=null?t:"").trim())}function Og(e){var n;let t=e.querySelectorAll("a[href]");for(let r=0;r<t.length;r++){let o=(n=t[r].getAttribute("href"))!=null?n:"";if(o&&o!=="#"&&!o.toLowerCase().startsWith("javascript:"))return!0}return!1}function ay(e){return!!e.querySelector('button, [role="button"], input[type="submit"], input[type="button"]')}function Pg(e){let t=e.match(uc);return t?t[0]:null}function Ig(e){var r,o,s;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&&((o=t.textContent)!=null&&o.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(s=n==null?void 0:n.textContent)!=null&&s.trim()?{title:n.textContent.trim(),href:null}:{title:"",href:null}}function iy(e){let t=[],n=r=>{let o=r.trim();o&&!t.includes(o)&&t.push(o)};return e.querySelectorAll("button").forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('[role="button"]').forEach(r=>{var o;return n((o=r.textContent)!=null?o:"")}),e.querySelectorAll('input[type="submit"], input[type="button"]').forEach(r=>{var o;n((o=r.value)!=null?o:"")}),t.slice(0,6)}var ly="commerce-card",cy="result-card";function Rg(e){return!Bg(e)||!Dg(e)||!Og(e)&&!ay(e)?0:5200}function Wg(e){var r;return!Bg(e)||Dg(e)||!Og(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 mc=[{id:ly,scoreElement(e){return Rg(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||uc.test(r)&&r.length<32)}return!0},formatSummary(e,t){var d,l,p;if(Rg(e)===0)return null;let{title:n,href:r}=Ig(e),o=(p=(l=Pg(((d=e.textContent)!=null?d:"").trim()))!=null?l:Pg(t.text))!=null?p:"",s=iy(e);return[r&&n?`[${n}](${r})${o?` \u2014 ${o}`:""}`:n?`${n}${o?` \u2014 ${o}`:""}`:o||t.text.trim().slice(0,120),`selector: ${t.selector}`,s.length?`actions: ${s.join(", ")}`:""].filter(Boolean).join(`
|
|
108
108
|
`)}},{id:cy,scoreElement(e){return Wg(e)},formatSummary(e,t){if(Wg(e)===0)return null;let{title:n,href:r}=Ig(e);return[r&&n?`[${n}](${r})`:n||t.text.trim().slice(0,120),`selector: ${t.selector}`].filter(Boolean).join(`
|
|
109
109
|
`)}}];function dy(){typeof console!="undefined"&&typeof console.warn=="function"&&console.warn('[persona] collectEnrichedPageContext: options.mode is "simple" but `rules` were provided; rules are ignored.')}function py(e){var p,u,f,g,v,y,w,S,O,k,I,R,T;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",o=(w=(y=t.maxTextLength)!=null?y:e.maxTextLength)!=null?w:200,s=(O=(S=t.visibleOnly)!=null?S:e.visibleOnly)!=null?O:!0,a=(k=t.root)!=null?k:e.root,i=(I=t.mode)!=null?I:"structured",d=(R=t.maxCandidates)!=null?R:Math.max(500,n*10),l=(T=e.rules)!=null?T:mc;return i==="simple"&&e.rules&&e.rules.length>0?(dy(),l=[]):i==="simple"&&(l=[]),{mode:i,maxElements:n,maxCandidates:d,excludeSelector:r,maxTextLength:o,visibleOnly:s,root:a,rules:l}}function pc(e){return typeof CSS!="undefined"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/([^\w-])/g,"\\$1")}var uy=["data-testid","data-product","data-action","data-id","data-name","data-type"];function my(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"||ny.has(t)||n&&ry.has(n)||e.hasAttribute("tabindex")||e.hasAttribute("onclick")||e.getAttribute("contenteditable")==="true"?"clickable":"static"}function Ng(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 gy(e){let t={},n=e.id;n&&(t.id=n);let r=e.getAttribute("href");r&&(t.href=r);let o=e.getAttribute("aria-label");o&&(t["aria-label"]=o);let s=e.getAttribute("type");s&&(t.type=s);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 gc(e){let t=e.tagName.toLowerCase();if(e.id){let o=`#${pc(e.id)}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}}for(let o of uy){let s=e.getAttribute(o);if(s){let a=`${t}[${o}="${pc(s)}"]`;try{if(e.ownerDocument.querySelectorAll(a).length===1)return a}catch{}}}let n=Array.from(e.classList).filter(o=>o&&!o.startsWith("persona-")).slice(0,3);if(n.length>0){let o=`${t}.${n.map(a=>pc(a)).join(".")}`;try{if(e.ownerDocument.querySelectorAll(o).length===1)return o}catch{}let s=e.parentElement;if(s){let i=Array.from(s.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(i>=0){let d=`${o}:nth-of-type(${i+1})`;try{if(e.ownerDocument.querySelectorAll(d).length===1)return d}catch{}}}}let r=e.parentElement;if(r){let s=Array.from(r.querySelectorAll(`:scope > ${t}`)).indexOf(e);if(s>=0)return`${t}:nth-of-type(${s+1})`}return t}function fy(e){return e==="static"?sy:oy}function Fg(e,t){var o;let n=e.tagName.toLowerCase(),r=((o=e.textContent)!=null?o:"").trim().substring(0,t);return{selector:gc(e),tagName:n,text:r,role:e.getAttribute("role"),interactivity:my(e),attributes:gy(e)}}function hy(e,t,n,r){let o=fy(t.interactivity),s=null;for(let a of n){let i=a.scoreElement(e,t,r);i>0&&(o+=i,a.formatSummary&&!s&&(s=a))}return{score:o,formattingRule:s}}function by(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 yy(e,t){let n={doc:t.ownerDocument,maxTextLength:e.maxTextLength},r=new Set,o=[],s=0,a=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),i=a.currentNode;for(;i&&o.length<e.maxCandidates;){if(i.nodeType===Node.ELEMENT_NODE){let l=i,p=l.tagName.toLowerCase();if(Hg.has(p)){i=a.nextNode();continue}if(e.excludeSelector)try{if(l.closest(e.excludeSelector)){i=a.nextNode();continue}}catch{}if(e.visibleOnly&&!Ng(l)){i=a.nextNode();continue}let u=Fg(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}=hy(l,u,e.rules,n);o.push({el:l,domIndex:s,enriched:u,score:v,formattingRule:y}),s+=1}i=a.nextNode()}o.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 o){if(d.length>=e.maxElements)break;by(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 xy(e,t){let n=[],r=new Set,o=document.createTreeWalker(t,NodeFilter.SHOW_ELEMENT,null),s=o.currentNode;for(;s&&n.length<e.maxElements;){if(s.nodeType===Node.ELEMENT_NODE){let d=s,l=d.tagName.toLowerCase();if(Hg.has(l)){s=o.nextNode();continue}if(e.excludeSelector)try{if(d.closest(e.excludeSelector)){s=o.nextNode();continue}}catch{}if(e.visibleOnly&&!Ng(d)){s=o.nextNode();continue}let p=Fg(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){s=o.nextNode();continue}r.has(p.selector)||(r.add(p.selector),n.push(p))}s=o.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 _g(e={}){var r;let t=py(e),n=(r=t.root)!=null?r:document.body;return n?t.mode==="simple"?xy(t,n):yy(t,n):[]}var sl=100;function $g(e,t={}){var s;if(e.length===0)return"No page elements found.";let n=(s=t.mode)!=null?s:"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 Ug="3.
|
|
123
|
+
`)}var Ug="3.34.1";var os=Ug;function jg(){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 qg(){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 zg(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:Or(e.colors.primary,.95),100:Or(e.colors.primary,.9),200:Or(e.colors.primary,.8),300:Or(e.colors.primary,.7),400:Or(e.colors.primary,.6),500:e.colors.primary,600:Or(e.colors.primary,.8),700:Or(e.colors.primary,.7),800:Or(e.colors.primary,.6),900:Or(e.colors.primary,.5),950:Or(e.colors.primary,.45)}}),{...t,palette:n}}}}function Vg(){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 Kg(){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 Or(e,t){let n=parseInt(e.slice(1,3),16),r=parseInt(e.slice(3,5),16),o=parseInt(e.slice(5,7),16),s=Math.round(n+(255-n)*(1-t)),a=Math.round(r+(255-r)*(1-t)),i=Math.round(o+(255-o)*(1-t));return`#${s.toString(16).padStart(2,"0")}${a.toString(16).padStart(2,"0")}${i.toString(16).padStart(2,"0")}`}function Gg(e){return{name:e.name,version:e.version,transform:e.transform||(t=>t),cssVariables:e.cssVariables,afterResolve:e.afterResolve}}var wy={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"}}},Jg={components:{panel:{borderRadius:"0",shadow:"none"}}},fc={id:"shop",label:"Shopping Assistant",config:{theme:wy,launcher:{title:"Shopping Assistant",subtitle:"Here to help you find what you need",agentIconText:"\u{1F6CD}\uFE0F",position:"bottom-right",width:nr},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?"]}},hc={id:"minimal",label:"Minimal",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},messages:{layout:"minimal"}},theme:Jg}},bc={id:"fullscreen",label:"Fullscreen Assistant",config:{launcher:{enabled:!1,fullHeight:!0},layout:{header:{layout:"minimal",showCloseButton:!1},contentMaxWidth:"72ch"},theme:Jg}},yc={shop:fc,minimal:hc,fullscreen:bc};function Qg(e){return yc[e]}var Xg=cc;function no(e){if(e!==void 0)return typeof e=="string"?e:Array.isArray(e)?`[${e.map(t=>t.toString()).join(", ")}]`:e.toString()}function Cy(e){if(e)return{getHeaders:no(e.getHeaders),onFeedback:no(e.onFeedback),onCopy:no(e.onCopy),requestMiddleware:no(e.requestMiddleware),actionHandlers:no(e.actionHandlers),actionParsers:no(e.actionParsers),postprocessMessage:no(e.postprocessMessage),contextProviders:no(e.contextProviders),streamParser:no(e.streamParser)}}var Yg=`({ 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
|